-
Notifications
You must be signed in to change notification settings - Fork 0
/
cognitoUser.model.ts
79 lines (75 loc) · 1.97 KB
/
cognitoUser.model.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
import { isEmpty } from './utils';
/**
* A user stored in a Cognito User Pool.
*/
export class CognitoUser {
/**
* The id of the user.
*/
userId: string;
/**
* The email address of the user.
*/
email: string;
/**
* The fullname of the user.
*/
name: string;
/**
* The URI to the user's picture.
*/
picture: string;
/**
* The list of groups containing the user.
*/
groups: string[];
/**
* The user's (custom) attributes.
*/
attributes: { [attribute: string]: string | number };
constructor(x: any = {}) {
this.userId = x.userId || x.sub;
this.email = x.email;
this.name = x.name;
this.picture = x.picture;
this.groups = x.groups || this.parseGroupsFromClaims(x['cognito:groups']);
if (x.attributes) this.attributes = x.attributes;
else {
this.attributes = {};
Object.keys(x)
.filter(a => a.startsWith('custom:'))
.forEach(a => (this.attributes[a.slice('custom:'.length)] = x[a]));
}
}
// the groups claim can come in many forms, depending on the input payload type and version.
private parseGroupsFromClaims(groupsClaim: string | string[]): string[] {
if (!groupsClaim) return [];
// ['myGroup1', 'myGroup2']
if (Array.isArray(groupsClaim)) return groupsClaim;
// '[myGroup1 myGroup2]'
if (groupsClaim.startsWith('[')) return groupsClaim.slice(1, groupsClaim.length - 1).split(' ');
// 'myGroup1, myGroup2'
else return groupsClaim.split(',');
}
/**
* Check whether the user's attributes are valid.
*/
validate(): string[] {
const e: string[] = [];
if (isEmpty(this.name)) e.push('name');
if (isEmpty(this.email, 'email')) e.push('email');
return e;
}
/**
* Whether the user is part of the administrators group.
*/
isAdmin(): boolean {
return this.groups.includes('admins');
}
/**
* Whether the user is part of the robots group.
*/
isRobot(): boolean {
return this.groups.includes('robots');
}
}