Created
June 11, 2018 09:07
-
-
Save Warrenn/a4401545535fc45381404ca3bcfc73c3 to your computer and use it in GitHub Desktop.
ng6 rout guard
This file contains hidden or 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 {Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router'; | |
import {AuthService} from '../services/auth.service'; | |
@Injectable() | |
export class RouteGuard implements CanActivate { | |
constructor( | |
private router: Router, | |
private auth: AuthService | |
) {} | |
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) { | |
const { auth, router } = this; | |
const { allowAccessTo } = next.data; | |
const identity = auth.getIdentity(); | |
if ( | |
identity && | |
allowAccessTo.indexOf(identity.role) | |
) { | |
// all good, proceed with activating route | |
return true; | |
} | |
if (identity) { | |
// TODO show ErrorForbiddenViewComponent instead of redirecting | |
console.log('403 Forbidden >>', next); | |
} | |
else { | |
// not logged in: redirect to login page with the return url | |
const [returnUrl, returnQueryParams] = state.url.split('?'); | |
console.log('401 Unauthorised >>', returnUrl, returnQueryParams, next); | |
router.navigate(['/login'], {queryParams: {returnUrl, returnQueryParams}}); | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment