Skip to content

Instantly share code, notes, and snippets.

@DrDanL
Last active August 21, 2020 12:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DrDanL/76c5e5ec7c7442ef3ce6790db84794b7 to your computer and use it in GitHub Desktop.
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/
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']);
}
})
}
}
@robpataki
Copy link

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 👍

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