Skip to content

Commit

Permalink
refactor: use RedirectCommand in auth guard
Browse files Browse the repository at this point in the history
  • Loading branch information
jrassa committed Oct 2, 2024
1 parent 0036485 commit ea0892d
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions src/app/core/auth/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { inject } from '@angular/core';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import {
ActivatedRouteSnapshot,
CanActivateFn,
GuardResult,
RedirectCommand,
Router,
RouterStateSnapshot
} from '@angular/router';

import { of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
Expand Down Expand Up @@ -35,7 +42,9 @@ function toAuthGuardConfig(
return {};
}

export function authGuard(configOrRoles?: string | string[] | Partial<AuthGuardConfig>) {
export function authGuard(
configOrRoles?: string | string[] | Partial<AuthGuardConfig>
): CanActivateFn {
return (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
// eslint-disable-next-line deprecation/deprecation
const router = inject(Router);
Expand All @@ -58,18 +67,18 @@ export function authGuard(configOrRoles?: string | string[] | Partial<AuthGuardC

return session$.pipe(
switchMap(() => sessionService.getCurrentEua()),
map((): boolean | UrlTree => {
map((): GuardResult => {
// The user still isn't authenticated
if (!session().isAuthenticated()) {
return router.parseUrl('/signin');
return new RedirectCommand(router.parseUrl('/signin'));
}

// Check to see if the user needs to agree to the end user agreement
if (config.requiresEua && !session().isEuaCurrent()) {
return router.parseUrl('/eua');
return new RedirectCommand(router.parseUrl('/eua'));
}

if (!session().isAdmin()) {
if (!session().isAdmin() || true) {
// -----------------------------------------------------------
// Check the role requirements for the route
// -----------------------------------------------------------
Expand All @@ -78,7 +87,7 @@ export function authGuard(configOrRoles?: string | string[] | Partial<AuthGuardC
!session().hasSomeRoles(config.roles)
) {
// The user doesn't have the needed roles to view the page
return router.parseUrl('/unauthorized');
return new RedirectCommand(router.parseUrl('/unauthorized'));
}
}

Expand Down

0 comments on commit ea0892d

Please sign in to comment.