Created
January 25, 2021 14:17
-
-
Save blakazulu/046211e144443b2f30f10ce7b9d7fcd7 to your computer and use it in GitHub Desktop.
Angular CMS
This file contains 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 {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router'; | |
import {Observable} from 'rxjs'; | |
import {AngularFirebaseService} from '../services/angular-firebase.service'; | |
import {map, take, tap} from 'rxjs/operators'; | |
import {User} from '../interfaces/user'; | |
import {ConsoleLoggerService} from '../services/console-logger.service'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class AdminGuard implements CanActivate { | |
constructor(private afService: AngularFirebaseService, | |
private logs: ConsoleLoggerService, | |
private router: Router) { | |
} | |
canActivate( | |
route: ActivatedRouteSnapshot, | |
state: RouterStateSnapshot): | |
Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { | |
return this.afService.user$ | |
.pipe( | |
take(1), | |
map((user: User) => !!(user && user.roles.admin)), | |
tap((isAdmin) => { | |
if (!isAdmin) { | |
this.logs.warn('Access is denied, Admins only allowed'); | |
this.router.navigateByUrl('home').then(); | |
} | |
})); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment