MCPcopy
hub / github.com/angular/angularfire / AuthComponent

Class AuthComponent

sample/src/app/auth/auth.component.ts:44–114  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

42 imports: [AsyncPipe]
43})
44export class AuthComponent implements OnDestroy {
45
46 private readonly auth = inject(Auth);
47 protected readonly authState = authState(this.auth);
48
49 private readonly transferState = inject(TransferState);
50 private readonly transferStateKey = makeStateKey<string|undefined>("auth:uid");
51 protected readonly uid = this.authState.pipe(map(u => u?.uid)).pipe(
52 isPlatformServer(inject(PLATFORM_ID)) ?
53 tap(it => this.transferState.set(this.transferStateKey, it)) :
54 this.transferState.hasKey(this.transferStateKey) ?
55 startWith(this.transferState.get(this.transferStateKey, undefined)) :
56 tap()
57);
58
59 protected readonly showLoginButton = this.uid.pipe(map(it => !it));
60 protected readonly showLogoutButton = this.uid.pipe(map(it => !!it));
61
62 private readonly unsubscribeFromOnIdTokenChanged: (() => void) | undefined;
63 private readonly unsubscribeFromBeforeAuthStateChanged: (() => void) | undefined;
64
65 constructor() {
66 if (isPlatformBrowser(inject(PLATFORM_ID))) {
67
68 this.unsubscribeFromOnIdTokenChanged = onIdTokenChanged(this.auth, async (user) => {
69 if (user) {
70 const idToken = await user.getIdToken();
71 cookies.set("__session", idToken);
72 } else {
73 cookies.remove("__session");
74 }
75 });
76
77 let priorCookieValue: string|undefined;
78 this.unsubscribeFromBeforeAuthStateChanged = beforeAuthStateChanged(this.auth, async (user) => {
79 priorCookieValue = cookies.get("__session");
80 const idToken = await user?.getIdToken();
81 if (idToken) {
82 cookies.set("__session", idToken);
83 } else {
84 cookies.remove("__session");
85 }
86 }, async () => {
87 // If another beforeAuthStateChanged rejects, revert the cookie (best-effort)
88 if (priorCookieValue) {
89 cookies.set("__session", priorCookieValue);
90 } else {
91 cookies.remove("__session");
92 }
93 });
94 }
95 }
96
97 ngOnDestroy(): void {
98 this.unsubscribeFromBeforeAuthStateChanged?.();
99 this.unsubscribeFromOnIdTokenChanged?.();
100 }
101

Callers

nothing calls this directly

Calls 2

setMethod · 0.65
getMethod · 0.65

Tested by

no test coverage detected