This repository has been archived by the owner on Mar 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 194
/
account-management.service.ts
634 lines (549 loc) · 21 KB
/
account-management.service.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
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import {Config} from '../config/config'
import {Logger} from './logger.service';
import * as sjcl from '../assets/vendor/sjcl';
declare const AWS: any;
declare const AWSCognito: any;
export enum UserState {
SignedOut = 0,
SignedIn = 1,
PendingConfirmation = 2,
InvalidCredentials = 3
}
export interface IUserRegistration {
email?: string;
givenName?: string;
familyName?: string;
username?: string;
password?: string;
}
export interface IUserLogin {
username?: string;
password?: string;
}
interface IUserAttribute {
Name: string;
Value: string;
}
@Injectable()
export class CognitoUtil {
private static _USER_POOL_ID = Config['USER_POOL_ID'];
private static _USER_POOL_DOMAIN_NAME = Config['USER_POOL_DOMAIN_NAME'];
private static _CLIENT_ID: string = Config['CLIENT_ID'];
private static _IDENTITY_POOL_ID: string = Config['IDENTITY_POOL_ID'];
private static _REGION: string = Config['REGION'];
private static _MOBILE_REDIRECT_URI = 'spacefinder://callback'
private static _WEB_REDIRECT_URI = 'http://localhost:8100'
private static _RESPONSE_TYPE = 'code';
public static getRegion(): string {
return CognitoUtil._REGION;
}
public static getHostedUiLoginMobileUrl(): string {
return 'https://' + CognitoUtil._USER_POOL_DOMAIN_NAME + '/login?redirect_uri=' + CognitoUtil._MOBILE_REDIRECT_URI + '&response_type=' + CognitoUtil._RESPONSE_TYPE + '&client_id=' + CognitoUtil._CLIENT_ID;
}
public static getHostedUiLoginWebUrl(): any {
return 'https://' + CognitoUtil._USER_POOL_DOMAIN_NAME + '/login?redirect_uri=' + CognitoUtil._WEB_REDIRECT_URI + '&response_type=' + CognitoUtil._RESPONSE_TYPE + '&client_id=' + CognitoUtil._CLIENT_ID;
}
private static getHostedUiTokenUrl(): string {
return 'https://' + CognitoUtil._USER_POOL_DOMAIN_NAME + '/oauth2/token'
}
public static getIdTokenFromAuthCode(authCode, platform: string, http: Http): Promise<any> {
return new Promise((resolve, reject) => {
let headers = new Headers();
let requestRedirectUri;
switch (platform) {
case 'mobile':
requestRedirectUri = CognitoUtil._MOBILE_REDIRECT_URI;
break;
case 'web':
requestRedirectUri = CognitoUtil._WEB_REDIRECT_URI;
break;
}
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body =
'grant_type=authorization_code&' +
'client_id=' + CognitoUtil._CLIENT_ID + '&' +
'redirect_uri=' + requestRedirectUri + '&' +
'code=' + authCode;
http.post(CognitoUtil.getHostedUiTokenUrl(), body, {headers: headers})
.map(res => res.json())
.subscribe(data => {
resolve(data);
//TODO: Catch any post error
});
});
}
public static getClientId(): string {
return CognitoUtil._CLIENT_ID;
}
public static getIdentityPoolId(): string {
return CognitoUtil._IDENTITY_POOL_ID;
}
public static getUserPoolId(): string {
return CognitoUtil._USER_POOL_ID;
}
public static getCognitoIdentityId(): string {
return AWS.config.credentials.identityId;
}
public static getUsername(): string {
// Retrieve username from local storage. Return null if it does not exist
return LocalStorage.get('userName');
}
public static setUsername(username: string) {
LocalStorage.set('userName', username);
}
public static getUserId(): string {
// Retrieve user ID from local storage. Return null if it does not exist
return LocalStorage.get('userId');
}
public static getUserProfile(): Object {
// Retrieve user profile attributes from local storage
return LocalStorage.getObject('userProfile');
}
public static getUserGroup(): string {
// Retrieve the user group from the local storage
return LocalStorage.get("userGroup");
}
public static getUserState(): UserState {
// Retrieve user state from local storage. Return null if it does not exist
switch (parseInt(LocalStorage.get('userState'))) {
case 0:
return UserState.SignedOut;
case 1:
return UserState.SignedIn;
case 2:
return UserState.PendingConfirmation;
case 3:
return UserState.InvalidCredentials;
default:
return null;
}
};
public static setUserState(userState: UserState) {
LocalStorage.set('userState', JSON.stringify(userState));
}
public static getUserPool() {
// Initialize Cognito User Pool
let poolData: Object = {
UserPoolId: CognitoUtil._USER_POOL_ID,
ClientId: CognitoUtil._CLIENT_ID
};
AWSCognito.config.region = CognitoUtil._REGION;
AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: CognitoUtil._IDENTITY_POOL_ID
});
// Initialize AWS config object with dummy keys - required if unauthenticated access is not enabled for identity pool
AWSCognito.config.update({accessKeyId: 'dummyvalue', secretAccessKey: 'dummyvalue'});
return new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
}
public static getCognitoUser() {
let username = LocalStorage.get('userName');
let userData = {
Username: username,
Pool: CognitoUtil.getUserPool()
};
return new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
}
public static getCurrentUser() {
return CognitoUtil.getUserPool().getCurrentUser();
}
}
@Injectable()
export class UserRegistrationService {
public static signUp(signUpData: IUserRegistration): Promise<void> {
let attributeList: IUserAttribute[] = [];
let dataEmail: IUserAttribute = {
Name: 'email',
Value: signUpData.email
};
let dataGivenName: IUserAttribute = {
Name: 'given_name',
Value: signUpData.givenName
};
let dataFamilyName: IUserAttribute = {
Name: 'family_name',
Value: signUpData.familyName
};
let attributeEmail = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataEmail);
let attributeGivenName = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataGivenName);
let attributeFamilyName = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataFamilyName);
attributeList.push(attributeEmail);
attributeList.push(attributeGivenName);
attributeList.push(attributeFamilyName);
let promise: Promise<void> = new Promise<void>((resolve, reject) => {
CognitoUtil.getUserPool().signUp(signUpData.username, signUpData.password, attributeList, undefined, (err, result) => {
if (err) {
reject(err);
return;
}
console.log('Username is ' + result.user.getUsername());
console.log('Sign-up successful!');
// Update user state to 'pendingConfirmation'
CognitoUtil.setUsername(signUpData.username);
CognitoUtil.setUserState(UserState.PendingConfirmation);
// Sign-up successful. Callback without error.
resolve();
});
});
return promise;
}
public static confirmSignUp(confirmationCode: string): Promise<void> {
let cognitoUser = CognitoUtil.getCognitoUser();
let promise: Promise<void> = new Promise<void>((resolve, reject) => {
cognitoUser.confirmRegistration(confirmationCode, true, (err: Error, data: any) => {
if (err) {
reject(err);
return;
}
CognitoUtil.setUserState(UserState.SignedIn);
resolve(data);
});
});
return promise;
}
public static resendConfirmationCode(): Promise<void> {
let cognitoParams = {
ClientId: CognitoUtil.getClientId(),
Username: CognitoUtil.getUsername()
};
let promise: Promise<void> = new Promise<void>((resolve, reject) => {
new AWSCognito.CognitoIdentityServiceProvider().resendConfirmationCode(cognitoParams, (err: Error, data: any) => {
if (err) {
reject(err);
return;
}
resolve(data);
});
});
return promise;
}
}
@Injectable()
export class UserLoginService {
private static _userTokens = {
accessToken: undefined,
idToken: undefined,
refreshToken: undefined
};
public static getAccessToken() {
let accessToken: string = UserLoginService._userTokens.accessToken;
if (!accessToken) {
// retrieve from Local Storage if it exists
accessToken = LocalStorage.get('userTokens.accessToken');
UserLoginService._userTokens.accessToken = accessToken;
}
return accessToken;
};
public static getIdToken() {
let idToken: string = UserLoginService._userTokens.idToken;
if (!idToken) {
// retrieve from Local Storage if it exists
idToken = LocalStorage.get('userTokens.idToken');
UserLoginService._userTokens.idToken = idToken;
}
return idToken;
};
public static getRefreshToken() {
let refreshToken: string = UserLoginService._userTokens.refreshToken;
if (!refreshToken) {
// retrieve from Local Storage if it exists
refreshToken = LocalStorage.get('userTokens.refreshToken');
UserLoginService._userTokens.refreshToken = refreshToken;
}
return refreshToken;
}
public static getAwsAccessKey() {
if (AWS.config.credentials == null) {
return LocalStorage.get('userTokens.awsAccessKeyId');
}
return AWS.config.credentials.accessKeyId || LocalStorage.get('userTokens.awsAccessKeyId');
}
public static getAwsSecretAccessKey() {
return AWS.config.credentials.secretAccessKey || LocalStorage.get('userTokens.awsSecretAccessKey');
}
public static getAwsSessionToken() {
return AWS.config.credentials.sessionToken || LocalStorage.get('userTokens.awsSessionToken');
}
private static clearUserState() {
// Clear user tokens
UserLoginService._userTokens = {
accessToken: undefined,
idToken: undefined,
refreshToken: undefined
};
LocalStorage.set('userTokens.accessToken', null);
LocalStorage.set('userTokens.idToken', null);
LocalStorage.set('userTokens.refreshToken', null);
LocalStorage.set('userTokens.awsAccessKeyId', null);
LocalStorage.set('userTokens.awsSecretAccessKey', null);
LocalStorage.set('userTokens.awsSessionToken', null);
// Clear user state
CognitoUtil.setUserState(UserState.SignedOut);
// Clear user profile attributes
LocalStorage.set('userProfile', null);
// Clear username and user ID attributes
LocalStorage.set('userId', null);
LocalStorage.set('userName', null);
};
public static signIn(userLogin: IUserLogin): Promise<void> {
let authenticationData = {
Username: userLogin.username,
Password: userLogin.password
};
let authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
CognitoUtil.setUsername(userLogin.username);
console.log('Authenticating user ' + userLogin.username);
let cognitoUser = CognitoUtil.getCognitoUser();
let promise: Promise<void> = new Promise<void>((resolve, reject) => {
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log(result);
UserLoginService.completeSignIn(result.getAccessToken().getJwtToken(),result.getIdToken().getJwtToken(),result.getRefreshToken().getToken()).then(() => {
resolve();
}).catch((err) => {
reject(err);
});
},
onFailure: function (err) {
// Check for user not confirmed exception
if (err.code === 'UserNotConfirmedException') {
// Set user state to pending confirmation
CognitoUtil.setUserState(UserState.PendingConfirmation);
} else {
CognitoUtil.setUserState(UserState.InvalidCredentials);
}
reject(err);
}
});
});
return promise;
}
public static completeSignIn(accessToken: string, idToken: string, refreshToken: string): Promise<void> {
let promise: Promise<void> = new Promise<void>((resolve, reject) => {
// Save user tokens to local state
UserLoginService._userTokens.accessToken = accessToken;
UserLoginService._userTokens.idToken = idToken;
UserLoginService._userTokens.refreshToken = refreshToken;
LocalStorage.set('userTokens.idToken', UserLoginService._userTokens.idToken);
console.log('%cCognito User Pools Identity Token: ', Logger.LeadInStyle, UserLoginService.getIdToken());
LocalStorage.set('userTokens.accessToken', UserLoginService._userTokens.accessToken);
console.log('%cCognito User Pools Access Token: ', Logger.LeadInStyle, UserLoginService.getAccessToken());
LocalStorage.set('userTokens.refreshToken', UserLoginService._userTokens.refreshToken);
console.log('%cCognito User Pools Refresh Token: ', Logger.LeadInStyle, UserLoginService.getRefreshToken());
/*
Extract the user group from the identity token.
First, get the identity token payload and then perform a Base64 decoding
so you can later extract the user group.
*/
let idTokenPayload = UserLoginService._userTokens.idToken.split('.')[1];
let idTokenDecoded = JSON.parse(sjcl.codec.utf8String.fromBits(sjcl.codec.base64url.toBits(idTokenPayload)));
CognitoUtil.setUsername(idTokenDecoded["cognito:username"]);
let userName = idTokenDecoded["cognito:username"];
let userGroup = idTokenDecoded["cognito:groups"];
if (userGroup && userGroup.length > 0) {
LocalStorage.set('userGroup', userGroup);
} else {
/*
The user group is set only for the pre-defined users. By default
we assign them to client group.
*/
userGroup = 'clientGroup';
LocalStorage.set('userGroup', userGroup[0]);
}
console.log('%cCognito User Pools User Groups: ' + '%c%s belongs to group %s', Logger.LeadInStyle, "black",
userName, userGroup[0]);
// Set user state to authenticated
CognitoUtil.setUserState(UserState.SignedIn);
// Read user attributes and write to console
console.log('%cCognito User Pools User Attributes: ', Logger.LeadInStyle, idTokenDecoded);
// Write user profile attributes to local storage
LocalStorage.setObject('userProfile', idTokenDecoded);
UserLoginService.getAwsCredentials().then(() => {
LocalStorage.set('userId', CognitoUtil.getCognitoIdentityId());
console.log('%cCognito Identity ID: ', Logger.LeadInStyle, CognitoUtil.getCognitoIdentityId());
LocalStorage.set('userTokens.awsAccessKeyId', AWS.config.credentials.accessKeyId);
console.log('%cAWS Access Key ID: ', Logger.LeadInStyle, AWS.config.credentials.accessKeyId);
LocalStorage.set('userTokens.awsSecretAccessKey', AWS.config.credentials.secretAccessKey);
console.log('%cAWS Secret Access Key: ', Logger.LeadInStyle, AWS.config.credentials.secretAccessKey);
LocalStorage.set('userTokens.awsSessionToken', AWS.config.credentials.sessionToken);
console.log('%cAWS Session Token: ', Logger.LeadInStyle, AWS.config.credentials.sessionToken);
// Resolve promise if all is successful
resolve();
}).catch((err) => {
reject(err);
});
});
return promise;
}
public static signOut() {
// Clear local user state
UserLoginService.clearUserState();
// Logout from Cognito service
CognitoUtil.getCognitoUser().signOut();
AWS.config.credentials.clearCachedId();
}
public static globalSignOut() {
// Clear local user state
UserLoginService.clearUserState();
// Logout from Cognito service
CognitoUtil.getCognitoUser().globalSignOut();
AWS.config.credentials.clearCachedId();
}
public static changePassword(previousPassword: string, proposedPassword: string): Promise<void> {
let promise: Promise<void> = new Promise<void>((resolve, reject) => {
// first, load the valid tokens cached in the local store, if they are available
// see: https://github.com/aws/amazon-cognito-identity-js/issues/71
let cognitoUser = CognitoUtil.getCognitoUser();
cognitoUser.getSession((err: Error, session: any) => {
if (err) {
reject(err);
return;
}
cognitoUser.changePassword(previousPassword, proposedPassword, (err: Error, result: any) => {
if (err) {
reject(err);
return;
}
resolve(result);
});
});
});
return promise;
}
public static forgotPassword(username: string): Promise<void> {
// Set target username
CognitoUtil.setUsername(username);
// Get Cognito User with session
let cognitoUser = CognitoUtil.getCognitoUser();
let promise: Promise<void> = new Promise<void>((resolve, reject) => {
cognitoUser.forgotPassword({
onSuccess: (result) => {
console.log('Initiated reset password for username ' + username);
resolve(result);
},
onFailure: (err) => {
console.log('Failed to initiate reset password for username ' + username);
reject(err);
return;
}
});
});
return promise;
}
public static confirmForgotPassword(username: string, verificationCode: string, password: string): Promise<void> {
// Set target username
CognitoUtil.setUsername(username);
// Get Cognito User with session
let cognitoUser = CognitoUtil.getCognitoUser();
let promise: Promise<void> = new Promise<void>((resolve, reject) => {
cognitoUser.confirmPassword(verificationCode, password, {
onSuccess: (result) => {
console.log('Password successfully reset for username ' + username);
resolve(result);
},
onFailure: (err) => {
console.log('Password was not reset for username ' + username);
console.log(`Error: ${err.name}. ${err.message}`);
reject(err);
return;
}
});
});
return promise;
}
public static getAwsCredentials(): Promise<void> {
let promise: Promise<void> = new Promise<void>((resolve, reject) => {
// TODO: Integrate this method as needed into the overall module
// Add the User's Id token to the Cognito credentials login map
let logins = {};
logins['cognito-idp.' + CognitoUtil.getRegion() + '.amazonaws.com/' + CognitoUtil.getUserPoolId()] = LocalStorage.get('userTokens.idToken');;
// Set Cognito Identity Pool details
AWS.config.region = CognitoUtil.getRegion();
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: CognitoUtil.getIdentityPoolId()
});
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: CognitoUtil.getIdentityPoolId(),
Logins: logins
});
// Call refresh method to authenticate user and get new temp AWS credentials
if (AWS.config.credentials.needsRefresh()) {
AWS.config.credentials.clearCachedId();
AWS.config.credentials.get((err) => {
if (err) {
reject(err);
return;
}
resolve();
});
} else {
AWS.config.credentials.get((err) => {
if (err) {
console.error(err);
reject(err);
return;
}
resolve();
});
}
});
return promise;
}
}
export class UserProfileService {
public static getUserAttributes() {
let promise: Promise<Object> = new Promise<Object>((resolve, reject) => {
let cognitoUser = CognitoUtil.getCognitoUser();
cognitoUser.getSession((err: Error, session: any) => {
if (err) {
reject(err);
return;
}
cognitoUser.getUserAttributes((err: Error, result: any) => {
if (err) {
reject(err);
return;
}
let userAttributes = {};
for (var i = 0; i < result.length; i++) {
userAttributes[result[i].getName()] = result[i].getValue();
}
console.log('%cCognito User Pools User Attributes: ', Logger.LeadInStyle, userAttributes);
// Write user profile attributes to local storage
LocalStorage.setObject('userProfile', userAttributes);
resolve(userAttributes);
});
})
});
return promise;
}
}
@Injectable()
export class LocalStorage {
private static getLocalStorage() {
let storage = window.localStorage || localStorage;
if (!localStorage) {
throw new Error('Browser does not support local storage');
}
return storage;
}
public static set(key: string, value: string): void {
LocalStorage.getLocalStorage().setItem(key, value);
}
public static get(key: string): string {
return LocalStorage.getLocalStorage().getItem(key);
}
public static setObject(key: string, value: any): void {
LocalStorage.set(key, JSON.stringify(value));
}
public static getObject(key: string): any {
return JSON.parse(LocalStorage.get(key) || '{}');
}
public static remove(key: string): any {
LocalStorage.getLocalStorage().removeItem(key);
}
}
export const LOCAL_STORAGE_PROVIDERS: any[] = [
{provide: LocalStorage, useClass: LocalStorage}
];