Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const routes: Routes = [
- {
- path: '',
- component: DashboardViewComponent
- },
- {
- path: 'login',
- component: LoginViewComponent
- },
- {
- path: 'protected/foo',
- component: FooViewComponent,
- data: {allowAccessTo: ['Administrator']},
- canActivate: [RouteGuard]
- },
- {
- path: '**',
- component: ErrorNotFoundViewComponent
- }
- ];
- 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;
- }
- }
Add Comment
Please, Sign In to add comment