Last active
August 21, 2020 12:07
-
-
Save DrDanL/76c5e5ec7c7442ef3ce6790db84794b7 to your computer and use it in GitHub Desktop.
Example of CanActivate being used to check if a user is logged in or not via Firebase - see https://leightley.com/angular-2-and-firebase-authentication-route-guard/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; | |
import { Observable } from 'rxjs/Observable'; | |
import { AngularFireAuth } from 'angularfire2/auth'; | |
import 'rxjs/add/operator/do'; | |
import 'rxjs/add/operator/map'; | |
import 'rxjs/add/operator/take'; | |
@Injectable() | |
export class AuthGuard implements CanActivate { | |
constructor(private afAuth: AngularFireAuth, private router: Router, private) {} | |
canActivate( | |
next: ActivatedRouteSnapshot, | |
state: RouterStateSnapshot): Observable<boolean> { | |
return this.afAuth.authState | |
.take(1) | |
.map(user => { | |
return !!user | |
}) | |
.do(loggedIn => { | |
if (!loggedIn) { | |
console.log("access denied") | |
this.router.navigate(['/login']); | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is great! I've just figured that using the
afAuth.authState
Observable in my AuthGuard make my weird Firebase DB 'PERMISSION DENIED' issue go away 👍