-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
auth.ts
78 lines (65 loc) · 2.54 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
import { Injectable, Inject, Optional, NgZone, PLATFORM_ID } from '@angular/core';
import { Observable, of, from } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { FirebaseAppConfig, FirebaseOptions } from '@angular/fire';
import { User, auth } from 'firebase/app';
import { FirebaseAuth, FirebaseOptionsToken, FirebaseNameOrConfigToken, _firebaseAppFactory, FirebaseZoneScheduler } from '@angular/fire';
@Injectable()
export class AngularFireAuth {
/**
* Firebase Auth instance
*/
public readonly auth: FirebaseAuth;
/**
* Observable of authentication state; as of Firebase 4.0 this is only triggered via sign-in/out
*/
public readonly authState: Observable<User|null>;
/**
* Observable of the currently signed-in user's JWT token used to identify the user to a Firebase service (or null).
*/
public readonly idToken: Observable<string|null>;
/**
* Observable of the currently signed-in user (or null).
*/
public readonly user: Observable<User|null>;
/**
* Observable of the currently signed-in user's IdTokenResult object which contains the ID token JWT string and other
* helper properties for getting different data associated with the token as well as all the decoded payload claims
* (or null).
*/
public readonly idTokenResult: Observable<auth.IdTokenResult|null>;
constructor(
@Inject(FirebaseOptionsToken) options:FirebaseOptions,
@Optional() @Inject(FirebaseNameOrConfigToken) nameOrConfig:string|FirebaseAppConfig|null|undefined,
@Inject(PLATFORM_ID) platformId: Object,
private zone: NgZone
) {
const scheduler = new FirebaseZoneScheduler(zone, platformId);
this.auth = zone.runOutsideAngular(() => {
const app = _firebaseAppFactory(options, zone, nameOrConfig);
return app.auth();
});
this.authState = scheduler.keepUnstableUntilFirst(
scheduler.runOutsideAngular(
new Observable(subscriber => {
const unsubscribe = this.auth.onAuthStateChanged(subscriber);
return { unsubscribe };
})
)
);
this.user = scheduler.keepUnstableUntilFirst(
scheduler.runOutsideAngular(
new Observable(subscriber => {
const unsubscribe = this.auth.onIdTokenChanged(subscriber);
return { unsubscribe };
})
)
);
this.idToken = this.user.pipe(switchMap(user => {
return user ? from(user.getIdToken()) : of(null)
}));
this.idTokenResult = this.user.pipe(switchMap(user => {
return user ? from(user.getIdTokenResult()) : of(null)
}));
}
}