Skip to content

Instantly share code, notes, and snippets.

@mohammedmatar
Created March 24, 2018 08:55
Show Gist options
  • Save mohammedmatar/5fa2496e1cdcccaec1ade6267243bafb to your computer and use it in GitHub Desktop.
Save mohammedmatar/5fa2496e1cdcccaec1ade6267243bafb to your computer and use it in GitHub Desktop.
Angular 5 - AuthGuard with
import { Injectable } from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';
import { Observable } from 'rxjs/Observable';
import {NbAuthService} from '@nebular/auth';
import { tap } from 'rxjs/operators/tap';
import 'rxjs/add/operator/mergeMap';
import {UsersDsService} from '../data-source/users-ds.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor( private authService: NbAuthService, private router: Router, private userDS: UsersDsService) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.isAuthenticated()
.pipe(
tap(authenticated => {
if (!authenticated) {
this.router.navigate(['auth/login']);
} else {
this.userDS.getRole().subscribe(role => {
switch (role) {
case 'admin': this.redirectIfNotInTheSamePage(next.routeConfig.path,
'pages/dashboard-page', 'dashboard-page'); break;
case 'donor': this.redirectIfNotInTheSamePage(next.routeConfig.path,
'pages/donor-dashboard', 'donor-dashboard'); break;
case 'parent': this.redirectIfNotInTheSamePage(next.routeConfig.path,
'pages/parent-dashboard', 'parent-dashboard'); break;
case 'partner': this.redirectIfNotInTheSamePage(next.routeConfig.path,
'pages/partner-dashboard', 'partner-dashboard'); break;
case 'student': this.redirectIfNotInTheSamePage(next.routeConfig.path,
'pages/student-dashboard', 'student-dashboard'); break;
}
});
}
}),
);
}
private redirectIfNotInTheSamePage(iWantGoTo: string, allowedFullPath: string, allowedPath: string) {
(iWantGoTo !== allowedPath) ? this.router.navigate([allowedFullPath]) : '';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment