-
Notifications
You must be signed in to change notification settings - Fork 19
/
user.ts
1519 lines (1450 loc) · 46.8 KB
/
user.ts
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
'use strict';
import Model, { Sofa } from '@sl-nx/sofa-model';
import merge from 'deepmerge';
import { EventEmitter } from 'events';
import { Request } from 'express';
import { DocumentScope, ServerScope } from 'nano';
import url from 'url';
import { v4 as uuidv4 } from 'uuid';
import { DBAuth } from './dbauth';
import { Hashing } from './hashing';
import { Mailer } from './mailer';
import { Session } from './session';
import { Config } from './types/config';
import {
ConsentRequest,
CouchDbAuthDoc,
CreateSessionOpts,
HashResult,
LocalHashObj,
RegistrationForm,
SessionObj,
SlAction,
SlLoginSession,
SlRefreshSession,
SlRequest,
SlUserDoc,
SlUserNew
} from './types/typings';
import { DbManager } from './user/DbManager';
import {
EMAIL_REGEXP,
URLSafeUUID,
USER_REGEXP,
arrayUnion,
extractCurrentConsents,
getSessionKey,
hashToken,
hyphenizeUUID,
removeHyphens,
verifyConsentUpdate,
verifySessionConfigRoles
} from './util';
export enum ValidErr {
'exists' = 'already in use',
'emailInvalid' = 'invalid email',
'userInvalid' = 'invalid username'
}
export class User {
private dbAuth: DBAuth;
private userDbManager: DbManager;
private session: Session;
private onCreateActions: SlAction[];
private onLinkActions: SlAction[];
private hasher: Hashing;
private passwordConstraints;
/**
* Checks that a username is valid and not in use.
* Resolves with nothing if successful.
* Resolves with an error object in failed.
*/
public validateUsername: (v: string) => Promise<string | void>;
/**
* Checks that an email is valid and not in use.
* Resolves with nothing if successful.
* Resolves with an error object in failed.
*/
public validateEmail: (v: string) => Promise<string | void>;
/** Validates whether the _format_ matches the config */
private validateConsents: (
v: Record<string, ConsentRequest>
) => string | void;
/** @internal */
userModel: Sofa.AsyncOptions;
private resetPasswordModel: Sofa.AsyncOptions;
private changePasswordModel: Sofa.AsyncOptions;
constructor(
protected config: Config,
public userDB: DocumentScope<SlUserDoc>,
public couchAuthDB: DocumentScope<CouchDbAuthDoc>,
protected mailer: Mailer,
public emitter: EventEmitter,
protected couchServer: ServerScope
) {
this.dbAuth = new DBAuth(config, userDB, couchServer, couchAuthDB);
this.onCreateActions = [];
this.onLinkActions = [];
this.hasher = new Hashing(config);
this.session = new Session(this.hasher);
this.userDbManager = new DbManager(userDB, config);
this.passwordConstraints = config.local.passwordConstraints;
// the validation functions are public and callable without `this` context
this.validateUsername = async function (username: string) {
if (!username) {
return;
}
if (username.startsWith('_') || !username.match(USER_REGEXP)) {
return ValidErr.userInvalid;
}
try {
const result = await userDB.view('auth', 'key', { key: username });
if (result.rows.length === 0) {
// Pass!
return;
} else {
return ValidErr.exists;
}
} catch (err) {
throw new Error(err);
}
};
this.validateEmail = async function (
email: string
): Promise<string | void> {
if (!email) {
return;
}
if (!email.match(EMAIL_REGEXP)) {
return ValidErr.emailInvalid;
}
try {
const result = await userDB.view('auth', 'email', { key: email });
if (result.rows.length === 0) {
// Pass!
return;
} else {
return ValidErr.exists;
}
} catch (err) {
throw new Error(err);
}
};
const requiredConsents: string[] = [];
for (const [k, v] of Object.entries(config.local.consents ?? {})) {
if (v.required) {
requiredConsents.push(k);
}
}
this.validateConsents = function (
initialConsents: Record<string, ConsentRequest>
): string | void {
if (initialConsents === undefined && !requiredConsents.length) {
return;
}
const err = verifyConsentUpdate(initialConsents, config);
if (err) {
return err;
}
const providedConsents = new Set(Object.keys(initialConsents));
if (requiredConsents.some(c => !providedConsents.has(c))) {
return 'must include all required consents';
}
};
// `consents`, `sessionType` are added dynamically based on the config
const userModel: Sofa.AsyncOptions = {
async: true,
whitelist: ['name', 'username', 'email', 'password', 'confirmPassword'],
customValidators: {
validateEmail: this.validateEmail,
validateUsername: this.validateUsername,
matches: this.matches,
validateConsents: this.validateConsents
},
sanitize: {
name: ['trim'],
username: ['trim', 'toLowerCase'],
email: ['trim', 'toLowerCase']
},
validate: {
email: {
presence: true,
validateEmail: true
},
username: {
presence: true,
validateUsername: true
},
password: this.passwordConstraints,
confirmPassword: {
presence: true
}
},
static: {
type: 'user',
roles: config.security.defaultRoles,
providers: ['local']
},
rename: {
username: 'key'
}
};
this.resetPasswordModel = {
async: true,
customValidators: {
matches: this.matches
},
validate: {
token: {
presence: true
},
password: this.passwordConstraints,
confirmPassword: {
presence: true
}
}
};
this.changePasswordModel = {
async: true,
customValidators: {
matches: this.matches
},
validate: {
newPassword: this.passwordConstraints,
confirmPassword: {
presence: true
}
}
};
if (config.local.emailUsername) {
delete userModel.validate.username;
}
if (config.local.consents) {
userModel.whitelist.push('consents');
userModel.validate.consents = {
validateConsents: true
};
if (requiredConsents.length) {
userModel.validate.consents.presence = true;
}
}
if (config.security.sessionConfig) {
userModel.whitelist.push('sessionType');
const sessionValidator = {
inclusion: {
within: Object.keys(config.security.sessionConfig)
}
};
userModel.validate.sessionType = sessionValidator;
this.resetPasswordModel.validate.sessionType = sessionValidator;
}
this.userModel = userModel;
}
/**
* Hashes a password using PBKDF2 and returns an object containing `salt` and
* `derived_key`.
*/
public hashPassword(pw: string): Promise<HashResult> {
return this.hasher.hashUserPassword(pw);
}
/**
* Verifies a password using a hash object. If you have a user doc, pass in
* `local` as the hash object.
* @returns resolves with `true` if valid, `false` if not
*/
public verifyPassword(obj: LocalHashObj, pw: string): Promise<boolean> {
return this.hasher.verifyUserPassword(obj, pw);
}
/**
* Use this to add as many functions as you want to transform the new user
* document before it is saved. Your function should accept two arguments
* (userDoc, provider) and return a Promise that resolves to the modified
* user document.
* onCreate functions will be chained in the order they were added.
* @param {Function} fn
*/
public onCreate(fn: SlAction) {
if (typeof fn === 'function') {
this.onCreateActions.push(fn);
} else {
throw new TypeError('onCreate: You must pass in a function');
}
}
/**
* Does the same thing as onCreate, but is called every time a user links a
* new provider, or their profile information is refreshed.
* This allows you to process profile information and, for example, create a
* master profile.
* If an object called profile exists inside the user doc it will be passed
* to the client along with session information at each login.
*/
public onLink(fn: SlAction) {
if (typeof fn === 'function') {
this.onLinkActions.push(fn);
} else {
throw new TypeError('onLink: You must pass in a function');
}
}
/** Validation function for ensuring that two fields match */
private matches(value, option, key, attributes) {
if (attributes && attributes[option] !== value) {
return 'does not match ' + option;
}
}
private async processTransformations(
fnArray: SlAction[],
userDoc: SlUserDoc,
provider: string
): Promise<SlUserDoc> {
for (const fn of fnArray) {
userDoc = await fn.call(null, userDoc, provider);
}
return userDoc;
}
/**
* retrieves by email (default) or username or uuid if the config options are
* set. Rejects if no valid format.
*/
public getUser(login: string, allowUUID = false): Promise<SlUserDoc | null> {
return this.userDbManager.getUser(login, allowUUID);
}
private async handleEmailExists(email: string, req?): Promise<void> {
const existingUser = await this.userDbManager.getUserBy('email', email);
if (this.config.local.sendExistingUserEmail && !this.config.mailer.useCustomMailer) {
await this.mailer.sendEmail('signupExistingEmail', email, {
user: existingUser,
req
});
}
this.emitter.emit('signup-attempt', existingUser, 'local');
}
/**
* Creates a new local user with a username/email and password.
* @param form requires the following: `username` and/or `email`, `password`,
* and `confirmPassword`. `name` is optional. Any additional fields must be
* whitelisted in your config under `userModel` or they will be removed.
* @param req additional request data passed to the email template
* @returns `SlUserDoc` of the created user. Note that the `_rev` won't be
* correct if `config.security.loginOnRegistration` is `false`: This is done
* to prevent [time-based attacks](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html#authentication-responses).
* Send a response right after this function resolves and subscribe to the
* `signup` event instead for further processing.
*/
public async createUser(
form: RegistrationForm,
req?
): Promise<void | SlUserDoc> {
req = req || {};
let finalUserModel = this.userModel;
const newUserModel = this.config.userModel;
if (typeof newUserModel === 'object') {
let whitelist;
if (newUserModel.whitelist) {
whitelist = arrayUnion(
this.userModel.whitelist,
newUserModel.whitelist
);
}
const addUserModel = this.config.userModel;
finalUserModel = merge(
this.userModel,
addUserModel ? (addUserModel as Sofa.AsyncOptions) : {}
);
finalUserModel.whitelist = whitelist || finalUserModel.whitelist;
}
const UserModel = Model(finalUserModel);
const user = new UserModel(form);
let newUser: Partial<SlUserNew> = {};
let hasError = false;
try {
newUser = await user.process();
} catch (err) {
hasError = true;
let doThrow = true;
if (
err.email &&
this.config.local.emailUsername &&
this.config.local.requireEmailConfirm
) {
const inUseIdx = err.email.findIndex((s: string) =>
s.endsWith(ValidErr.exists)
);
if (inUseIdx >= 0) {
err.email.splice(inUseIdx, 1);
if (err.email.length === 0) {
delete err.email;
if (Object.keys(err).length === 0) {
this.handleEmailExists(form.email, req);
doThrow = false;
}
}
}
}
if (doThrow) {
throw {
error: 'Validation failed',
validationErrors: err,
status: 400
};
}
}
// TODO: This is an instance of the promise constructor anti-pattern
return new Promise(async (resolve, reject) => {
newUser = await this.prepareNewUser(newUser);
if (hasError || !this.config.security.loginOnRegistration) {
resolve(hasError ? undefined : (newUser as SlUserDoc));
}
if (!hasError) {
const finalUser = await this.insertNewUserDocument(newUser, req);
this.emitter.emit('signup', finalUser, 'local');
if (this.config.security.loginOnRegistration) {
resolve(finalUser);
}
}
});
}
private async prepareNewUser(newUser: Partial<SlUserNew>) {
const uid = uuidv4();
// todo: remove, this is just for backwards compat...
if (this.config.local.sendNameAndUUID) {
newUser.user_uid = uid;
}
newUser._id = removeHyphens(uid);
if (this.config.local.emailUsername) {
newUser.key = await this.userDbManager.generateUsername();
}
if (this.config.local.sendConfirmEmail) {
newUser.unverifiedEmail = {
email: newUser.email,
token: URLSafeUUID()
};
delete newUser.email;
}
newUser.local = await this.hashPassword(newUser.password ?? URLSafeUUID());
delete newUser.password;
delete newUser.confirmPassword;
if (newUser.consents) {
for (const [k, v] of Object.entries(newUser.consents)) {
(v as any).timestamp = new Date().toISOString();
newUser.consents[k] = [v as any];
}
}
newUser.signUp = {
provider: 'local',
timestamp: new Date().toISOString()
};
return newUser;
}
private async insertNewUserDocument(newUser: Partial<SlUserNew>, req?) {
newUser = await this.addUserDBs(newUser as SlUserDoc);
newUser = this.userDbManager.logActivity(
'signup',
'local',
newUser as SlUserDoc
);
const finalNewUser = await this.processTransformations(
this.onCreateActions,
newUser as SlUserDoc,
'local'
);
const result = await this.userDB.insert(finalNewUser);
newUser._rev = result.rev;
if (this.config.local.sendConfirmEmail && !this.config.mailer.useCustomMailer) {
try {
await this.mailer.sendEmail(
'confirmEmail',
newUser.unverifiedEmail.email,
{
req: req,
user: newUser
}
);
}
catch (err) {
this.emitter.emit('confirmation-email-error', newUser);
console.warn('error sending confirmation email to '+newUser.unverifiedEmail?.email, err);
}
}
return newUser as SlUserDoc;
}
/**
* Creates a new user following authentication from an OAuth provider.
* If the user already exists it will update the profile.
* @param provider the name of the provider in lowercase, (e.g. 'facebook')
* @param {any} auth credentials supplied by the provider
* @param {any} profile the profile supplied by the provider
*/
public async createUserSocial(
provider: string,
auth,
profile
): Promise<SlUserDoc> {
let user: Partial<SlUserDoc>;
let newAccount = false;
// This used to be consumed by `.nodeify` from Bluebird. I hope `callbackify` works just as well...
const results = await this.userDB.view('auth', provider, {
key: profile.id,
include_docs: true
});
if (results.rows.length > 0) {
user = results.rows[0].doc;
} else {
newAccount = true;
user = {
email: profile.emails ? profile.emails[0].value : undefined,
providers: [provider],
type: 'user',
roles: this.config.security.defaultRoles,
signUp: {
provider: provider,
timestamp: new Date().toISOString()
}
};
user[provider] = {};
// Now we need to generate a username
if (!user.email) {
throw {
error: 'No email provided',
message: `An email is required for registration, but ${provider} didn't supply one.`,
status: 400
};
}
const emailCheck = await this.validateEmail(user.email);
if (emailCheck) {
throw {
error: 'Email already in use',
message:
'Your email is already in use. Try signing in first and then linking this account.',
status: 409
};
}
user.key = await this.userDbManager.generateUsername();
}
user[provider].auth = auth;
user[provider].profile = profile;
if (!user.name) {
user.name = profile.displayName;
}
delete user[provider].profile._raw;
if (newAccount) {
user._id = removeHyphens(uuidv4());
user = await this.addUserDBs(user as SlUserDoc);
}
let finalUser = await this.processTransformations(
newAccount ? this.onCreateActions : this.onLinkActions,
user as SlUserDoc,
provider
);
const action = newAccount ? 'signup' : 'create-social';
finalUser = this.userDbManager.logActivity(action, provider, finalUser);
await this.userDB.insert(finalUser);
this.emitter.emit(action, user, provider);
return user as SlUserDoc;
}
/**
* like `createUserSocial`, but for an already existing user identified by
* `login`
*/
public async linkUserSocial(
login: string,
provider: string,
auth,
profile
): Promise<SlUserDoc> {
let userDoc = await this.userDbManager.initLinkSocial(
login,
provider,
auth,
profile
);
userDoc = await this.processTransformations(
this.onLinkActions,
userDoc,
provider
);
userDoc = this.userDbManager.logActivity('link-social', provider, userDoc);
await this.userDB.insert(userDoc);
this.emitter.emit('link-social', userDoc, provider);
return userDoc;
}
/**
* Removes the specified provider from the user's account.
* `local` cannot be removed. If there is only one provider left it will fail.
* Returns the modified user, if successful.
* @param login email, username or UUID
* @param provider the OAuth provider
*/
public unlinkUserSocial(login: string, provider: string): Promise<SlUserDoc> {
return this.userDbManager.unlink(login, provider);
}
/**
* Creates a new session for a user
* @param params: The login options.
* - `login`: the email, username or UUID (depending on your config)
* - `provider`: 'local' or one of the configured OAuth providers
* - `byUUID`: if `true`, interpret `login` always as UUID
* - `sessionType`: see `security` -> `sessionConfig` for details
* @returns the new session
*/
public async createSession(
params: CreateSessionOpts
): Promise<SlLoginSession> {
const login = params.login;
const provider = params.provider;
let user = params.byUUID
? await this.userDbManager.getUserByUUID(login)
: await this.getUser(login);
if (!user) {
console.warn('createSession - could not retrieve: ', login);
throw { error: 'Bad Request', status: 400 };
}
const now = Date.now();
const password = URLSafeUUID();
let sessionLife = this.config.security.sessionLife * 1000;
if (params.sessionType) {
const sessionConfig =
this.config.security.sessionConfig[params.sessionType];
verifySessionConfigRoles(user.roles, sessionConfig);
sessionLife = sessionConfig.lifetime * 1000;
}
const token = {
key: user.inactiveSessions?.shift() ?? getSessionKey(),
password,
_id: user._id,
issued: now,
expires: now + sessionLife,
roles: user.roles,
provider
};
try {
await this.dbAuth.storeKey(
user.key,
hyphenizeUUID(user._id),
token.key,
password,
token.expires,
user.roles,
provider
);
} catch (error) {
let msg =
'Could not create session token with key: ' +
token.key +
' - was inactiveSessions copied and does the key already exist?';
if (error.status) {
msg += ', status: ' + error.status;
}
console.error(msg);
throw error;
}
// authorize the new session across all dbs
if (user.personalDBs) {
await this.dbAuth.authorizeUserSessions(user.personalDBs, token.key);
}
if (!user.session) {
user.session = {};
}
const newSession: Partial<SlLoginSession> = {
issued: token.issued,
expires: token.expires,
provider: provider,
sessionType: params.sessionType ?? undefined
};
user.session[token.key] = newSession as SessionObj;
// Clear any failed login attempts
if (provider === 'local') {
if (!user.local) user.local = {};
delete user.local.failedLoginAttempts;
delete user.local.lockedUntil;
}
const userDoc = this.userDbManager.logActivity('login', provider, user);
// Clean out expired sessions on login
const finalUser = await this.dbAuth.logoutUserSessions(userDoc, 'expired');
user = finalUser;
await this.userDB.insert(finalUser);
newSession.token = token.key;
newSession.password = password;
newSession.user_id = user.key;
newSession.roles = user.roles;
// Inject the list of userDBs
if (typeof user.personalDBs === 'object') {
const userDBs = {};
let publicURL: string;
if (this.config.dbServer.publicURL) {
const dbObj = url.parse(this.config.dbServer.publicURL);
dbObj.auth = newSession.token + ':' + newSession.password;
publicURL = url.format(dbObj);
} else {
publicURL =
this.config.dbServer.protocol +
newSession.token +
':' +
newSession.password +
'@' +
this.config.dbServer.host +
'/';
}
Object.keys(user.personalDBs).forEach(finalDBName => {
userDBs[user.personalDBs[finalDBName].name] = publicURL + finalDBName;
});
newSession.userDBs = userDBs;
}
if (user.profile) {
newSession.profile = user.profile;
}
if (this.config.local.sendNameAndUUID) {
if (user.name) {
newSession.name = user.name;
}
newSession.user_uid = hyphenizeUUID(user._id);
}
this.emitter.emit('login', newSession, provider);
return newSession as SlLoginSession;
}
/**
* Extends the life of your current token and returns updated token information.
* The only field that will change is expires. Expired sessions are removed.
* todo:
* - handle error if invalid state occurs that doc is not present.
*/
public async refreshSession(sessionId: string): Promise<SlRefreshSession> {
let userDoc = await this.userDbManager.findUserDocBySession(sessionId);
let minutesToExtend = this.config.security.sessionLife;
if (userDoc.session[sessionId].sessionType) {
minutesToExtend =
this.config.security.sessionConfig[
userDoc.session[sessionId].sessionType
].lifetime;
}
const newExpiration = Date.now() + minutesToExtend * 1000;
userDoc.session[sessionId].expires = newExpiration;
// Clean out expired sessions on refresh
userDoc = await this.dbAuth.logoutUserSessions(userDoc, 'expired');
userDoc = this.userDbManager.logActivity('refresh', sessionId, userDoc);
await this.userDB.insert(userDoc);
await this.dbAuth.extendKey(sessionId, newExpiration);
const newSession: SlRefreshSession = {
...userDoc.session[sessionId],
token: sessionId,
user_uid: hyphenizeUUID(userDoc._id),
user_id: userDoc.key,
roles: userDoc.roles
};
delete newSession['ip'];
this.emitter.emit('refresh', newSession);
return newSession;
}
/**
* Required form fields: token, password, and confirmPassword
*/
public async resetPassword(
form,
req: Partial<Request> = undefined
): Promise<SlUserDoc> {
req = req || {};
const ResetPasswordModel = Model(this.resetPasswordModel);
const passwordResetForm = new ResetPasswordModel(form);
let user: SlUserDoc;
try {
await passwordResetForm.validate();
} catch (err) {
throw {
error: 'Validation failed',
validationErrors: err,
status: 400
};
}
const tokenHash = hashToken(form.token);
const results = await this.userDB.view('auth', 'passwordReset', {
key: tokenHash,
include_docs: true
});
if (!results.rows.length) {
throw { status: 400, error: 'Invalid token' };
}
user = results.rows[0].doc;
if (user.forgotPassword.expires < Date.now()) {
return Promise.reject({ status: 400, error: 'Token expired' });
}
if (this.config.security.passwordResetRateLimit) {
const username = form[this.config.local.usernameField || 'username'];
if (!username) {
throw { status: 400, error: 'Invalid token' };
}
const slUser = await this.getUser(
form[this.config.local.usernameField || 'username']
);
if (user._id !== slUser._id) {
throw { status: 400, error: 'Invalid token' };
}
}
const hash = await this.hashPassword(form.password);
if (!user.local) {
user.local = {};
}
user.local = { ...user.local, ...hash };
if (user.providers.indexOf('local') === -1) {
user.providers.push('local');
}
// logout user completely
user = await this.dbAuth.logoutUserSessions(user, 'all');
delete user.forgotPassword;
if (user.unverifiedEmail) {
user = await this.markEmailAsVerified(user);
}
user = this.userDbManager.logActivity('password-reset', 'local', user);
await this.userDB.insert(user);
await this.sendModifiedPasswordEmail(user, req);
this.emitter.emit('password-reset', user);
return user;
}
/**
* Changes the password of a user, validating the provided data.
* @param login the `email`, `_id` or `key` of the `sl-user` to updated
* @param form `newPassword`, `confirmPassword` (same) and `currentPassword`
* as sent by the user.
* @param req additional data that will be passed to the template as `req`
*/
public async changePasswordSecure(login: string, form, req?): Promise<void> {
req = req || {};
const ChangePasswordModel = Model(this.changePasswordModel);
const changePasswordForm = new ChangePasswordModel(form);
try {
await changePasswordForm.validate();
} catch (err) {
throw {
error: 'Validation failed',
validationErrors: err,
status: 400
};
}
try {
const user = await this.getUser(login);
if (!user) {
throw { error: 'Bad Request', status: 400 }; // should exist.
}
if (user.local && user.local.salt && user.local.derived_key) {
// Password is required
if (!form.currentPassword) {
throw {
error: 'Password change failed',
message:
'You must supply your current password in order to change it.',
status: 400
};
}
await this.verifyPassword(user.local, form.currentPassword);
}
await this.changePassword(user._id, form.newPassword, user, req);
} catch (err) {
throw (
err || {
error: 'Password change failed',
message: 'The current password you supplied is incorrect.',
status: 400
}
);
}
if (req.user && req.user.key) {
await this.logoutOthers(req.user.key);
}
}
public async forgotUsername(
email: string,
req: Partial<Request>
): Promise<void> {
if (!email || !email.match(EMAIL_REGEXP)) {
throw { error: 'invalid email', status: 400 };
}
req = req || {};
try {
const user = await this.userDbManager.getUserBy('email', email);
if (!user) {
throw {
error: 'User not found',
status: 404
};
}
if (!this.config.mailer.useCustomMailer) {
await this.mailer.sendEmail(
'forgotUsername',
user.email || user.unverifiedEmail.email,
{ user: user, req: req }
);
}
this.emitter.emit('forgot-username', user);
} catch (err) {
this.emitter.emit('forgot-username-attempt', email);
if (err.status !== 404) {
throw err;
}
}
}
/**
* Changes the password of a user. Note that this method does not perform
* any validations of the supplied password as `changePasswordSecure` does.
* @param user_uid the UUID of the user (without hypens, `_id` in `sl-users`)
* @param newPassword the new password for the user
* @param userDoc the `SlUserDoc` of the user. Will be retrieved by the
* `user_uid` if not passed.
* @param req additional data that will be passed to the template as `req`
*/
public async changePassword(
user_uid: string,
newPassword: string,
userDoc?: SlUserDoc,
req?: any
): Promise<void> {
req = req || {};
if (!userDoc) {
try {
userDoc = await this.userDB.get(user_uid);
} catch (error) {
throw {
error: 'User not found',
status: 404
};
}
}
const hash = await this.hashPassword(newPassword);
if (!userDoc.local) {
userDoc.local = {};
}
if (userDoc.providers.indexOf('local') === -1) {
userDoc.providers.push('local');
}
userDoc.local = { ...userDoc.local, ...hash };
const finalUser = this.userDbManager.logActivity(
'password-change',
'local',
userDoc
);
await this.userDB.insert(finalUser);
await this.sendModifiedPasswordEmail(userDoc, req);
this.emitter.emit('password-change', userDoc);
}
private async sendModifiedPasswordEmail(user: SlUserDoc, req): Promise<void> {
if (this.config.local.sendPasswordChangedEmail && !this.config.mailer.useCustomMailer) {
await this.mailer.sendEmail(
'modifiedPassword',
user.email || user.unverifiedEmail.email,
{ user: user, req: req }
);
}
}
/**
* sends out a passwort reset email, if the user exists
* @param email email of the user
* @param req additional request data, passed to the template as `req`
*/
public async forgotPassword(email: string, req: any): Promise<void> {
email = email.toLowerCase();
if (!email || !email.match(EMAIL_REGEXP)) {
return Promise.reject({ error: 'invalid email', status: 400 });
}
req = req || {};
try {
const user = await this.userDbManager.getUserBy('email', email);
if (!user) {
throw {
error: 'User not found', // not sent as response.
status: 404
};
}
this.completeForgotPassRequest(user, req).catch(err => {
this.emitter.emit('forgot-password-attempt', email);