/
auth.ts
580 lines (476 loc) · 17.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
import {
Injectable,
} from '@angular/core'
// import { HttpClient } from '@angular/common/http'
import { Storage } from '@ionic/storage'
import {
JwtHelperService,
} from '@auth0/angular-jwt'
import {
Auth0UserProfile,
WebAuth,
} from 'auth0-js'
import Auth0Lock from 'auth0-lock'
import { Brolog } from 'brolog'
import {
BehaviorSubject,
Observable,
Subscription,
} from 'rxjs/Rx'
import 'rxjs/add/operator/map'
import {
AUTH0_SETTINGS,
} from '../config'
const STORAGE_KEY = {
ACCESS_TOKEN: 'access_token',
ID_TOKEN: 'id_token',
USER_PROFILE: 'user_profile',
/**
* OIDC-conformant refresh tokens: https://auth0.com/docs/api-auth/tutorials/adoption/refresh-tokens
* Silent Authentication: https://auth0.com/docs/api-auth/tutorials/silent-authentication
*/
REFRESH_TOKEN: 'refresh_token',
}
interface AuthSnapshot {
valid: boolean,
profile: Auth0UserProfile,
}
@Injectable()
export class Auth {
public snapshot: AuthSnapshot
private expireTimer: NodeJS.Timer | null
/**
* User Profile: https://auth0.com/docs/user-profile
* Structure of the User Profile: https://auth0.com/docs/user-profile/user-profile-structure
* Control the contents of an ID token: https://auth0.com/docs/tokens/id-token#control-the-contents-of-an-id-token
* OpenID Connect Standard Claims: https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
*/
private _profile: BehaviorSubject<Auth0UserProfile>
public get profile() {
this.log.verbose('Auth', 'get profile()')
return this._profile.asObservable()
.share()
.distinctUntilChanged()
}
private localProfile: Auth0UserProfile
/**
* Persisting user authentication with BehaviorSubject in Angular
* - https://netbasal.com/angular-2-persist-your-login-status-with-behaviorsubject-45da9ec43243
* BehaviorSubject.asObservable.toPromise() will not return the last value without next a new one! :(
* - https://github.com/ReactiveX/RxJS/issues/1478
* - https://github.com/Reactive-Extensions/RxJS/issues/1088
*/
private _valid: BehaviorSubject<boolean>
public get valid() {
this.log.verbose('Auth', 'get valid()')
return this._valid.asObservable() // .share()
.share()
.distinctUntilChanged()
}
private accessToken: string | null = null
private refreshToken: string | null = null
private _idToken: string | null = null
private get idToken() {
this.log.silly('Auth', 'get idToken() = %s', this._idToken && this._idToken.length)
return this._idToken
}
private set idToken(newIdToken) {
this.log.verbose('Auth', 'set idToken(%s)', newIdToken && newIdToken.length)
this._idToken = newIdToken
if (newIdToken) {
this.scheduleExpire(newIdToken)
} else {
this.unscheduleExpire()
}
}
private refreshSubscription: Subscription
constructor(
public log: Brolog,
// public httpClient: HttpClient,
public jwtHelper: JwtHelperService,
public storage: Storage,
) {
this.log.verbose('Auth', 'constructor()')
this.init()
}
public async init() {
this.log.verbose('Auth', 'init()')
this.snapshot = {} as AuthSnapshot
this.localProfile = {} as Auth0UserProfile
this._profile = new BehaviorSubject<Auth0UserProfile>({} as Auth0UserProfile)
this._profile.subscribe(p => this.snapshot.profile = p)
this._valid = new BehaviorSubject<boolean>(false)
this._valid.subscribe(v => this.snapshot.valid = v)
try {
await this.load()
// if (this.idToken && this.snapshot.profile) {
if (this.authenticated()) {
this.log.silly('Auth', 'init() from storage for user({email:%s})', this.snapshot.profile.email)
this._profile.next(this.localProfile)
this._valid.next(true)
} else {
this.log.silly('Auth', 'init() idToken(length:%s) & profile(%s) not ready',
this.idToken && this.idToken.length,
this.snapshot.profile,
)
this.log.silly('Auth', 'init() idToken: %s', this.idToken)
this._profile.next({} as Auth0UserProfile)
this._valid.next(false)
}
} catch (e) {
this.log.error('Auth', 'init() exception: %s', e.message)
return
}
}
/**
* Lock Configurable Options: https://auth0.com/docs/libraries/lock/v10/customization
*/
private getAuth0Lock(): Auth0LockStatic {
this.log.verbose('Auth', 'getAuth0Lock()')
const options: Auth0LockConstructorOptions = {
// oidcConformant: true,
languageDictionary: {
title: 'Chatie',
},
// Lock: Authentication Parameters
// - https://auth0.com/docs/libraries/lock/v10/sending-authentication-parameters#supported-parameters
auth: {
params: {
// scope: 'openid profile user_metadata app_metadata email offline_access ', // offline_access for refreshToken(?)
scope: 'openid email profile offline_access', // offline_access for refreshToken(?)
},
redirect: false, // must use popup for ionic2
responseType: 'id_token token', // token for `accessToken`
},
allowSignUp: false,
allowForgotPassword: false,
allowedConnections: ['github'],
initialScreen: 'login',
// usernameStyle: 'email',
socialButtonStyle: 'big',
mustAcceptTerms: true,
rememberLastLogin: true,
autofocus: true,
autoclose: false,
theme: {
logo: 'https://avatars2.githubusercontent.com/u/25162437?v=3&s=200',
primaryColor: '#32db64',
},
}
const auth0Lock = new Auth0Lock(
AUTH0_SETTINGS.CLIENT_ID,
AUTH0_SETTINGS.DOMAIN,
options,
)
// Rxjs.Observable.merge
// Rxjs.Observable.fromEvent(auth0Lock, 'unrecoverable_error')
// Rxjs.Observable.fromEvent(auth0Lock, 'authorization_error')
auth0Lock.on('unrecoverable_error', error => {
this.log.warn('Auth', 'login() on(unrecoverable_error) error:%s', error)
this._valid.error(error)
auth0Lock.hide()
})
auth0Lock.on('authorization_error', error => {
this.log.verbose('Auth', 'login() on(authorization_error)')
this._valid.error(error)
})
// Add callback for lock `authenticated` event
// TODO: replace on with Observable.fromEvent().switchMap(getProfile)
auth0Lock.on('authenticated', async (authResult) => {
this.log.verbose('Auth', 'login() on(authenticated, authResult={%s})',
Object.keys(authResult).join(','),
)
this.accessToken = authResult.accessToken
this.idToken = authResult.idToken
if (!this.idToken) {
this.log.error('Auth', 'login() Auth0Lock.on(authenticated) no idToken')
return
}
const profile = await this.getProfile()
this._profile.next(profile)
// auth0Lock.getProfile(this.idToken, (error, profile) => {
// if (error) {
// // Handle error
// this.log.warn('Auth', 'login() Auth0Lock.getProfile() error:%s', error)
// return
// }
// this.log.verbose('Auth', 'login() Auth0Lock.getProfile() profile:{email:%s,...}',
// profile.email,
// )
// }) // Auth0Lock.getProfile
await this.save()
this.scheduleRefresh()
auth0Lock.hide()
this.log.verbose('Auth', 'getAuth0Lock() Auth0Lock.on(authenticated) _valid.next(true)')
this._valid.next(true)
})
return auth0Lock
}
public async getProfile(): Promise<Auth0UserProfile> {
this.log.verbose('Auth', 'getProfile()')
return new Promise<Auth0UserProfile>((resolve, reject) => {
if (!this.idToken || !this.accessToken) {
const e = new Error('no id/access token')
this.log.error('Auth', 'getProfile() %s', e.message)
return reject(e)
}
// const userId: string = this.jwtHelper.decodeToken(this.idToken).sub
// this.getManagement().getUser(userId, (error, profile) => {
// auth0Lock.getProfile(this.idToken, (error, profile) => {
// auth0Lock.getUserInfo(this.accessToken, (error, profile) => {
this.getWebAuth().client.userInfo(this.accessToken, (error, profile) => {
this.log.verbose('Auth', 'getProfile() WebAuth.client.userInfo()')
if (error) {
const e = new Error(error.description)
this.log.error('Auth', 'getProfile() WebAuth.client.userInfo() %s', e.message)
return reject(e)
}
this.log.silly('Auth', 'getProfile() WebAuth.client.userInfo() got {email=%s,...}', profile.email)
return resolve(profile)
})
})
}
public getWebAuth() {
this.log.verbose('Auth', 'getWebAuth()')
return new WebAuth({
clientID: AUTH0_SETTINGS.CLIENT_ID,
domain: AUTH0_SETTINGS.DOMAIN,
})
}
/*
getManagement() {
this.log.verbose('Auth', 'getManagement')
if (!this.accessToken) {
throw new Error('no access token')
}
return new Management({
domain: AUTH0.DOMAIN,
token: this.accessToken,
})
}
*/
/*
https://github.com/auth0/lock/issues/541
authenticated$ = Observable
.fromEvent(this.authService.authLock, 'authenticated')
.do((authResult: any) => {
localStorage.setItem('id_token', authResult.idToken);
})
.map(()=>new auth.LoginSuccessAction({}));
getProfile(idToken: string): Observable<any>{
return new Observable(observer => {
this.lock.getProfile(idToken, (err, profile) => {
if (err) {
observer.error(err);
}
else {
console.log(profile);
observer.next(profile);
observer.complete();
}
});
});
}
*/
/**
*
*/
public login(): void {
this.log.verbose('Auth', 'login()')
const auth0Lock = this.getAuth0Lock()
// Call the show method to display the widget.
auth0Lock.show()
}
public logout(): void {
this.log.verbose('Auth', 'logout()')
// Unschedule the token refresh
this.unscheduleRefresh()
this.unscheduleExpire()
this.remove()
this._profile.next({} as Auth0UserProfile)
this._valid.next(false)
this.log.verbose('Auth', 'logout() _valid.next(false)')
this._valid.next(false)
}
public authenticated(): boolean {
// Check if there's an unexpired JWT
// It searches for an item in localStorage with key == 'id_token'
const invalid = !this.idToken || this.jwtHelper.isTokenExpired(this.idToken)
this.log.verbose('Auth', 'authenticated(): %s', !invalid)
return !invalid
}
private scheduleExpire(idToken: string|null): void {
this.log.verbose('Auth', 'scheduleExpire()')
if (this.expireTimer) {
clearTimeout(this.expireTimer)
this.log.silly('Auth', 'scheduleExpire() clearTimeout()')
this.expireTimer = null
}
if (!idToken) {
this.log.verbose('Auth', 'scheduleExpire() no idToken')
this.log.verbose('Auth', 'scheduleExpire() _valid.next(false)')
this._valid.next(false)
return
}
try {
const expire = this.jwtHelper.getTokenExpirationDate(idToken)
const now = new Date()
let timeout = expire.getTime() - now.getTime()
if (timeout < 0) {
timeout = 0
}
this.expireTimer = setTimeout(() => {
this.log.verbose('Auth', 'scheduleExpire() _valid.next(false)')
this._valid.next(false)
}, timeout)
this.log.silly('Auth', 'scheduleExpire() setTimeout(,%s) = %s hours',
timeout,
Math.round(timeout / 3600) / 1000,
)
} catch (e) {
this.log.error('Auth', 'scheduleExpire() exception: %s', e.message)
}
}
public scheduleRefresh() {
this.log.verbose('Auth', 'scheduleRefresh()')
// If the user is authenticated, use the token stream
// provided by angular2-jwt and flatMap the token
if (!this.idToken) {
this.log.error('Auth', 'scheduleRefresh() error: no this.idToken')
return
}
const source = Observable.of(this.idToken).flatMap(token => {
if (!token) {
const e = new Error('scheduleRefresh() failed to get token')
this.log.error('Auth', e.message)
throw e
}
const decodedToken = this.jwtHelper.decodeToken(token)
this.log.verbose('Auth', 'scheduleRefresh() for token {email:%s,...}', decodedToken.email)
// The delay to generate in this case is the difference
// between the expiry time and the issued at time
const jwtIat = this.jwtHelper.decodeToken(token).iat
const jwtExp = this.jwtHelper.decodeToken(token).exp
const iat = new Date(0)
const exp = new Date(0)
const delay = (exp.setUTCSeconds(jwtExp) - iat.setUTCSeconds(jwtIat))
return Observable.interval(delay)
})
this.refreshSubscription = source.subscribe(() => {
this.getNewJwt()
})
}
public async startupTokenRefresh() {
this.log.verbose('Auth', 'startupTokenRefresh()')
// http://stackoverflow.com/a/34190965/1123955
if (this.snapshot.valid) {
// If the user is authenticated, use the token stream
// provided by angular2-jwt and flatMap the token
// const source = this.authHttp.tokenStream.flatMap(
// token => {
// // Get the expiry time to generate
// // a delay in milliseconds
// const now: number = new Date().valueOf()
// const jwtExp: number = this.jwtHelper.decodeToken(token).exp
// const exp: Date = new Date(0)
// exp.setUTCSeconds(jwtExp)
// // XXX the delay should be shorter
// // becasue we should emit refresh before scheduleExpire()
// // maybe 1 hour?
// const delay: number = exp.valueOf() - now
// // Use the delay in a timer to
// // run the refresh at the proper time
// return Observable.timer(delay)
// },
// )
// // Once the delay time from above is
// // reached, get a new JWT and schedule
// // additional refreshes
// source.subscribe(() => {
// this.getNewJwt()
// this.scheduleRefresh()
// })
}
}
public unscheduleRefresh() {
this.log.verbose('Auth', 'unscheduleRefresh()')
// Unsubscribe fromt the refresh
if (this.refreshSubscription) {
this.refreshSubscription.unsubscribe()
}
}
public unscheduleExpire(): void {
this.log.verbose('Auth', 'unscheduleExpire()')
if (this.expireTimer) {
clearTimeout(this.expireTimer)
this.log.silly('Auth', 'unscheduleExpire() clearTimeout()')
this.expireTimer = null
}
}
public async getNewJwt() {
this.log.verbose('Auth', 'getNewJwt()')
// Get a new JWT from Auth0 using the refresh token saved
// in local storage
try {
// Configure Auth0
/**
* Token Lifetime: https://auth0.com/docs/tokens/id-token#token-lifetime
*/
this.getWebAuth().renewAuth({
// ???
// https://github.com/auth0/auth0.js/blob/master/example/index.html
// https://auth0.com/docs/libraries/auth0js/v8#using-renewauth-to-acquire-new-tokens
// https://auth0.com/forum/t/remember-me-in-authservice-using-auth0-js-v8/5037
//
// audience: 'https://example.com/api/v2',
// scope: 'read:something write:otherthing',
// Hosted Login Page: https://auth0.com/docs/hosted-pages/login
// redirectUri: 'https://zixia.auth0.com/login?client=g6P417oEmHON1BuPdsV9foNgP4h98dmh',
usePostMessage: true,
}, (err, authResult) => {
if (err) {
this.log.error('Auth', 'getNewJwt() WebAuth.renewAuth() error: %s', err)
return
}
this.accessToken = authResult.accessToken
this.idToken = authResult.idToken
this.refreshToken = authResult.refreshToken
this.save()
})
} catch (e) {
this.log.error('Auth', 'getNewJwt() error: %s', e.message)
}
}
public async save(): Promise<void> {
this.log.verbose('Auth', 'save()')
await this.storage.ready()
this.storage.set(STORAGE_KEY.ACCESS_TOKEN, this.accessToken)
this.storage.set(STORAGE_KEY.ID_TOKEN, this.idToken)
this.storage.set(STORAGE_KEY.REFRESH_TOKEN, this.refreshToken)
this.storage.set(STORAGE_KEY.USER_PROFILE, this.snapshot.profile)
}
public async remove(): Promise<void> {
this.log.verbose('Auth', 'remove()')
await this.storage.ready()
// Remove token from localStorage
this.storage.remove(STORAGE_KEY.ACCESS_TOKEN)
this.storage.remove(STORAGE_KEY.ID_TOKEN)
this.storage.remove(STORAGE_KEY.REFRESH_TOKEN)
this.storage.remove(STORAGE_KEY.USER_PROFILE)
this.accessToken = null
this.idToken = null
this.refreshToken = null
}
public async load(): Promise<void> {
this.log.verbose('Auth', 'load()')
await this.storage.ready()
this.log.silly('Auth', 'load() Storage.ready() done')
this.accessToken = await this.storage.get(STORAGE_KEY.ACCESS_TOKEN)
this.idToken = await this.storage.get(STORAGE_KEY.ID_TOKEN)
this.refreshToken = await this.storage.get(STORAGE_KEY.REFRESH_TOKEN)
this.localProfile = await this.storage.get(STORAGE_KEY.USER_PROFILE)
this.log.silly('Auth', 'load() Storage.get() all done. profile={email:%s,...}',
this.localProfile && this.localProfile.email,
)
}
}