Skip to content

Instantly share code, notes, and snippets.

@blakazulu
Created January 25, 2021 14:17
Show Gist options
  • Save blakazulu/046211e144443b2f30f10ce7b9d7fcd7 to your computer and use it in GitHub Desktop.
Save blakazulu/046211e144443b2f30f10ce7b9d7fcd7 to your computer and use it in GitHub Desktop.
Angular CMS
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