Skip to content

Instantly share code, notes, and snippets.

@vsaw
Last active May 18, 2020 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vsaw/d9c340d2151965dbdd6747943664a4dd to your computer and use it in GitHub Desktop.
Save vsaw/d9c340d2151965dbdd6747943664a4dd to your computer and use it in GitHub Desktop.
Fixes NgZone Issues in angularfire auth as described in https://github.com/angular/angularfire/issues/2355
import { Injectable, Inject, Optional, NgZone } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable, of, pipe, UnaryFunction } from 'rxjs';
import { map, switchMap, take, observeOn, shareReplay } from 'rxjs/operators'
import { User } from 'firebase/app';
import { ɵAngularFireSchedulers, FirebaseOptions, FirebaseAppConfig, FIREBASE_OPTIONS, FIREBASE_APP_NAME, ɵfirebaseAppFactory, ɵZoneScheduler } from '@angular/fire';
export type AuthPipeGenerator = (next: ActivatedRouteSnapshot, state: RouterStateSnapshot) => AuthPipe;
export type AuthPipe = UnaryFunction<Observable<User | null>, Observable<boolean | any[]>>;
@Injectable({
providedIn: 'any'
})
export class AngularFireAuthGuardFix implements CanActivate {
authState: Observable<User | null>;
zone: NgZone;
constructor(
@Inject(FIREBASE_OPTIONS) options: FirebaseOptions,
@Optional() @Inject(FIREBASE_APP_NAME) nameOrConfig: string | FirebaseAppConfig | null | undefined,
zone: NgZone,
private router: Router
) {
const auth = of(undefined).pipe(
// observeOn(new ɵAngularFireSchedulers(zone).outsideAngular),
// switchMap(() => zone.runOutsideAngular(() => import('firebase/auth'))),
// observeOn(new ɵAngularFireSchedulers(zone).insideAngular),
switchMap(() => zone.run(() => import('firebase/auth'))),
map(() => ɵfirebaseAppFactory(options, zone, nameOrConfig)),
map(app => app.auth()),
shareReplay({ bufferSize: 1, refCount: false }),
);
this.authState = auth.pipe(
switchMap(auth => new Observable<User | null>(auth.onAuthStateChanged.bind(auth)))
);
}
canActivate = (next: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
const authPipeFactory = next.data.authGuardPipe as AuthPipeGenerator || (() => loggedIn);
return this.authState.pipe(
take(1),
authPipeFactory(next, state),
map(can => typeof can == "boolean" ? can : this.router.createUrlTree(<any[]>can))
);
}
}
export const canActivate = (pipe: AuthPipeGenerator) => ({
canActivate: [AngularFireAuthGuardFix], data: { authGuardPipe: pipe }
});
export const loggedIn: AuthPipe = map(user => !!user);
export const isNotAnonymous: AuthPipe = map(user => !!user && !user.isAnonymous);
export const idTokenResult = switchMap((user: User | null) => user ? user.getIdTokenResult() : of(null));
export const emailVerified: AuthPipe = map(user => !!user && user.emailVerified);
export const customClaims = pipe(idTokenResult, map(idTokenResult => idTokenResult ? idTokenResult.claims : []));
export const hasCustomClaim = (claim: string) => pipe(customClaims, map(claims => claims.hasOwnProperty(claim)));
export const redirectUnauthorizedTo = (redirect: any[]) => pipe(loggedIn, map(loggedIn => loggedIn || redirect));
export const redirectLoggedInTo = (redirect: any[]) => pipe(loggedIn, map(loggedIn => loggedIn && redirect || true));
@vsaw
Copy link
Author

vsaw commented Apr 24, 2020

Summary

Full disclosure this is copied from https://github.com/angular/angularfire/blob/master/src/auth-guard/auth-guard.ts and fixes angular/angularfire#2355 as a quick workaround.

The important changes can be found in https://gist.github.com/vsaw/d9c340d2151965dbdd6747943664a4dd#file-angular-fire-auth-guard-fix-guard-ts-L26-L29

License

The MIT License

Copyright (c) 2020, Valentin Sawadski

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment