Skip to content

Instantly share code, notes, and snippets.

@ITECHINN
Forked from codediodeio/auth.guard.ts
Created June 12, 2018 10:33
Show Gist options
  • Save ITECHINN/5b1f9f4e4181955da0633e535fa5e97f to your computer and use it in GitHub Desktop.
Save ITECHINN/5b1f9f4e4181955da0633e535fa5e97f to your computer and use it in GitHub Desktop.
Angular Firebase Router Guard with Browser Refresh
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) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> {
return this.afAuth.authState
.take(1)
.map(user => !!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