-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathuser.js
1417 lines (1277 loc) · 47.4 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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright IBM Corp. 2014,2018. All Rights Reserved.
// Node module: loopback
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
/*!
* Module Dependencies.
*/
'use strict';
var g = require('../../lib/globalize');
var isEmail = require('isemail');
var loopback = require('../../lib/loopback');
var utils = require('../../lib/utils');
var path = require('path');
var qs = require('querystring');
var SALT_WORK_FACTOR = 10;
var crypto = require('crypto');
// bcrypt's max length is 72 bytes;
// See https://github.com/kelektiv/node.bcrypt.js/blob/45f498ef6dc6e8234e58e07834ce06a50ff16352/src/node_blf.h#L59
var MAX_PASSWORD_LENGTH = 72;
var bcrypt;
try {
// Try the native module first
bcrypt = require('bcrypt');
// Browserify returns an empty object
if (bcrypt && typeof bcrypt.compare !== 'function') {
bcrypt = require('bcryptjs');
}
} catch (err) {
// Fall back to pure JS impl
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 OWNER `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.
* @property {String} realm The namespace the user belongs to. See [Partitioning users with realms](http://loopback.io/doc/en/lb2/Partitioning-users-with-realms.html) for details.
* @property {Object} settings Extends the `Model.settings` object.
* @property {Boolean} settings.emailVerificationRequired Require the email verification
* process before allowing a login.
* @property {Number} settings.ttl Default time to live (in seconds) for the `AccessToken` created by `User.login() / user.createAccessToken()`.
* Default is `1209600` (2 weeks)
* @property {Number} settings.maxTTL The max value a user can request a token to be alive / valid for.
* Default is `31556926` (1 year)
* @property {Boolean} settings.realmRequired Require a realm when logging in a user.
* @property {String} settings.realmDelimiter When set a realm is required.
* @property {Number} settings.resetPasswordTokenTTL Time to live for password reset `AccessToken`. Default is `900` (15 minutes).
* @property {Number} settings.saltWorkFactor The `bcrypt` salt work factor. Default is `10`.
* @property {Boolean} settings.caseSensitiveEmail Enable case sensitive email.
*
* @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
*
* Supported flavours:
*
* ```js
* createAccessToken(ttl, cb)
* createAccessToken(ttl, options, cb);
* createAccessToken(options, cb);
* // recent addition:
* createAccessToken(data, options, cb);
* ```
*
* @options {Number|Object} [ttl|data] Either the requested ttl,
* or an object with token properties to set (see below).
* @property {Number} [ttl] The requested ttl
* @property {String[]} [scopes] The access scopes granted to the token.
* @param {Object} [options] Additional options including remoting context
* @callback {Function} cb The callback function
* @param {String|Error} err The error string or object
* @param {AccessToken} token The generated access token object
* @promise
*
*/
User.prototype.createAccessToken = function(ttl, options, cb) {
if (cb === undefined && typeof options === 'function') {
// createAccessToken(ttl, cb)
cb = options;
options = undefined;
}
cb = cb || utils.createPromiseCallback();
let tokenData;
if (typeof ttl !== 'object') {
// createAccessToken(ttl[, options], cb)
tokenData = {ttl};
} else if (options) {
// createAccessToken(data, options, cb)
tokenData = ttl;
} else {
// createAccessToken(options, cb);
tokenData = {};
}
var userSettings = this.constructor.settings;
tokenData.ttl = Math.min(tokenData.ttl || userSettings.ttl, userSettings.maxTTL);
this.accessTokens.create(tokenData, options, cb);
return cb.promise;
};
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);
* });
* ```
*
* If the `emailVerificationRequired` flag is set for the inherited user model
* and the email has not yet been verified then the method will return a 401
* error that will contain the user's id. This id can be used to call the
* `api/verify` remote method to generate a new email verification token and
* send back the related email to the user.
*
* @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
* @promise
*/
User.login = function(credentials, include, fn) {
var self = this;
if (typeof include === 'function') {
fn = include;
include = undefined;
}
fn = fn || utils.createPromiseCallback();
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(g.f('{{realm}} is required'));
err1.statusCode = 400;
err1.code = 'REALM_REQUIRED';
fn(err1);
return fn.promise;
}
if (!query.email && !query.username) {
var err2 = new Error(g.f('{{username}} or {{email}} is required'));
err2.statusCode = 400;
err2.code = 'USERNAME_EMAIL_REQUIRED';
fn(err2);
return fn.promise;
}
self.findOne({where: query}, function(err, user) {
var defaultError = new Error(g.f('login failed'));
defaultError.statusCode = 401;
defaultError.code = 'LOGIN_FAILED';
function tokenHandler(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);
}
if (err) {
debug('An error is reported from User.findOne: %j', err);
fn(defaultError);
} else if (user) {
user.hasPassword(credentials.password, function(err, isMatch) {
if (err) {
debug('An error is reported from User.hasPassword: %j', err);
fn(defaultError);
} else if (isMatch) {
if (self.settings.emailVerificationRequired && !user.emailVerified) {
// Fail to log in if email verification is not done yet
debug('User email has not been verified');
err = new Error(g.f('login failed as the email has not been verified'));
err.statusCode = 401;
err.code = 'LOGIN_FAILED_EMAIL_NOT_VERIFIED';
err.details = {
userId: user.id,
};
fn(err);
} else {
if (user.createAccessToken.length === 2) {
user.createAccessToken(credentials.ttl, tokenHandler);
} else {
user.createAccessToken(credentials.ttl, credentials, tokenHandler);
}
}
} 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);
}
});
return fn.promise;
};
/**
* 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
* @promise
*/
User.logout = function(tokenId, fn) {
fn = fn || utils.createPromiseCallback();
var err;
if (!tokenId) {
err = new Error(g.f('{{accessToken}} is required to logout'));
err.statusCode = 401;
process.nextTick(fn, err);
return fn.promise;
}
this.relations.accessTokens.modelTo.destroyById(tokenId, function(err, info) {
if (err) {
fn(err);
} else if ('count' in info && info.count === 0) {
err = new Error(g.f('Could not find {{accessToken}}'));
err.statusCode = 401;
fn(err);
} else {
fn();
}
});
return fn.promise;
};
User.observe('before delete', function(ctx, next) {
// Do nothing when the access control was disabled for this user model.
if (!ctx.Model.relations.accessTokens) return next();
var AccessToken = ctx.Model.relations.accessTokens.modelTo;
var pkName = ctx.Model.definition.idName() || 'id';
ctx.Model.find({where: ctx.where, fields: [pkName]}, function(err, list) {
if (err) return next(err);
var ids = list.map(function(u) { return u[pkName]; });
ctx.where = {};
ctx.where[pkName] = {inq: ids};
AccessToken.destroyAll({userId: {inq: ids}}, next);
});
});
/**
* Compare the given `password` with the users hashed password.
*
* @param {String} password The plain text password
* @callback {Function} callback Callback function
* @param {Error} err Error object
* @param {Boolean} isMatch Returns true if the given `password` matches record
* @promise
*/
User.prototype.hasPassword = function(plain, fn) {
fn = fn || utils.createPromiseCallback();
if (this.password && plain) {
bcrypt.compare(plain, this.password, function(err, isMatch) {
if (err) return fn(err);
fn(null, isMatch);
});
} else {
fn(null, false);
}
return fn.promise;
};
/**
* Change this user's password.
*
* @param {*} userId Id of the user changing the password
* @param {string} oldPassword Current password, required in order
* to strongly verify the identity of the requesting user
* @param {string} newPassword The new password to use.
* @param {object} [options]
* @callback {Function} callback
* @param {Error} err Error object
* @promise
*/
User.changePassword = function(userId, oldPassword, newPassword, options, cb) {
if (cb === undefined && typeof options === 'function') {
cb = options;
options = undefined;
}
cb = cb || utils.createPromiseCallback();
// Make sure to use the constructor of the (sub)class
// where the method is invoked from (`this` instead of `User`)
this.findById(userId, options, (err, inst) => {
if (err) return cb(err);
if (!inst) {
const err = new Error(`User ${userId} not found`);
Object.assign(err, {
code: 'USER_NOT_FOUND',
statusCode: 401,
});
return cb(err);
}
inst.changePassword(oldPassword, newPassword, options, cb);
});
return cb.promise;
};
/**
* Change this user's password (prototype/instance version).
*
* @param {string} oldPassword Current password, required in order
* to strongly verify the identity of the requesting user
* @param {string} newPassword The new password to use.
* @param {object} [options]
* @callback {Function} callback
* @param {Error} err Error object
* @promise
*/
User.prototype.changePassword = function(oldPassword, newPassword, options, cb) {
if (cb === undefined && typeof options === 'function') {
cb = options;
options = undefined;
}
cb = cb || utils.createPromiseCallback();
this.hasPassword(oldPassword, (err, isMatch) => {
if (err) return cb(err);
if (!isMatch) {
const err = new Error('Invalid current password');
Object.assign(err, {
code: 'INVALID_PASSWORD',
statusCode: 400,
});
return cb(err);
}
this.setPassword(newPassword, options, cb);
});
return cb.promise;
};
/**
* Set this user's password after a password-reset request was made.
*
* @param {*} userId Id of the user changing the password
* @param {string} newPassword The new password to use.
* @param {Object} [options] Additional options including remoting context
* @callback {Function} callback
* @param {Error} err Error object
* @promise
*/
User.setPassword = function(userId, newPassword, options, cb) {
assert(userId != null && userId !== '', 'userId is a required argument');
assert(!!newPassword, 'newPassword is a required argument');
if (cb === undefined && typeof options === 'function') {
cb = options;
options = undefined;
}
cb = cb || utils.createPromiseCallback();
// Make sure to use the constructor of the (sub)class
// where the method is invoked from (`this` instead of `User`)
this.findById(userId, options, (err, inst) => {
if (err) return cb(err);
if (!inst) {
const err = new Error(`User ${userId} not found`);
Object.assign(err, {
code: 'USER_NOT_FOUND',
statusCode: 401,
});
return cb(err);
}
inst.setPassword(newPassword, options, cb);
});
return cb.promise;
};
/**
* Set this user's password. The callers of this method
* must ensure the client making the request is authorized
* to change the password, typically by providing the correct
* current password or a password-reset token.
*
* @param {string} newPassword The new password to use.
* @param {Object} [options] Additional options including remoting context
* @callback {Function} callback
* @param {Error} err Error object
* @promise
*/
User.prototype.setPassword = function(newPassword, options, cb) {
assert(!!newPassword, 'newPassword is a required argument');
if (cb === undefined && typeof options === 'function') {
cb = options;
options = undefined;
}
cb = cb || utils.createPromiseCallback();
try {
this.constructor.validatePassword(newPassword);
} catch (err) {
cb(err);
return cb.promise;
}
// We need to modify options passed to patchAttributes, but we don't want
// to modify the original options object passed to us by setPassword caller
options = Object.assign({}, options);
// patchAttributes() does not allow callers to modify the password property
// unless "options.setPassword" is set.
options.setPassword = true;
const delta = {password: newPassword};
this.patchAttributes(delta, options, (err, updated) => cb(err));
return cb.promise;
};
/**
* Returns default verification options to use when calling User.prototype.verify()
* from remote method /user/:id/verify.
*
* NOTE: the User.getVerifyOptions() method can also be used to ease the
* building of identity verification options.
*
* ```js
* var verifyOptions = MyUser.getVerifyOptions();
* user.verify(verifyOptions);
* ```
*
* This is the full list of possible params, with example values
*
* ```js
* {
* type: 'email',
* mailer: {
* send(verifyOptions, options, cb) {
* // send the email
* cb(err, result);
* }
* },
* to: '[email protected]',
* from: '[email protected]'
* subject: 'verification email subject',
* text: 'Please verify your email by opening this link in a web browser',
* headers: {'Mime-Version': '1.0'},
* template: 'path/to/template.ejs',
* templateFn: function(verifyOptions, options, cb) {
* cb(null, 'some body template');
* }
* redirect: '/',
* verifyHref: 'http://localhost:3000/api/user/confirm',
* host: 'localhost'
* protocol: 'http'
* port: 3000,
* restApiRoot= '/api',
* generateVerificationToken: function (user, options, cb) {
* cb(null, 'random-token');
* }
* }
* ```
*
* NOTE: param `to` internally defaults to user's email but can be overriden for
* test purposes or advanced customization.
*
* Static default params can be modified in your custom user model json definition
* using `settings.verifyOptions`. Any default param can be programmatically modified
* like follows:
*
* ```js
* customUserModel.getVerifyOptions = function() {
* const base = MyUser.base.getVerifyOptions();
* return Object.assign({}, base, {
* // custom values
* });
* }
* ```
*
* Usually you should only require to modify a subset of these params
* See `User.verify()` and `User.prototype.verify()` doc for params reference
* and their default values.
*/
User.getVerifyOptions = function() {
const defaultOptions = {
type: 'email',
from: '[email protected]',
};
return Object.assign({}, this.settings.verifyOptions || defaultOptions);
};
/**
* Verify a user's identity by sending them a confirmation message.
* NOTE: Currently only email verification is supported
*
* ```js
* var verifyOptions = {
* type: 'email',
* from: '[email protected]'
* template: 'verify.ejs',
* redirect: '/',
* generateVerificationToken: function (user, options, cb) {
* cb('random-token');
* }
* };
*
* user.verify(verifyOptions);
* ```
*
* NOTE: the User.getVerifyOptions() method can also be used to ease the
* building of identity verification options.
*
* ```js
* var verifyOptions = MyUser.getVerifyOptions();
* user.verify(verifyOptions);
* ```
*
* @options {Object} verifyOptions
* @property {String} type Must be `'email'` in the current implementation.
* @property {Function} mailer A mailer function with a static `.send() method.
* The `.send()` method must accept the verifyOptions object, the method's
* remoting context options object and a callback function with `(err, email)`
* as parameters.
* Defaults to provided `userModel.email` function, or ultimately to LoopBack's
* own mailer function.
* @property {String} to Email address to which verification email is sent.
* Defaults to user's email. Can also be overriden to a static value for test
* purposes.
* @property {String} from Sender email address
* For example `'[email protected]'`.
* @property {String} subject Subject line text.
* Defaults to `'Thanks for Registering'` or a local equivalent.
* @property {String} text Text of email.
* Defaults to `'Please verify your email by opening this link in a web browser:`
* followed by the verify link.
* @property {Object} headers Email headers. None provided by default.
* @property {String} template Relative path of template that displays verification
* page. Defaults to `'../../templates/verify.ejs'`.
* @property {Function} templateFn A function generating the email HTML body
* from `verify()` options object and generated attributes like `options.verifyHref`.
* It must accept the verifyOptions object, the method's remoting context options
* object and a callback function with `(err, html)` as parameters.
* A default templateFn function is provided, see `createVerificationEmailBody()`
* for implementation details.
* @property {String} redirect Page to which user will be redirected after
* they verify their email. Defaults to `'/'`.
* @property {String} verifyHref The link to include in the user's verify message.
* Defaults to an url analog to:
* `http://host:port/restApiRoot/userRestPath/confirm?uid=userId&redirect=/``
* @property {String} host The API host. Defaults to app's host or `localhost`.
* @property {String} protocol The API protocol. Defaults to `'http'`.
* @property {Number} port The API port. Defaults to app's port or `3000`.
* @property {String} restApiRoot The API root path. Defaults to app's restApiRoot
* or `'/api'`
* @property {Function} generateVerificationToken A function to be used to
* generate the verification token.
* It must accept the verifyOptions object, the method's remoting context options
* object and a callback function with `(err, hexStringBuffer)` as parameters.
* This function should NOT add the token to the user object, instead simply
* execute the callback with the token! User saving and email sending will be
* handled in the `verify()` method.
* A default token generation function is provided, see `generateVerificationToken()`
* for implementation details.
* @callback {Function} cb Callback function.
* @param {Object} options remote context options.
* @param {Error} err Error object.
* @param {Object} object Contains email, token, uid.
* @promise
*/
User.prototype.verify = function(verifyOptions, options, cb) {
if (cb === undefined && typeof options === 'function') {
cb = options;
options = undefined;
}
cb = cb || utils.createPromiseCallback();
var user = this;
var userModel = this.constructor;
var registry = userModel.registry;
verifyOptions = Object.assign({}, verifyOptions);
// final assertion is performed once all options are assigned
assert(typeof verifyOptions === 'object',
'verifyOptions object param required when calling user.verify()');
// Shallow-clone the options object so that we don't override
// the global default options object
verifyOptions = Object.assign({}, verifyOptions);
// Set a default template generation function if none provided
verifyOptions.templateFn = verifyOptions.templateFn || createVerificationEmailBody;
// Set a default token generation function if none provided
verifyOptions.generateVerificationToken = verifyOptions.generateVerificationToken ||
User.generateVerificationToken;
// Set a default mailer function if none provided
verifyOptions.mailer = verifyOptions.mailer || userModel.email ||
registry.getModelByType(loopback.Email);
var pkName = userModel.definition.idName() || 'id';
verifyOptions.redirect = verifyOptions.redirect || '/';
var defaultTemplate = path.join(__dirname, '..', '..', 'templates', 'verify.ejs');
verifyOptions.template = path.resolve(verifyOptions.template || defaultTemplate);
verifyOptions.user = user;
verifyOptions.protocol = verifyOptions.protocol || 'http';
var app = userModel.app;
verifyOptions.host = verifyOptions.host || (app && app.get('host')) || 'localhost';
verifyOptions.port = verifyOptions.port || (app && app.get('port')) || 3000;
verifyOptions.restApiRoot = verifyOptions.restApiRoot || (app && app.get('restApiRoot')) || '/api';
var displayPort = (
(verifyOptions.protocol === 'http' && verifyOptions.port == '80') ||
(verifyOptions.protocol === 'https' && verifyOptions.port == '443')
) ? '' : ':' + verifyOptions.port;
if (!verifyOptions.verifyHref) {
const confirmMethod = userModel.sharedClass.findMethodByName('confirm');
if (!confirmMethod) {
throw new Error(
'Cannot build user verification URL, ' +
'the default confirm method is not public. ' +
'Please provide the URL in verifyOptions.verifyHref.'
);
}
const urlPath = joinUrlPath(
verifyOptions.restApiRoot,
userModel.http.path,
confirmMethod.http.path
);
verifyOptions.verifyHref =
verifyOptions.protocol +
'://' +
verifyOptions.host +
displayPort +
urlPath +
'?' + qs.stringify({
uid: '' + verifyOptions.user[pkName],
redirect: verifyOptions.redirect,
});
}
verifyOptions.to = verifyOptions.to || user.email;
verifyOptions.subject = verifyOptions.subject || g.f('Thanks for Registering');
verifyOptions.headers = verifyOptions.headers || {};
// assert the verifyOptions params that might have been badly defined
assertVerifyOptions(verifyOptions);
// argument "options" is passed depending on verifyOptions.generateVerificationToken function requirements
var tokenGenerator = verifyOptions.generateVerificationToken;
if (tokenGenerator.length == 3) {
tokenGenerator(user, options, addTokenToUserAndSave);
} else {
tokenGenerator(user, addTokenToUserAndSave);
}
function addTokenToUserAndSave(err, token) {
if (err) return cb(err);
user.verificationToken = token;
user.save(options, function(err) {
if (err) return cb(err);
sendEmail(user);
});
}
// TODO - support more verification types
function sendEmail(user) {
verifyOptions.verifyHref +=
verifyOptions.verifyHref.indexOf('?') === -1 ? '?' : '&';
verifyOptions.verifyHref += 'token=' + user.verificationToken;
verifyOptions.verificationToken = user.verificationToken;
verifyOptions.text = verifyOptions.text || g.f('Please verify your email by opening ' +
'this link in a web browser:\n\t%s', verifyOptions.verifyHref);
verifyOptions.text = verifyOptions.text.replace(/\{href\}/g, verifyOptions.verifyHref);
// argument "options" is passed depending on templateFn function requirements
var templateFn = verifyOptions.templateFn;
if (templateFn.length == 3) {
templateFn(verifyOptions, options, setHtmlContentAndSend);
} else {
templateFn(verifyOptions, setHtmlContentAndSend);
}
function setHtmlContentAndSend(err, html) {
if (err) return cb(err);
verifyOptions.html = html;
// Remove verifyOptions.template to prevent rejection by certain
// nodemailer transport plugins.
delete verifyOptions.template;
// argument "options" is passed depending on Email.send function requirements
var Email = verifyOptions.mailer;
if (Email.send.length == 3) {
Email.send(verifyOptions, options, handleAfterSend);
} else {
Email.send(verifyOptions, handleAfterSend);
}
function handleAfterSend(err, email) {
if (err) return cb(err);
cb(null, {email: email, token: user.verificationToken, uid: user[pkName]});
}
}
}
return cb.promise;
};
function assertVerifyOptions(verifyOptions) {
assert(verifyOptions.type, 'You must supply a verification type (verifyOptions.type)');
assert(verifyOptions.type === 'email', 'Unsupported verification type');
assert(verifyOptions.to, 'Must include verifyOptions.to when calling user.verify() ' +
'or the user must have an email property');
assert(verifyOptions.from, 'Must include verifyOptions.from when calling user.verify()');
assert(typeof verifyOptions.templateFn === 'function',
'templateFn must be a function');
assert(typeof verifyOptions.generateVerificationToken === 'function',
'generateVerificationToken must be a function');
assert(verifyOptions.mailer, 'A mailer function must be provided');
assert(typeof verifyOptions.mailer.send === 'function', 'mailer.send must be a function ');
}
function createVerificationEmailBody(verifyOptions, options, cb) {
var template = loopback.template(verifyOptions.template);
var body = template(verifyOptions);
cb(null, body);
}
/**
* A default verification token generator which accepts the user the token is
* being generated for and a callback function to indicate completion.
* This one uses the crypto library and 64 random bytes (converted to hex)
* for the token. When used in combination with the user.verify() method this
* function will be called with the `user` object as it's context (`this`).
*
* @param {object} user The User this token is being generated for.
* @param {object} options remote context options.
* @param {Function} cb The generator must pass back the new token with this function call.
*/
User.generateVerificationToken = function(user, options, cb) {
crypto.randomBytes(64, function(err, buf) {
cb(err, buf && buf.toString('hex'));
});
};
/**
* 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
* @promise
*/
User.confirm = function(uid, token, redirect, fn) {
fn = fn || utils.createPromiseCallback();
this.findById(uid, function(err, user) {
if (err) {
fn(err);
} else {
if (user && user.verificationToken === token) {
user.verificationToken = null;
user.emailVerified = true;
user.save(function(err) {
if (err) {
fn(err);
} else {
fn();
}
});
} else {
if (user) {
err = new Error(g.f('Invalid token: %s', token));
err.statusCode = 400;
err.code = 'INVALID_TOKEN';
} else {
err = new Error(g.f('User not found: %s', uid));
err.statusCode = 404;
err.code = 'USER_NOT_FOUND';
}
fn(err);
}
}
});
return fn.promise;
};
/**
* Create a short lived access token for temporary login. Allows users
* to change passwords if forgotten.
*
* @options {Object} options
* @prop {String} email The user's email address
* @property {String} realm The user's realm (optional)
* @callback {Function} callback
* @param {Error} err
* @promise
*/
User.resetPassword = function(options, cb) {
cb = cb || utils.createPromiseCallback();
var UserModel = this;
var ttl = UserModel.settings.resetPasswordTokenTTL || DEFAULT_RESET_PW_TTL;
options = options || {};
if (typeof options.email !== 'string') {
var err = new Error(g.f('Email is required'));
err.statusCode = 400;
err.code = 'EMAIL_REQUIRED';
cb(err);
return cb.promise;
}
try {
if (options.password) {
UserModel.validatePassword(options.password);
}
} catch (err) {
return cb(err);
}
var where = {
email: options.email,
};
if (options.realm) {
where.realm = options.realm;
}
UserModel.findOne({where: where}, function(err, user) {
if (err) {
return cb(err);
}
if (!user) {
err = new Error(g.f('Email not found'));
err.statusCode = 404;
err.code = 'EMAIL_NOT_FOUND';
return cb(err);
}
// create a short lived access token for temp login to change password
// TODO(ritch) - eventually this should only allow password change
if (UserModel.settings.emailVerificationRequired && !user.emailVerified) {
err = new Error(g.f('Email has not been verified'));
err.statusCode = 401;
err.code = 'RESET_FAILED_EMAIL_NOT_VERIFIED';
return cb(err);
}
if (UserModel.settings.restrictResetPasswordTokenScope) {
const tokenData = {
ttl: ttl,
scopes: ['reset-password'],
};
user.createAccessToken(tokenData, options, onTokenCreated);
} else {
// We need to preserve backwards-compatibility with
// user-supplied implementations of "createAccessToken"
// that may not support "options" argument (we have such
// examples in our test suite).
user.createAccessToken(ttl, onTokenCreated);
}
function onTokenCreated(err, accessToken) {
if (err) {
return cb(err);
}
cb();
UserModel.emit('resetPasswordRequest', {
email: options.email,
accessToken: accessToken,
user: user,
options: options,