diff --git a/src/app/authentication.guard.ts b/src/app/authentication.guard.ts index 3883037a46bfe57fd992fdba30d81389f61c636e..cec297d1bb377e163c193e08af9f23227feccee4 100644 --- a/src/app/authentication.guard.ts +++ b/src/app/authentication.guard.ts @@ -7,6 +7,7 @@ import 'rxjs/add/observable/of'; import 'rxjs/add/operator/catch'; import { NotificationService } from './notification.service'; import { UserRole } from './user-roles.enum'; +import { User } from './user'; @Injectable() export class AuthenticationGuard implements CanActivate { @@ -16,21 +17,22 @@ export class AuthenticationGuard implements CanActivate { } canActivate(next: ActivatedRouteSnapshot, - state: RouterStateSnapshot): Observable<boolean> { - return this.authenticationService.getUser().map(user => { - // Get roles having access to this route - // undefined if every logged in user should have access regardless of its role - const requiredRoles = next.data['roles'] as Array<UserRole>; - // Allow access when user is logged in AND - // the route doesn't require a specific role OR - // the user's role is one of the required roles - if (user && (!requiredRoles || requiredRoles.includes(user.role))) { - return true; - } - this.notificationService.show(`You're not authorized to view this page.`); - // TODO: redirect to error page - this.router.navigate(['/']); - return false; - }); + state: RouterStateSnapshot): boolean { + // Get active user + const user: User = this.authenticationService.getUser(); + // Get roles having access to this route + // undefined if every logged in user should have access regardless of its role + const requiredRoles = next.data['roles'] as Array<UserRole>; + // Allow access when user is logged in AND + // the route doesn't require a specific role OR + // the user's role is one of the required roles + if (user && (!requiredRoles || requiredRoles.includes(user.role))) { + return true; + } + + this.notificationService.show(`You're not authorized to view this page.`); + // TODO: redirect to error page + this.router.navigate(['/']); + return false; } } diff --git a/src/app/authentication.service.ts b/src/app/authentication.service.ts index c4afdd393fa5e7b86026db8e573f1dca4a84e4e1..b04d62359d9a76595424c7b1f42da931d741b6df 100644 --- a/src/app/authentication.service.ts +++ b/src/app/authentication.service.ts @@ -41,16 +41,16 @@ export class AuthenticationService { this.user = undefined; } - getUser(): Observable<User> { - return of(this.user); + getUser(): User { + return this.user; } - isLoggedIn(): Observable<boolean> { - return of(this.user !== undefined); + isLoggedIn(): boolean { + return this.user !== undefined; } - getRole(): Observable<UserRole> { - return of(this.user.role); + getRole(): UserRole { + return this.isLoggedIn() ? this.user.role : undefined; } }