|
1 | 1 | import { Injectable, Inject } from '@angular/core'
|
2 | 2 | import {
|
3 | 3 | FIREBASE_AUTH_SERVER_ADMIN_APP,
|
4 |
| - FIREBASE_AUTH_SERVER_USER_JWT |
| 4 | + FIREBASE_AUTH_SERVER_USER_JWT, |
| 5 | + FIREBASE_AUTH_OBJ_TS |
5 | 6 | } from './server.common'
|
6 | 7 | import { auth } from 'firebase-admin'
|
7 | 8 | import { of } from 'rxjs'
|
8 |
| -import { flatMap } from 'rxjs/operators' |
| 9 | +import { flatMap, catchError, map, tap } from 'rxjs/operators' |
| 10 | +import { TransferState } from '@angular/platform-browser' |
9 | 11 |
|
10 | 12 | function validateToken(auth: auth.Auth, jwt: string) {
|
11 | 13 | return of(auth.verifyIdToken(jwt))
|
12 | 14 | }
|
13 | 15 |
|
| 16 | +function byMappingItToUndefined(err: any) { |
| 17 | + return of(undefined) |
| 18 | +} |
| 19 | + |
| 20 | +function cacheToBrowser(ts: TransferState) { |
| 21 | + return function(obj: any) { |
| 22 | + ts.set(FIREBASE_AUTH_OBJ_TS, obj) |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +function toPsuedoUserObject(jwtObj: any) { |
| 27 | + return { |
| 28 | + isAnonymous: false, // TODO |
| 29 | + uid: jwtObj.uid, |
| 30 | + displayName: jwtObj.name, |
| 31 | + email: jwtObj.email, |
| 32 | + emailVerified: jwtObj.email_verified, |
| 33 | + photoURL: jwtObj.picture, |
| 34 | + phoneNumber: jwtObj.phone_number, |
| 35 | + // providerData: '', |
| 36 | + providerId: jwtObj.firebase && jwtObj.firebase.sign_in_provider |
| 37 | + } |
| 38 | +} |
| 39 | + |
14 | 40 | // tslint:disable:no-this
|
15 | 41 | // tslint:disable-next-line:no-class
|
16 | 42 | @Injectable()
|
17 | 43 | export class FirebaseServerAuth {
|
18 | 44 | constructor(
|
| 45 | + private ts: TransferState, |
19 | 46 | @Inject(FIREBASE_AUTH_SERVER_ADMIN_APP) private authAdmin: auth.Auth,
|
20 | 47 | @Inject(FIREBASE_AUTH_SERVER_USER_JWT) private jwt: string
|
21 | 48 | ) {}
|
22 | 49 |
|
23 | 50 | readonly validatedToken_ = this.jwt
|
24 |
| - ? validateToken(this.authAdmin, this.jwt).pipe(flatMap(a => a)) |
| 51 | + ? validateToken(this.authAdmin, this.jwt).pipe( |
| 52 | + flatMap(a => a), |
| 53 | + map(toPsuedoUserObject), |
| 54 | + tap(cacheToBrowser(this.ts)), |
| 55 | + catchError(byMappingItToUndefined) |
| 56 | + ) |
25 | 57 | : of(null)
|
26 | 58 |
|
27 | 59 | readonly user = this.validatedToken_
|
|
0 commit comments