forked from strongloop/loopback
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.js
572 lines (519 loc) · 17.6 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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
/*!
* Module Dependencies.
*/
var loopback = require('../../lib/loopback');
var path = require('path');
var SALT_WORK_FACTOR = 10;
var crypto = require('crypto');
var bcrypt = require('bcryptjs');
var DEFAULT_TTL = 1209600; // 2 weeks in seconds
var DEFAULT_RESET_PW_TTL = 15 * 60; // 15 mins in seconds
var DEFAULT_MAX_TTL = 31556926; // 1 year in seconds
var assert = require('assert');
var debug = require('debug')('loopback:user');
/**
* Built-in User model.
* Extends LoopBack [PersistedModel](#persistedmodel-new-persistedmodel).
*
* Default `User` ACLs.
*
* - DENY EVERYONE `*`
* - ALLOW EVERYONE `create`
* - ALLOW OWNER `deleteById`
* - ALLOW EVERYONE `login`
* - ALLOW EVERYONE `logout`
* - ALLOW EVERYONE `findById`
* - ALLOW OWNER `updateAttributes`
*
* @property {String} username Must be unique
* @property {String} password Hidden from remote clients
* @property {String} email Must be valid email
* @property {Boolean} emailVerified Set when a user's email has been verified via `confirm()`
* @property {String} verificationToken Set when `verify()` is called
*
* @class User
* @inherits {PersistedModel}
*/
module.exports = function(User) {
/**
* Create access token for the logged in user. This method can be overridden to
* customize how access tokens are generated
*
* @param {Number} ttl The requested ttl
* @callack {Function} cb The callback function
* @param {String|Error} err The error string or object
* @param {AccessToken} token The generated access token object
*/
User.prototype.createAccessToken = function(ttl, cb) {
var userModel = this.constructor;
ttl = Math.min(ttl || userModel.settings.ttl, userModel.settings.maxTTL);
this.accessTokens.create({
ttl: ttl
}, cb);
};
function splitPrincipal(name, realmDelimiter) {
var parts = [null, name];
if (!realmDelimiter) {
return parts;
}
var index = name.indexOf(realmDelimiter);
if (index !== -1) {
parts[0] = name.substring(0, index);
parts[1] = name.substring(index + realmDelimiter.length);
}
return parts;
}
/**
* Normalize the credentials
* @param {Object} credentials The credential object
* @param {Boolean} realmRequired
* @param {String} realmDelimiter The realm delimiter, if not set, no realm is needed
* @returns {Object} The normalized credential object
*/
User.normalizeCredentials = function(credentials, realmRequired, realmDelimiter) {
var query = {};
credentials = credentials || {};
if (!realmRequired) {
if (credentials.email) {
query.email = credentials.email;
} else if (credentials.username) {
query.username = credentials.username;
}
} else {
if (credentials.realm) {
query.realm = credentials.realm;
}
var parts;
if (credentials.email) {
parts = splitPrincipal(credentials.email, realmDelimiter);
query.email = parts[1];
if (parts[0]) {
query.realm = parts[0];
}
} else if (credentials.username) {
parts = splitPrincipal(credentials.username, realmDelimiter);
query.username = parts[1];
if (parts[0]) {
query.realm = parts[0];
}
}
}
return query;
};
/**
* Login a user by with the given `credentials`.
*
* ```js
* User.login({username: 'foo', password: 'bar'}, function (err, token) {
* console.log(token.id);
* });
* ```
*
* @param {Object} credentials username/password or email/password
* @param {String[]|String} [include] Optionally set it to "user" to include
* the user info
* @callback {Function} callback Callback function
* @param {Error} err Error object
* @param {AccessToken} token Access token if login is successful
*/
User.login = function(credentials, include, fn) {
var self = this;
if (typeof include === 'function') {
fn = include;
include = undefined;
}
include = (include || '');
if (Array.isArray(include)) {
include = include.map(function(val) {
return val.toLowerCase();
});
} else {
include = include.toLowerCase();
}
var realmDelimiter;
// Check if realm is required
var realmRequired = !!(self.settings.realmRequired ||
self.settings.realmDelimiter);
if (realmRequired) {
realmDelimiter = self.settings.realmDelimiter;
}
var query = self.normalizeCredentials(credentials, realmRequired,
realmDelimiter);
if (realmRequired && !query.realm) {
var err1 = new Error('realm is required');
err1.statusCode = 400;
return fn(err1);
}
if (!query.email && !query.username) {
var err2 = new Error('username or email is required');
err2.statusCode = 400;
return fn(err2);
}
self.findOne({where: query}, function(err, user) {
var defaultError = new Error('login failed');
defaultError.statusCode = 401;
if (err) {
debug('An error is reported from User.findOne: %j', err);
fn(defaultError);
} else if (user) {
if (self.settings.emailVerificationRequired) {
if (!user.emailVerified) {
// Fail to log in if email verification is not done yet
debug('User email has not been verified');
err = new Error('login failed as the email has not been verified');
err.statusCode = 401;
return fn(err);
}
}
user.hasPassword(credentials.password, function(err, isMatch) {
if (err) {
debug('An error is reported from User.hasPassword: %j', err);
fn(defaultError);
} else if (isMatch) {
user.createAccessToken(credentials.ttl, function(err, token) {
if (err) return fn(err);
if (Array.isArray(include) ? include.indexOf('user') !== -1 : include === 'user') {
// NOTE(bajtos) We can't set token.user here:
// 1. token.user already exists, it's a function injected by
// "AccessToken belongsTo User" relation
// 2. ModelBaseClass.toJSON() ignores own properties, thus
// the value won't be included in the HTTP response
// See also loopback#161 and loopback#162
token.__data.user = user;
}
fn(err, token);
});
} else {
debug('The password is invalid for user %s', query.email || query.username);
fn(defaultError);
}
});
} else {
debug('No matching record is found for user %s', query.email || query.username);
fn(defaultError);
}
});
};
/**
* Logout a user with the given accessToken id.
*
* ```js
* User.logout('asd0a9f8dsj9s0s3223mk', function (err) {
* console.log(err || 'Logged out');
* });
* ```
*
* @param {String} accessTokenID
* @callback {Function} callback
* @param {Error} err
*/
User.logout = function(tokenId, fn) {
this.relations.accessTokens.modelTo.findById(tokenId, function(err, accessToken) {
if (err) {
fn(err);
} else if (accessToken) {
accessToken.destroy(fn);
} else {
fn(new Error('could not find accessToken'));
}
});
};
/**
* Compare the given `password` with the users hashed password.
*
* @param {String} password The plain text password
* @returns {Boolean}
*/
User.prototype.hasPassword = function(plain, fn) {
if (this.password && plain) {
bcrypt.compare(plain, this.password, function(err, isMatch) {
if (err) return fn(err);
fn(null, isMatch);
});
} else {
fn(null, false);
}
};
/**
* Verify a user's identity by sending them a confirmation email.
*
* ```js
* var options = {
* type: 'email',
* to: user.email,
* template: 'verify.ejs',
* redirect: '/'
* };
*
* user.verify(options, next);
* ```
*
* @options {Object} options
* @property {String} type Must be 'email'.
* @property {String} to Email address to which verification email is sent.
* @property {String} from Sender email addresss, for example
* `'[email protected]'`.
* @property {String} subject Subject line text.
* @property {String} text Text of email.
* @property {String} template Name of template that displays verification
* page, for example, `'verify.ejs'.
* @property {String} redirect Page to which user will be redirected after
* they verify their email, for example `'/'` for root URI.
*/
User.prototype.verify = function(options, fn) {
var user = this;
var userModel = this.constructor;
assert(typeof options === 'object', 'options required when calling user.verify()');
assert(options.type, 'You must supply a verification type (options.type)');
assert(options.type === 'email', 'Unsupported verification type');
assert(options.to || this.email, 'Must include options.to when calling user.verify() or the user must have an email property');
assert(options.from, 'Must include options.from when calling user.verify() or the user must have an email property');
options.redirect = options.redirect || '/';
options.template = path.resolve(options.template || path.join(__dirname, '..', '..', 'templates', 'verify.ejs'));
options.user = this;
options.protocol = options.protocol || 'http';
var app = userModel.app;
options.host = options.host || (app && app.get('host')) || 'localhost';
options.port = options.port || (app && app.get('port')) || 3000;
options.restApiRoot = options.restApiRoot || (app && app.get('restApiRoot')) || '/api';
options.verifyHref = options.verifyHref ||
options.protocol +
'://' +
options.host +
':' +
options.port +
options.restApiRoot +
userModel.http.path +
userModel.confirm.http.path +
'?uid=' +
options.user.id +
'&redirect=' +
options.redirect;
// Email model
var Email = options.mailer || this.constructor.email || loopback.getModelByType(loopback.Email);
crypto.randomBytes(64, function(err, buf) {
if (err) {
fn(err);
} else {
user.verificationToken = buf.toString('hex');
user.save(function(err) {
if (err) {
fn(err);
} else {
sendEmail(user);
}
});
}
});
// TODO - support more verification types
function sendEmail(user) {
options.verifyHref += '&token=' + user.verificationToken;
options.text = options.text || 'Please verify your email by opening this link in a web browser:\n\t{href}';
options.text = options.text.replace('{href}', options.verifyHref);
var template = loopback.template(options.template);
Email.send({
to: options.to || user.email,
from: options.from,
subject: options.subject || 'Thanks for Registering',
text: options.text,
html: template(options),
headers: options.headers || {}
}, function(err, email) {
if (err) {
fn(err);
} else {
fn(null, {email: email, token: user.verificationToken, uid: user.id});
}
});
}
};
/**
* Confirm the user's identity.
*
* @param {Any} userId
* @param {String} token The validation token
* @param {String} redirect URL to redirect the user to once confirmed
* @callback {Function} callback
* @param {Error} err
*/
User.confirm = function(uid, token, redirect, fn) {
this.findById(uid, function(err, user) {
if (err) {
fn(err);
} else {
if (user && user.verificationToken === token) {
user.verificationToken = undefined;
user.emailVerified = true;
user.save(function(err) {
if (err) {
fn(err);
} else {
fn();
}
});
} else {
if (user) {
err = new Error('Invalid token: ' + token);
err.statusCode = 400;
} else {
err = new Error('User not found: ' + uid);
err.statusCode = 404;
}
fn(err);
}
}
});
};
/**
* Create a short lived acess token for temporary login. Allows users
* to change passwords if forgotten.
*
* @options {Object} options
* @prop {String} email The user's email address
* @callback {Function} callback
* @param {Error} err
*/
User.resetPassword = function(options, cb) {
var UserModel = this;
var ttl = UserModel.settings.resetPasswordTokenTTL || DEFAULT_RESET_PW_TTL;
options = options || {};
if (typeof options.email === 'string') {
UserModel.findOne({ where: {email: options.email} }, function(err, user) {
if (err) {
cb(err);
} else if (user) {
// create a short lived access token for temp login to change password
// TODO(ritch) - eventually this should only allow password change
user.accessTokens.create({ttl: ttl}, function(err, accessToken) {
if (err) {
cb(err);
} else {
cb();
UserModel.emit('resetPasswordRequest', {
email: options.email,
accessToken: accessToken,
user: user
});
}
});
} else {
cb();
}
});
} else {
var err = new Error('email is required');
err.statusCode = 400;
cb(err);
}
};
/*!
* Setup an extended user model.
*/
User.setup = function() {
// We need to call the base class's setup method
User.base.setup.call(this);
var UserModel = this;
// max ttl
this.settings.maxTTL = this.settings.maxTTL || DEFAULT_MAX_TTL;
this.settings.ttl = DEFAULT_TTL;
UserModel.setter.password = function(plain) {
var salt = bcrypt.genSaltSync(this.constructor.settings.saltWorkFactor || SALT_WORK_FACTOR);
this.$password = bcrypt.hashSync(plain, salt);
};
// Make sure emailVerified is not set by creation
UserModel.beforeRemote('create', function(ctx, user, next) {
var body = ctx.req.body;
if (body && body.emailVerified) {
body.emailVerified = false;
}
next();
});
loopback.remoteMethod(
UserModel.login,
{
description: 'Login a user with username/email and password',
accepts: [
{arg: 'credentials', type: 'object', required: true, http: {source: 'body'}},
{arg: 'include', type: 'string', http: {source: 'query' },
description: 'Related objects to include in the response. ' +
'See the description of return value for more details.'}
],
returns: {
arg: 'accessToken', type: 'object', root: true,
description:
'The response body contains properties of the AccessToken created on login.\n' +
'Depending on the value of `include` parameter, the body may contain ' +
'additional properties:\n\n' +
' - `user` - `{User}` - Data of the currently logged in user. (`include=user`)\n\n'
},
http: {verb: 'post'}
}
);
loopback.remoteMethod(
UserModel.logout,
{
description: 'Logout a user with access token',
accepts: [
{arg: 'access_token', type: 'string', required: true, http: function(ctx) {
var req = ctx && ctx.req;
var accessToken = req && req.accessToken;
var tokenID = accessToken && accessToken.id;
return tokenID;
}, description: 'Do not supply this argument, it is automatically extracted ' +
'from request headers.'
}
],
http: {verb: 'all'}
}
);
loopback.remoteMethod(
UserModel.confirm,
{
description: 'Confirm a user registration with email verification token',
accepts: [
{arg: 'uid', type: 'string', required: true},
{arg: 'token', type: 'string', required: true},
{arg: 'redirect', type: 'string', required: true}
],
http: {verb: 'get', path: '/confirm'}
}
);
loopback.remoteMethod(
UserModel.resetPassword,
{
description: 'Reset password for a user with email',
accepts: [
{arg: 'options', type: 'object', required: true, http: {source: 'body'}}
],
http: {verb: 'post', path: '/reset'}
}
);
UserModel.on('attached', function() {
UserModel.afterRemote('confirm', function(ctx, inst, next) {
if (ctx.req) {
ctx.res.redirect(ctx.req.param('redirect'));
} else {
next(new Error('transport unsupported'));
}
});
});
// default models
assert(loopback.Email, 'Email model must be defined before User model');
UserModel.email = loopback.Email;
assert(loopback.AccessToken, 'AccessToken model must be defined before User model');
UserModel.accessToken = loopback.AccessToken;
// email validation regex
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
UserModel.validatesFormatOf('email', {with: re, message: 'Must provide a valid email'});
// FIXME: We need to add support for uniqueness of composite keys in juggler
if (!(UserModel.settings.realmRequired || UserModel.settings.realmDelimiter)) {
UserModel.validatesUniquenessOf('email', {message: 'Email already exists'});
UserModel.validatesUniquenessOf('username', {message: 'User already exists'});
}
return UserModel;
};
/*!
* Setup the base user.
*/
User.setup();
};