forked from Someguy123/LiteVault
-
Notifications
You must be signed in to change notification settings - Fork 4
/
user.js
372 lines (348 loc) · 15.2 KB
/
user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
var crypto = require('crypto')
, Blockr = require('./helpers/blockr-api')
, mysql = require('./config.js')
, s = require('speakeasy');
function createUserString() {
var bytes = crypto.randomBytes(16).toString('hex');
return bytes.slice(0, 7) +
"-" + bytes.slice(8, 16) +
"-" + bytes.slice(17, 24) +
"-" + bytes.slice(25, 32);
}
function db_error(message) {
if (message === void 0) { message = "There was a database error! Please contact an administrator immediately"}
return {
"error": {"type": "DB_ERROR", "message":message}
};
}
var User = (function() {
function User(req) {
this.req = req;
// If email was submitted as the identifier then load identifier from db
req.body.identifier
}
User.prototype.read_user_settings = function(identifier, callback) {
var mysqlString = "";
if (identifier && typeof identifier === "string" && identifier.includes("@")){
mysqlString = 'SELECT setting, value, shared_key, identifier FROM user_settings INNER JOIN users ON users.email = user_settings.email WHERE users.email = ?';
} else {
mysqlString = 'SELECT setting, value, shared_key FROM user_settings INNER JOIN users ON users.identifier = user_settings.identifier WHERE users.identifier = ?';
}
mysql.query(mysqlString, [identifier], function(err, rows) {
if(err) {
console.log(err);
callback(err);
}
var settings = {};
if(rows.length > 0) {
for(var row in rows) {
if(rows.hasOwnProperty(row)) {
settings[rows[row]['setting']] = rows[row]['value'];
}
}
}
callback(false, settings)
});
};
User.prototype.getIdentifierFromEmail = function(emailAddress, callback){
mysql.query('SELECT * FROM users WHERE email = ?', emailAddress, function(err, rows) {
if(err) {
console.log(err);
callback(err);
}
if(rows.length > 0) {
// false (noError), false (notUnique)
callback(false, rows[0].identifier);
} else {
// false (noError), true (unique)
callback(true, "No Identifier Matches Email");
}
});
};
User.prototype.getIdentifier = function(identifier, callback){
if (identifier && typeof identifier == "string" && identifier.includes("@")){
this.getIdentifierFromEmail(identifier, function(err, identifier){
if (err){
console.log(identifier);
return;
}
callback(identifier);
})
} else {
callback(identifier);
}
};
User.prototype.checkUniqueEmail = function(emailAddress, callback){
mysql.query('SELECT * FROM users WHERE email = ?', emailAddress, function(err, rows) {
if(err) {
console.log(err);
callback(err);
}
var settings = {};
if(rows.length > 0) {
// false (noError), false (notUnique)
callback(false, false);
} else {
// false (noError), true (unique)
callback(false, true);
}
});
};
User.prototype.create = function(callback) {
var createAndFinish = function(req){
var identifier = createUserString();
var data = {};
var wallet = {
identifier: identifier,
shared_key: crypto.randomBytes(48).toString('hex'),
wallet_data: "",
created_at: Math.floor(new Date() / 1000),
last_update: Math.floor(new Date() / 1000),
created_ip_address: req.ip,
last_ip_address: req.ip,
email: ('email' in req.body) ? req.body.email : null
};
mysql.query('INSERT INTO users SET ?', wallet, function(err, rows) {
if(err) {
console.log(err);
callback(db_error());
}
data.identifier = identifier;
data.shared_key = wallet.shared_key;
data.error = false;
callback(data);
});
}
if (this.req && this.req.body && this.req.body.email){
var request = this.req;
this.checkUniqueEmail(this.req.body.email, function(err, unique){
if (err){
callback({error: true, errorText: err });
return;
}
if (unique){
createAndFinish(request);
} else {
callback({error: true, errorText: "Please provide a unique email"});
}
})
} else {
createAndFinish(this.req);
}
};
User.prototype.genAuthKey = function(identifier, expires, callback) {
var data = {
identifier: identifier,
expires: expires,
user_agent: this.req.headers['user-agent'],
auth_key: crypto.randomBytes(64).toString('hex')
};
mysql.query('INSERT INTO user_authkeys SET ?', data, function(err, rows) {
if(err){
callback(db_error());
}
callback(false, data.auth_key);
});
};
User.prototype.tryGauth = function(identifier, token, is_trusted, callback) {
var _this = this;
this.read_user_settings(identifier,
function(err, settings) {
if(err){
console.log(err);
callback(db_error());
}
if('gauth_enabled' in settings && (settings['gauth_enabled'] == 'true')) {
var expected_key = s.totp({key: settings['gauth_secret'], encoding: 'base32'});
if(expected_key === token) {
// 1 week if trusted, 2 hours if not
var expiration_time = (is_trusted == "true")
? Math.floor(new Date() / 1000) + (60 * 60 * 24 * 7)
: Math.floor(new Date() / 1000) + (60 * 60 * 2);
_this.genAuthKey(identifier, expiration_time, function(err, auth_key) {
if(err) {
callback(err);
}
callback({error: false, data: {auth_key: auth_key, expires: expiration_time}});
});
} else {
callback({error: {type: "WRONG_TOKEN", message: "The token you provided is wrong. " +
"You may need to try again in about 10 seconds because " +
"these tokens are time based"}});
}
} else {
callback({error: {type: "NO_GAUTH", message: "Google Authenticator was not found for this identifier"}});
}
}
);
};
User.prototype.setGauth = function(identifier, token, secret, shared_key, callback) {
var _this = this;
mysql.query('SELECT * FROM users WHERE identifier = ?', [identifier], function(err, rows) {
if(rows.length > 0) {
var row = rows[0];
if(row.shared_key === shared_key) {
var expected_key = s.totp({key: secret, encoding: 'base32'});
if(token === expected_key) {
var q1 = "INSERT INTO user_settings (`identifier`, `setting`, `value`) VALUES (?, 'gauth_enabled', 'true') ON DUPLICATE KEY UPDATE `value` = 'true'; ";
var q2 = "INSERT INTO user_settings (`identifier`, `setting`, `value`) VALUES (?, 'gauth_secret', ?) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);";
var combined = mysql.format(q1 + q2, [
identifier,
identifier,
secret
]);
//console.log(combined);
mysql.query(combined, function(err, rows) {
if(err) {
console.log(err);
callback(db_error())
}
var expires = Math.floor(new Date() / 1000) + (60 * 60 * 24 * 7);
_this.genAuthKey(identifier, expires, function(err, auth_key) {
if(err) {
console.log(err);
callback(db_error())
}
callback({error: false, data: {message: "successfully set token", auth_key: auth_key, expires: expires}});
});
});
} else {
callback({
error: {
type: "WRONG_TOKEN",
message: "The token you provided is wrong. " +
"You may need to try again in about 10 seconds because " +
"these tokens are time based"
}
});
}
}
}
});
};
User.prototype.check2FA = function (res, identifier, callback, fail_callback) {
var req = this.req;
this.read_user_settings(identifier, function(err, settings) {
if(err) {
res.json(db_error());
}
if (settings && ('gauth_enabled' in settings) && settings.gauth_enabled === 'true') {
//console.log(req.cookies);
if('auth_key' in req.cookies) {
//console.log('in cookies');
mysql.query('SELECT * FROM user_authkeys WHERE identifier=? AND auth_key=?', [identifier, req.cookies.auth_key], function(err, rows) {
if(rows.length > 0) {
var row = rows[0];
if(parseInt(row.expires) < Math.floor(new Date() / 1000)) {
// 2FA enabled, but their authkey recently expired
if (fail_callback === void 0) {
res.json(
{
error: {
type: "AUTH_KEY_EXPIRED",
message: "Your 2FA authentication token has expired. You'll need to login again using your 2FA Authenticator such as Google Authenticator."
}
}
);
}else{
fail_callback();
}
} else {
// 2FA enabled, and they're authorized
callback();
}
} else {
//console.log('not in db');
// 2FA enabled, there's a cookie, but it's not in our DB
if (fail_callback === void 0) {
res.json({error: {type: "2FA_ENABLED", message: "2FA is enabled for this account, but you're not authenticated."}});
} else {
fail_callback();
}
}
});
} else {
// 2FA enabled, but no cookie
if (fail_callback === void 0) {
res.json({error: {type: "2FA_ENABLED", message: "2FA is enabled for this account, but you're not authenticated."}});
} else {
fail_callback();
}
}
} else {
// if they don't have 2FA enabled, we run the callback normally
callback();
}
});
};
User.prototype.updateEmail = function(identifier, shared_key, email, callback) {
mysql.query('SELECT * FROM users WHERE identifier = ?', [identifier], function(err, rows) {
if(err) {
callback(db_error());
}
if (rows.length > 0) {
var row = rows[0];
if (row.shared_key === shared_key) {
this.checkUniqueEmail(email, function(err, unique){
if (unique){
mysql.query('UPDATE users SET email = ? WHERE identifier = ?', [email, identifier], function(err, rows) {
if(err) {
callback(db_error());
} else {
callback({error: false})
}
});
} else {
callback({error: {
"type": "EMAIL_NOT_UNIQUE",
"message": "Unable to update email, please provide an email address that is not already in use."
}})
}
})
} else {
callback({error: {
"type": "INVALID_SHAREDKEY",
"message": "Fatal Error: Shared Key does not match wallet, update aborted"
}})
}
} else {
callback({error: {
"type": "WALLET_NOT_FOUND",
"message": "There is no wallet with that identifier"
}
})
}
});
};
User.prototype.readAccount = function(identifier, shared_key, callback) {
mysql.query('SELECT * FROM users WHERE identifier = ?', [identifier], function(err, rows) {
if(err) {
callback(db_error());
}
if (rows.length > 0) {
var row = rows[0];
if (row.shared_key === shared_key) {
callback({error: false,
data:
{
email: rows[0].email
}
});
} else {
callback({error: {
"type": "INVALID_SHAREDKEY",
"message": "Fatal Error: Shared Key does not match wallet, update aborted"
}})
}
} else {
callback({error: {
"type": "WALLET_NOT_FOUND",
"message": "There is no wallet with that identifier"
}
})
}
});
};
return User;
})();
module.exports = User;