-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Auth.ts
1225 lines (1130 loc) · 45.6 KB
/
Auth.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
/*
* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
import { AuthOptions, FederatedResponse } from './types';
import {
AWS,
Cognito,
ConsoleLogger as Logger,
Constants,
Hub,
FacebookOAuth,
GoogleOAuth,
JS
} from '../Common';
import Platform from '../Common/Platform';
import Cache from '../Cache';
import { ICognitoUserPoolData, ICognitoUserData } from 'amazon-cognito-identity-js';
const logger = new Logger('AuthClass');
const {
CognitoIdentityCredentials,
Credentials
} = AWS;
const {
CookieStorage,
CognitoUserPool,
CognitoUserAttribute,
CognitoUser,
AuthenticationDetails,
} = Cognito;
const dispatchAuthEvent = (event, data) => {
Hub.dispatch('auth', { event, data }, 'Auth');
};
/**
* Provide authentication steps
*/
export default class AuthClass {
private _config: AuthOptions;
private _userPoolStorageSync: Promise<any>;
private userPool = null;
private credentials = null;
private credentials_source = ''; // aws, guest, userPool, federated
private user:any = null;
private _refreshHandlers = {};
private _gettingCredPromise = null;
/**
* Initialize Auth with AWS configurations
* @param {Object} config - Configuration of the Auth
*/
constructor(config: AuthOptions) {
this.configure(config);
// refresh token
this._refreshHandlers['google'] = GoogleOAuth.refreshGoogleToken;
this._refreshHandlers['facebook'] = FacebookOAuth.refreshFacebookToken;
if (AWS.config) {
AWS.config.update({customUserAgent: Constants.userAgent});
} else {
logger.warn('No AWS.config');
}
}
configure(config) {
logger.debug('configure Auth');
let conf = config? config.Auth || config : {};
if (conf['aws_cognito_identity_pool_id']) {
conf = {
userPoolId: conf['aws_user_pools_id'],
userPoolWebClientId: conf['aws_user_pools_web_client_id'],
region: conf['aws_cognito_region'],
identityPoolId: conf['aws_cognito_identity_pool_id'],
mandatorySignIn: conf['aws_mandatory_sign_in'] === 'enable'? true: false
};
}
this._config = Object.assign({}, this._config, conf);
if (!this._config.identityPoolId) { logger.debug('Do not have identityPoolId yet.'); }
const { userPoolId, userPoolWebClientId, cookieStorage } = this._config;
if (userPoolId) {
const userPoolData: ICognitoUserPoolData = {
UserPoolId: userPoolId,
ClientId: userPoolWebClientId,
};
if (cookieStorage) {
userPoolData.Storage = new CookieStorage(cookieStorage);
}
this.userPool = new CognitoUserPool(userPoolData);
if (Platform.isReactNative) {
const that = this;
this._userPoolStorageSync = new Promise((resolve, reject) => {
this.userPool.storage.sync((err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
}
dispatchAuthEvent('configured', null);
return this._config;
}
/**
* Sign up with username, password and other attrbutes like phone, email
* @param {String | object} params - The user attirbutes used for signin
* @param {String[]} restOfAttrs - for the backward compatability
* @return - A promise resolves callback data if success
*/
public signUp(params: string | object, ...restOfAttrs: string[]): Promise<any> {
if (!this.userPool) { return Promise.reject('No userPool'); }
let username : string = null;
let password : string = null;
const attributes : object[] = [];
let validationData: object[] = null;
if (params && typeof params === 'string') {
username = params;
password = restOfAttrs? restOfAttrs[0] : null;
const email : string = restOfAttrs? restOfAttrs[1] : null;
const phone_number : string = restOfAttrs? restOfAttrs[2] : null;
if (email) attributes.push({Name: 'email', Value: email});
if (phone_number) attributes.push({Name: 'phone_number', Value: phone_number});
} else if (params && typeof params === 'object') {
username = params['username'];
password = params['password'];
const attrs = params['attributes'];
if (attrs) {
Object.keys(attrs).map(key => {
const ele : object = { Name: key, Value: attrs[key] };
attributes.push(ele);
});
}
validationData = params['validationData'] || null;
} else {
return Promise.reject('The first parameter should either be non-null string or object');
}
if (!username) { return Promise.reject('Username cannot be empty'); }
if (!password) { return Promise.reject('Password cannot be empty'); }
logger.debug('signUp attrs:', attributes);
logger.debug('signUp validation data:', validationData);
return new Promise((resolve, reject) => {
this.userPool.signUp(username, password, attributes, validationData, function(err, data) {
if (err) {
dispatchAuthEvent('signUp_failure', err);
reject(err);
} else {
dispatchAuthEvent('signUp', data);
resolve(data);
}
});
});
}
/**
* Send the verfication code to confirm sign up
* @param {String} username - The username to be confirmed
* @param {String} code - The verification code
* @return - A promise resolves callback data if success
*/
public confirmSignUp(username: string, code: string): Promise<any> {
if (!this.userPool) { return Promise.reject('No userPool'); }
if (!username) { return Promise.reject('Username cannot be empty'); }
if (!code) { return Promise.reject('Code cannot be empty'); }
const user = this.createCognitoUser(username);
return new Promise((resolve, reject) => {
user.confirmRegistration(code, true, function(err, data) {
if (err) { reject(err); } else { resolve(data); }
});
});
}
/**
* Resend the verification code
* @param {String} username - The username to be confirmed
* @return - A promise resolves data if success
*/
public resendSignUp(username: string): Promise<any> {
if (!this.userPool) { return Promise.reject('No userPool'); }
if (!username) { return Promise.reject('Username cannot be empty'); }
const user = this.createCognitoUser(username);
return new Promise((resolve, reject) => {
user.resendConfirmationCode(function(err, data) {
if (err) { reject(err); } else { resolve(data); }
});
});
}
/**
* Sign in
* @param {String} username - The username to be signed in
* @param {String} password - The password of the username
* @return - A promise resolves the CognitoUser
*/
public signIn(username: string, password: string): Promise<any> {
if (!this.userPool) { return Promise.reject('No userPool'); }
if (!username) { return Promise.reject('Username cannot be empty'); }
if (!password) { return Promise.reject('Password cannot be empty'); }
const user = this.createCognitoUser(username);
const authDetails = new AuthenticationDetails({
Username: username,
Password: password
});
const that = this;
return new Promise((resolve, reject) => {
user.authenticateUser(authDetails, {
onSuccess: (session) => {
logger.debug(session);
that._setCredentialsFromSession(session).then((cred) => {
that.user = user;
dispatchAuthEvent('signIn', user);
resolve(user);
}).catch(e => {
logger.debug('cannot get cognito credentials');
reject('signin failed');
});
},
onFailure: (err) => {
logger.debug('signIn failure', err);
dispatchAuthEvent('signIn_failure', err);
reject(err);
},
mfaRequired: (challengeName, challengeParam) => {
logger.debug('signIn MFA required');
user['challengeName'] = challengeName;
user['challengeParam'] = challengeParam;
resolve(user);
},
newPasswordRequired: (userAttributes, requiredAttributes) => {
logger.debug('signIn new password');
user['challengeName'] = 'NEW_PASSWORD_REQUIRED';
user['challengeParam'] = {
userAttributes,
requiredAttributes
};
resolve(user);
},
mfaSetup: (challengeName, challengeParam) => {
logger.debug('signIn mfa setup', challengeName);
user['challengeName'] = challengeName;
user['challengeParam'] = challengeParam;
resolve(user);
},
totpRequired: (challengeName, challengeParam) => {
logger.debug('signIn totpRequired');
user['challengeName'] = challengeName;
user['challengeParam'] = challengeParam;
resolve(user);
},
selectMFAType: (challengeName, challengeParam) => {
logger.debug('signIn selectMFAType', challengeName);
user['challengeName'] = challengeName;
user['challengeParam'] = challengeParam;
resolve(user);
}
});
});
}
/**
* get user current preferred mfa option
* @param {CognitoUser} user - the current user
* @return - A promise resolves the current preferred mfa option if success
*/
public getMFAOptions(user : any) : Promise<any> {
return new Promise((res, rej) => {
user.getMFAOptions((err, mfaOptions) => {
if (err) {
logger.debug('get MFA Options failed', err);
rej(err);
}
logger.debug('get MFA options success', mfaOptions);
res(mfaOptions);
});
});
}
/**
* set preferred MFA method
* @param {CognitoUser} user - the current Cognito user
* @param {string} mfaMethod - preferred mfa method
* @return - A promise resolve if success
*/
public setPreferredMFA(user : any, mfaMethod : string): Promise<any> {
let smsMfaSettings = {
PreferredMfa : false,
Enabled : false
};
let totpMfaSettings = {
PreferredMfa : false,
Enabled : false
};
switch(mfaMethod) {
case 'TOTP':
totpMfaSettings = {
PreferredMfa : true,
Enabled : true
};
break;
case 'SMS':
smsMfaSettings = {
PreferredMfa : true,
Enabled : true
};
break;
case 'NOMFA':
break;
default:
logger.debug('no validmfa method provided');
return Promise.reject('no validmfa method provided');
}
const that = this;
const TOTP_NOT_VERIFED = 'User has not verified software token mfa';
const TOTP_NOT_SETUP = 'User has not set up software token mfa';
return new Promise((res, rej) => {
user.setUserMfaPreference(smsMfaSettings, totpMfaSettings, (err, result) => {
if (err) {
// if totp not setup or verified and user want to set it, return error
// otherwise igonre it
if (err.message === TOTP_NOT_SETUP || err.message === TOTP_NOT_VERIFED) {
if (mfaMethod === 'SMS') {
that.enableSMS(user).then((data) => {
logger.debug('Set user mfa success', data);
res(data);
}).catch(err => {
logger.debug('Set user mfa preference error', err);
rej(err);
});
} else if (mfaMethod === 'NOMFA') {
// diable sms
that.disableSMS(user).then((data) => {
logger.debug('Set user mfa success', data);
res(data);
}).catch(err => {
logger.debug('Set user mfa preference error', err);
rej(err);
});
} else {
logger.debug('Set user mfa preference error', err);
rej(err);
}
} else {
logger.debug('Set user mfa preference error', err);
rej(err);
}
}
logger.debug('Set user mfa success', result);
res(result);
});
});
}
/**
* diable SMS
* @param {CognitoUser} user - the current user
* @return - A promise resolves is success
*/
public disableSMS(user : any) : Promise<any> {
return new Promise((res, rej) => {
user.disableMFA((err, data) => {
if (err) {
logger.debug('disable mfa failed', err);
rej(err);
}
logger.debug('disable mfa succeed', data);
res(data);
});
});
}
/**
* enable SMS
* @param {CognitoUser} user - the current user
* @return - A promise resolves is success
*/
public enableSMS(user) {
return new Promise((res, rej) => {
user.enableMFA((err, data) => {
if (err) {
logger.debug('enable mfa failed', err);
rej(err);
}
logger.debug('enable mfa succeed', data);
res(data);
});
});
}
/**
* Setup TOTP
* @param {CognitoUser} user - the current user
* @return - A promise resolves with the secret code if success
*/
public setupTOTP(user) {
return new Promise((res, rej) => {
user.associateSoftwareToken({
onFailure: (err) => {
logger.debug('associateSoftwareToken failed', err);
rej(err);
},
associateSecretCode: (secretCode) => {
logger.debug('associateSoftwareToken sucess', secretCode);
res(secretCode);
}
});
});
}
/**
* verify TOTP setup
* @param {CognitoUser} user - the current user
* @param {string} challengeAnswer - challenge answer
* @return - A promise resolves is success
*/
public verifyTotpToken(user, challengeAnswer) {
logger.debug('verfication totp token', user, challengeAnswer);
return new Promise((res, rej) => {
user.verifySoftwareToken(challengeAnswer, 'My TOTP device', {
onFailure: (err) => {
logger.debug('verifyTotpToken failed', err);
rej(err);
},
onSuccess: (data) => {
logger.debug('verifyTotpToken success', data);
res(data);
}
});
});
}
/**
* Send MFA code to confirm sign in
* @param {Object} user - The CognitoUser object
* @param {String} code - The confirmation code
*/
public confirmSignIn(user: any, code: string, mfaType: string | null): Promise<any> {
if (!code) { return Promise.reject('Code cannot be empty'); }
const that = this;
return new Promise((resolve, reject) => {
user.sendMFACode(
code, {
onSuccess: (session) => {
logger.debug(session);
that._setCredentialsFromSession(session).then((cred) => {
that.user = user;
dispatchAuthEvent('signIn', user);
resolve(user);
}).catch(e => {
logger.debug('cannot get cognito credentials');
reject('signin failed');
});
},
onFailure: (err) => {
logger.debug('confirm signIn failure', err);
reject(err);
}
},
mfaType);
});
}
public completeNewPassword(
user: any,
password: string,
requiredAttributes: any
): Promise<any> {
if (!password) { return Promise.reject('Password cannot be empty'); }
const that = this;
return new Promise((resolve, reject) => {
user.completeNewPasswordChallenge(password, requiredAttributes, {
onSuccess: (session) => {
logger.debug(session);
that._setCredentialsFromSession(session).then((cred) => {
that.user = user;
dispatchAuthEvent('signIn', user);
resolve(user);
}).catch(e => {
logger.debug('cannot get cognito credentials');
reject('signin failed');
});
},
onFailure: (err) => {
logger.debug('completeNewPassword failure', err);
reject(err);
},
mfaRequired: (challengeName, challengeParam) => {
logger.debug('signIn MFA required');
user['challengeName'] = challengeName;
user['challengeParam'] = challengeParam;
resolve(user);
}
});
});
}
/**
* Update an authenticated users' attributes
* @param {CognitoUser} - The currently logged in user object
* @return {Promise}
**/
public updateUserAttributes(user, attributes:object): Promise<any> {
let attr:object = {};
const attributeList:Array<object> = [];
return this.userSession(user)
.then(session => {
return new Promise((resolve, reject) => {
for (const key in attributes) {
if ( key !== 'sub' &&
key.indexOf('_verified') < 0 &&
attributes[key] ) {
attr = {
'Name': key,
'Value': attributes[key]
};
attributeList.push(attr);
}
}
user.updateAttributes(attributeList, (err,result) => {
if (err) { reject(err); } else { resolve(result); }
});
});
});
}
/**
* Return user attributes
* @param {Object} user - The CognitoUser object
* @return - A promise resolves to user attributes if success
*/
public userAttributes(user): Promise<any> {
return this.userSession(user)
.then(session => {
return new Promise((resolve, reject) => {
user.getUserAttributes((err, attributes) => {
if (err) { reject(err); } else { resolve(attributes); }
});
});
});
}
public verifiedContact(user) {
const that = this;
return this.userAttributes(user)
.then(attributes => {
const attrs = that.attributesToObject(attributes);
const unverified = {};
const verified = {};
if (attrs['email']) {
if (attrs['email_verified']) {
verified['email'] = attrs['email'];
} else {
unverified['email'] = attrs['email'];
}
}
if (attrs['phone_number']) {
if (attrs['phone_number_verified']) {
verified['phone_number'] = attrs['phone_number'];
} else {
unverified['phone_number'] = attrs['phone_number'];
}
}
return {
verified,
unverified
};
});
}
/**
* Get current authenticated user
* @return - A promise resolves to curret authenticated CognitoUser if success
*/
public currentUserPoolUser(): Promise<any> {
if (!this.userPool) { return Promise.reject('No userPool'); }
let user = null;
if (Platform.isReactNative) {
const that = this;
return this.getSyncedUser().then(user => {
if (!user) { return Promise.reject('No current user in userPool'); }
return new Promise((resolve, reject) => {
user.getSession(function(err, session) {
if (err) { reject(err); } else { resolve(user); }
});
});
});
} else {
user = this.userPool.getCurrentUser();
if (!user) { return Promise.reject('No current user in userPool'); }
return new Promise((resolve, reject) => {
user.getSession(function(err, session) {
if (err) { reject(err); } else { resolve(user); }
});
});
}
}
/**
* Return the current user after synchornizing AsyncStorage
* @return - A promise with the current authenticated user
**/
private getSyncedUser(): Promise<any> {
const that = this;
return (this._userPoolStorageSync || Promise.resolve()).then(result => {
if (!that.userPool) {
return Promise.reject('No userPool');
}
that.credentials_source = 'userPool';
return that.userPool.getCurrentUser();
});
}
/**
* Get current authenticated user
* @return - A promise resolves to curret authenticated CognitoUser if success
*/
public async currentAuthenticatedUser(): Promise<any> {
let federatedUser = null;
try {
federatedUser = await Cache.getItem('federatedUser');
} catch (e) {
logger.debug('cannot load federated user from cache');
}
if (federatedUser) {
this.user = federatedUser;
logger.debug('get current authenticated federated user', this.user);
return this.user;
}
else {
logger.debug('get current authenticated userpool user');
try {
this.user = await this.currentUserPoolUser();
return this.user;
} catch (e) {
return Promise.reject('not authenticated');
}
}
}
/**
* Get current user's session
* @return - A promise resolves to session object if success
*/
public currentSession() : Promise<any> {
let user:any;
const that = this;
logger.debug('getting current session');
if (!this.userPool) { return Promise.reject('No userPool'); }
if (Platform.isReactNative) {
return this.getSyncedUser().then(user => {
if (!user) { return Promise.reject('No current user'); }
return that.userSession(user);
});
} else {
user = this.userPool.getCurrentUser();
if (!user) { return Promise.reject('No current user'); }
return this.userSession(user);
}
}
/**
* Get the corresponding user session
* @param {Object} user - The CognitoUser object
* @return - A promise resolves to the session
*/
public userSession(user) : Promise<any> {
return new Promise((resolve, reject) => {
logger.debug(user);
user.getSession(function(err, session) {
if (err) { reject(err); } else { resolve(session); }
});
});
}
/**
* Get authenticated credentials of current user.
* @return - A promise resolves to be current user's credentials
*/
public currentUserCredentials() : Promise<any> {
const that = this;
logger.debug('getting current user credential');
if (Platform.isReactNative) {
// asyncstorage
return Cache.getItem('federatedInfo')
.then((federatedInfo) => {
if (federatedInfo) {
// refresh the jwt token here if necessary
return that._refreshFederatedToken(federatedInfo);
} else {
return that.currentSession()
.then(session => {
return that._setCredentialsFromSession(session);
}).catch((error) => {
return that._setCredentialsForGuest();
});
}
}).catch((error) => {
return Promise.reject(error);
});
} else {
// first to check whether there is federation info in the local storage
const federatedInfo = Cache.getItem('federatedInfo');
if (federatedInfo) {
// refresh the jwt token here if necessary
return this._refreshFederatedToken(federatedInfo);
} else {
return this.currentSession()
.then(session => {
logger.debug('getting session success', session);
return this._setCredentialsFromSession(session);
}).catch((error) => {
logger.debug('getting session failed', error);
return this._setCredentialsForGuest();
});
}
}
}
private _refreshFederatedToken(federatedInfo) {
const { provider, user } = federatedInfo;
let token = federatedInfo.token;
let expires_at = federatedInfo.expires_at;
const that = this;
logger.debug('checking if federated jwt token expired');
if (expires_at < new Date().getTime()
&& typeof that._refreshHandlers[provider] === 'function') {
logger.debug('getting refreshed jwt token from federation provider');
return that._refreshHandlers[provider]().then((data) => {
logger.debug('refresh federated token sucessfully', data);
token = data.token;
expires_at = data.expires_at;
// Cache.setItem('federatedInfo', { provider, token, user, expires_at }, { priority: 1 });
return that._setCredentialsFromFederation({ provider, token, user, expires_at });
}).catch(e => {
logger.debug('refresh federated token failed', e);
this.cleanCachedItems();
return Promise.reject('refreshing federation token failed: ' + e);
});
} else {
if (!that._refreshHandlers[provider]) {
logger.debug('no refresh hanlder for provider:', provider);
this.cleanCachedItems();
return Promise.reject('no refresh hanlder for provider');
} else {
logger.debug('token not expired');
return this._setCredentialsFromFederation({provider, token, user, expires_at });
}
}
}
public currentCredentials(): Promise<any> {
return this.pickupCredentials();
}
/**
* Initiate an attribute confirmation request
* @param {Object} user - The CognitoUser
* @param {Object} attr - The attributes to be verified
* @return - A promise resolves to callback data if success
*/
public verifyUserAttribute(user, attr): Promise<any> {
return new Promise((resolve, reject) => {
user.getAttributeVerificationCode(attr, {
onSuccess(data) { resolve(data); },
onFailure(err) { reject(err); }
});
});
}
/**
* Confirm an attribute using a confirmation code
* @param {Object} user - The CognitoUser
* @param {Object} attr - The attribute to be verified
* @param {String} code - The confirmation code
* @return - A promise resolves to callback data if success
*/
public verifyUserAttributeSubmit(user, attr, code): Promise<any> {
if (!code) { return Promise.reject('Code cannot be empty'); }
return new Promise((resolve, reject) => {
user.verifyAttribute(attr, code, {
onSuccess(data) { resolve(data); },
onFailure(err) { reject(err); }
});
});
}
verifyCurrentUserAttribute(attr) {
const that = this;
return that.currentUserPoolUser()
.then(user => that.verifyUserAttribute(user, attr));
}
/**
* Confirm current user's attribute using a confirmation code
* @param {Object} attr - The attribute to be verified
* @param {String} code - The confirmation code
* @return - A promise resolves to callback data if success
*/
verifyCurrentUserAttributeSubmit(attr, code) {
const that = this;
return that.currentUserPoolUser()
.then(user => that.verifyUserAttributeSubmit(user, attr, code));
}
/**
* Sign out method
* @return - A promise resolved if success
*/
public async signOut(): Promise<any> {
try {
await this.cleanCachedItems();
} catch (e) {
logger.debug('failed to clear cached items');
}
const source = this.credentials_source;
if (source === 'aws' || source === 'userPool') {
if (!this.userPool) { return Promise.reject('No userPool'); }
const user = this.userPool.getCurrentUser();
if (user) {
logger.debug('user sign out', user);
user.signOut();
}
}
const that = this;
return new Promise((resolve, reject) => {
that._setCredentialsForGuest().then((cred) => {
dispatchAuthEvent('signOut', that.user);
that.user = null;
resolve();
}).catch((e) => {
logger.debug('cannot load guest credentials for unauthenticated user');
dispatchAuthEvent('signOut', that.user);
that.user = null;
resolve();
});
});
}
private async cleanCachedItems() {
// clear cognito cached item
const { identityPoolId, region, mandatorySignIn } = this._config;
if (identityPoolId) {
// work around for cognito js sdk to ensure clearCacheId works
const credentials = new CognitoIdentityCredentials(
{
IdentityPoolId: identityPoolId
}, {
region
});
credentials.clearCachedId();
}
// clear federatedInfo
await Cache.removeItem('federatedInfo');
await Cache.removeItem('federatedUser');
}
/**
* Change a password for an authenticated user
* @param {Object} user - The CognitoUser object
* @param {String} oldPassword - the current password
* @param {String} newPassword - the requested new password
* @return - A promise resolves if success
*/
public changePassword(user: any, oldPassword: string, newPassword: string): Promise<any> {
return this.userSession(user)
.then(session => {
return new Promise((resolve, reject) => {
user.changePassword(oldPassword, newPassword, (err, data) => {
if (err) {
logger.debug('change password failure', err);
reject(err);
} else {
resolve(data);
}
});
});
});
}
/**
* Initiate a forgot password request
* @param {String} username - the username to change password
* @return - A promise resolves if success
*/
public forgotPassword(username: string): Promise<any> {
if (!this.userPool) { return Promise.reject('No userPool'); }
if (!username) { return Promise.reject('Username cannot be empty'); }
const user = this.createCognitoUser(username);
return new Promise((resolve, reject) => {
user.forgotPassword({
onSuccess: () => { resolve(); },
onFailure: err => {
logger.debug('forgot password failure', err);
reject(err);
},
inputVerificationCode: data => {
resolve(data);
}
});
});
}
/**
* Confirm a new password using a confirmation Code
* @param {String} username - The username
* @param {String} code - The confirmation code
* @param {String} password - The new password
* @return - A promise that resolves if success
*/
public forgotPasswordSubmit(
username: string,
code: string,
password: string
): Promise<any> {
if (!this.userPool) { return Promise.reject('No userPool'); }
if (!username) { return Promise.reject('Username cannot be empty'); }
if (!code) { return Promise.reject('Code cannot be empty'); }
if (!password) { return Promise.reject('Password cannot be empty'); }
const user = this.createCognitoUser(username);
return new Promise((resolve, reject) => {
user.confirmPassword(code, password, {
onSuccess: () => { resolve(); },
onFailure: err => { reject(err); }
});
});
}
/**
* Get user information
* @async
* @return {Object }- current User's information
*/
public async currentUserInfo() {
const source = this.credentials_source;
if (!source || source === 'aws' || source === 'userPool') {
const user = await this.currentUserPoolUser()
.catch(err => logger.debug(err));
if (!user) { return null; }
try {
const attributes = await this.userAttributes(user);
const userAttrs:object = this.attributesToObject(attributes);
// check if the credentials is in the memory
if (!this.credentials) {
try {
await this.currentCredentials();
} catch (e) {
logger.debug('Failed to retrieve credentials while getting current user info', e);
}
}
const info = {
'id': this.credentials? this.credentials.identityId : undefined,
'username': user.username,
'attributes': userAttrs
};
return info;
} catch(err) {
logger.debug('currentUserInfo error', err);
return {};
}
}