user-route-access-service.ts 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { Injectable, isDevMode } from '@angular/core';
  2. import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
  3. import { Principal } from '../';
  4. import { LoginModalService } from '../login/login-modal.service';
  5. import { StateStorageService } from './state-storage.service';
  6. @Injectable({ providedIn: 'root' })
  7. export class UserRouteAccessService implements CanActivate {
  8. constructor(
  9. private router: Router,
  10. private loginModalService: LoginModalService,
  11. private principal: Principal,
  12. private stateStorageService: StateStorageService
  13. ) {}
  14. canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Promise<boolean> {
  15. const authorities = route.data['authorities'];
  16. // We need to call the checkLogin / and so the principal.identity() function, to ensure,
  17. // that the client has a principal too, if they already logged in by the server.
  18. // This could happen on a page refresh.
  19. return this.checkLogin(authorities, state.url);
  20. }
  21. checkLogin(authorities: string[], url: string): Promise<boolean> {
  22. const principal = this.principal;
  23. return Promise.resolve(
  24. principal.identity().then(account => {
  25. if (!authorities || authorities.length === 0) {
  26. return true;
  27. }
  28. if (account) {
  29. return principal.hasAnyAuthority(authorities).then(response => {
  30. if (response) {
  31. return true;
  32. }
  33. if (isDevMode()) {
  34. console.error('User has not any of required authorities: ', authorities);
  35. }
  36. return false;
  37. });
  38. }
  39. this.stateStorageService.storeUrl(url);
  40. this.router.navigate(['accessdenied']).then(() => {
  41. // only show the login dialog, if the user hasn't logged in yet
  42. if (!account) {
  43. this.loginModalService.open();
  44. }
  45. });
  46. return false;
  47. })
  48. );
  49. }
  50. }