/
server.auth.module.ts
83 lines (77 loc) 路 2.34 KB
/
server.auth.module.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
import { NgModule, APP_INITIALIZER } from '@angular/core'
import { AngularFireAuth } from 'angularfire2/auth'
import { FirebaseServerAuth } from './server.auth.service'
import {
FIREBASE_AUTH_SERVER_ADMIN_APP,
FIREBASE_AUTH_SERVER_USER_JWT
} from './server.common'
import { initializeApp, credential, auth, apps } from 'firebase-admin'
import { EnvironmentService } from '../../environment'
import { FIREBASE_AUTH_COOKIE_STO_KEY, FIREBASE_AUTH_OBJ_TS } from './tokens'
import { CookieService } from '../../cookies/browser'
import { TransferState, StateKey } from '@angular/platform-browser'
import { take, tap } from 'rxjs/operators'
import { FirebaseUniversalAuthService } from './browser.auth.service'
function firebaseAdminAppAlreadyExists() {
return apps.length ? true : false
}
function repairInlinePem(str?: string) {
return str ? str.replace(/\\n/g, '\n') : ''
}
export function fbAdminFactory(es: EnvironmentService) {
!firebaseAdminAppAlreadyExists() &&
initializeApp({
credential: credential.cert({
projectId: es.config.FIREBASE_PROJECT_ID,
clientEmail: es.config.SERVER_FIREBASE_CLIENT_EMAIL,
privateKey: repairInlinePem(es.config.SERVER_FIREBASE_PRIVATE_KEY)
}),
databaseURL: es.config.FIREBASE_DATABASE_URL
})
return auth()
}
export function getUserJwt(cs: CookieService, key: string) {
return cs.get(key)
}
export function onBootstrap(
transferState: TransferState,
auth: FirebaseServerAuth,
tsKey: StateKey<string>
) {
return () => {
return auth.user
.pipe(
take(1),
tap(user => transferState.set(tsKey, user))
)
.toPromise()
}
}
// tslint:disable-next-line:no-class
@NgModule({
providers: [
FirebaseServerAuth,
{ provide: AngularFireAuth, useExisting: FirebaseServerAuth },
{
provide: FirebaseUniversalAuthService,
useExisting: FirebaseServerAuth
},
{
provide: FIREBASE_AUTH_SERVER_ADMIN_APP,
useFactory: fbAdminFactory,
deps: [EnvironmentService]
},
{
provide: FIREBASE_AUTH_SERVER_USER_JWT,
useFactory: getUserJwt,
deps: [CookieService, FIREBASE_AUTH_COOKIE_STO_KEY]
},
{
provide: APP_INITIALIZER,
useFactory: onBootstrap,
deps: [TransferState, FirebaseServerAuth, FIREBASE_AUTH_OBJ_TS],
multi: true
}
]
})
export class FirebaseAuthServerModule {}