-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathWebAuth0AuthClient.ts
More file actions
230 lines (190 loc) · 5.47 KB
/
Copy pathWebAuth0AuthClient.ts
File metadata and controls
230 lines (190 loc) · 5.47 KB
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
import * as auth0 from 'auth0-js';
import * as R from 'ramda';
import {
throwIfMissingRequiredParameters,
StorageAPI,
PACKAGES,
IAuthState,
IAuthClient,
IStorageOptions,
} from '@8base/utils';
import jwtDecode from 'jwt-decode';
export interface IAuth0Data {
state?: object;
isEmailVerified: boolean;
idToken: string;
email: string;
idTokenPayload: any;
firstName?: string;
lastName?: string;
avatar?: string;
}
export interface IAuth0IdTokenData {
given_name: string;
family_name: string;
nickname: string;
name: string;
picture: string;
updated_at: string;
email: string;
email_verified: boolean;
iss: string;
}
export interface IAuth0ClientOptions {
domain: string;
clientId: string;
redirectUri: string;
scope?: string;
audience?: string;
responseType?: string;
responseMode?: string;
}
export interface IWebAuth0AuthClientOptions extends IAuth0ClientOptions {
logoutRedirectUri?: string;
}
const isEmptyOrNil = R.either(R.isNil, R.isEmpty);
const isEmailVerified = R.pipe(
R.pathOr<boolean>(false, ['idTokenPayload', 'email_verified']),
R.equals(true),
);
const getEmail = R.path(['idTokenPayload', 'email']);
const getIdToken = R.path(['idToken']);
const getIdTokenPayload = R.propOr(undefined, 'idTokenPayload');
const getState = R.propOr(undefined, 'state');
/**
* Creates instance of the web auth0 auth client.
*/
class WebAuth0AuthClient implements IAuthClient {
public auth0: auth0.WebAuth;
private logoutHasCalled: boolean;
private readonly logoutRedirectUri?: string;
private storageAPI: StorageAPI<IAuthState>;
constructor(options: IWebAuth0AuthClientOptions, storageOptions: IStorageOptions<IAuthState> = {}) {
throwIfMissingRequiredParameters(['domain', 'clientId', 'redirectUri'], PACKAGES.WEB_AUTH0_AUTH_CLIENT, options);
const { logoutRedirectUri, clientId, ...restOptions } = options;
this.storageAPI = new StorageAPI<IAuthState>(
storageOptions.storage || window.localStorage,
storageOptions.storageKey || 'auth',
storageOptions.initialState,
);
this.logoutHasCalled = false;
this.logoutRedirectUri = logoutRedirectUri;
this.auth0 = new auth0.WebAuth({
clientID: clientId,
responseType: 'token id_token',
scope: 'openid email profile',
...restOptions,
});
}
public setState(state: IAuthState): void {
this.storageAPI.setState(state);
}
public getState(): IAuthState {
return this.storageAPI.getState();
}
public getTokenInfo() {
const { token } = this.storageAPI.getState();
if (!token) {
return undefined;
}
try {
return (jwtDecode(token || '') as IAuth0IdTokenData) || undefined;
} catch (err) {
return undefined;
}
}
public purgeState(): void {
this.storageAPI.purgeState();
}
public checkIsEmailVerified() {
const tokenResult = this.getTokenInfo();
return tokenResult && tokenResult.email_verified;
}
public checkIsAuthorized(): boolean {
const { token } = this.getState();
return R.not(isEmptyOrNil(token));
}
public authorize(options: object = {}): void {
if (!this.logoutHasCalled) {
// @ts-ignore
this.auth0.authorize({
...options,
});
}
}
public checkSession(options: object = {}): Promise<IAuth0Data> {
return new Promise((resolve: any, reject) => {
this.auth0.checkSession(options, (error, result: any) => {
if (error) {
reject(error || {});
return;
}
const idToken = (getIdToken(result) as string) || '';
const jwtResult: IAuth0IdTokenData = jwtDecode(idToken) || {};
resolve({
idToken,
firstName: jwtResult.given_name,
lastName: jwtResult.family_name,
picture: jwtResult.picture,
email: getEmail(result),
idTokenPayload: getIdTokenPayload(result),
isEmailVerified: isEmailVerified(result),
state: getState(result),
});
});
});
}
public changePassword(): Promise<{ email: string }> {
const { email = '' } = this.getState();
return new Promise((resolve, reject) => {
this.auth0.changePassword(
{
connection: 'Username-Password-Authentication',
email,
},
(error) => {
if (error) {
reject(error || {});
return;
}
resolve({ email });
},
);
});
}
public getAuthorizedData(): Promise<IAuth0Data> {
return new Promise((resolve: Function, reject) => {
this.auth0.parseHash((error, authResult) => {
if (error) {
reject(error);
return;
}
const idToken = (getIdToken(authResult) as string) || '';
if (idToken) {
const jwtResult: IAuth0IdTokenData = jwtDecode(idToken) || {};
resolve({
idToken,
firstName: jwtResult.given_name,
lastName: jwtResult.family_name,
picture: jwtResult.picture,
email: getEmail(authResult),
idTokenPayload: getIdTokenPayload(authResult),
isEmailVerified: isEmailVerified(authResult),
state: getState(authResult),
});
}
});
});
}
public logout(options: object = {}): void {
window.addEventListener('unload', () => {
this.purgeState();
});
this.logoutHasCalled = true;
this.auth0.logout({
returnTo: this.logoutRedirectUri,
...options,
});
}
}
export { WebAuth0AuthClient };