Guest User

Untitled

a guest
May 22nd, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. const routes: Routes = [
  2. {
  3. path: '',
  4. component: DashboardViewComponent
  5. },
  6. {
  7. path: 'login',
  8. component: LoginViewComponent
  9. },
  10. {
  11. path: 'protected/foo',
  12. component: FooViewComponent,
  13. data: {allowAccessTo: ['Administrator']},
  14. canActivate: [RouteGuard]
  15. },
  16. {
  17. path: '**',
  18. component: ErrorNotFoundViewComponent
  19. }
  20. ];
  21.  
  22. import {Injectable} from '@angular/core';
  23. import {Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
  24. import {AuthService} from '../services/auth.service';
  25.  
  26. @Injectable()
  27. export class RouteGuard implements CanActivate {
  28.  
  29. constructor(
  30. private router: Router,
  31. private auth: AuthService
  32. ) {}
  33.  
  34. canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  35. const { auth, router } = this;
  36. const { allowAccessTo } = next.data;
  37. const identity = auth.getIdentity();
  38. if (
  39. identity &&
  40. allowAccessTo.indexOf(identity.role)
  41. ) {
  42. // all good, proceed with activating route
  43. return true;
  44. }
  45. if (identity) {
  46. // TODO show ErrorForbiddenViewComponent instead of redirecting
  47. console.log('403 Forbidden >>', next);
  48. }
  49. else {
  50. // not logged in: redirect to login page with the return url
  51. const [returnUrl, returnQueryParams] = state.url.split('?');
  52. console.log('401 Unauthorised >>', returnUrl, returnQueryParams, next);
  53. router.navigate(['/login'], {queryParams: {returnUrl, returnQueryParams}});
  54. }
  55. return false;
  56. }
  57. }
Add Comment
Please, Sign In to add comment