Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update NgxPermissionsGuard to return UrlTree when redirecting instead of using router.navigate #242

Open
rms2219 opened this issue Sep 5, 2024 · 1 comment

Comments

@rms2219
Copy link

rms2219 commented Sep 5, 2024

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report 
[x] Feature request
[ ] Documentation issue or request

Current behavior

If the permissions guard is configured with a redirect, and the permissions test fails, the guard uses the Router service to navigate to the configured route.

Expected behavior

As of Angular 7.1, router guards can return a boolean or an instance of UrlTree. By returning a UrlTree instead of using the router to do the navigation, we can prioritize redirects when there are multiple guards applied to a route, both with competing redirects.

Minimal reproduction of the problem with instructions

const authGuard: CanActivateFn|CanMatchFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
  const authService = inject(AuthService);
  const router = inject(Router);
  return authService.isAuthenticated$
    .pipe(
      switchMap(isAuthenticated => {
        if (isAuthenticated) {
          return true;
        }

        return of(router.createUrlTree(['/login']));
    }),
  );
};

// Routes
{
    path: 'home',
    canMatch: [authGuard, ngxPermissionsGuard],
    component: AdminHomeComponent,
    data: {
      permissions: {
        only: ['ROLE_ADMIN'],
        redirectTo: {
          navigationCommands: ['unauthorized'],
          navigationExtras: {
            skipLocationChange: true,
          },
        }
      },
    }
}

The code above will navigate to the "unauthorized" route instead of "login", even though the authGuard guard has priority.

Environment


Angular version: 17.1.1
ngx-permissions version: 17.1.0


Browser:
- [ ] Chrome (desktop) version XX
- [ ] Chrome (Android) version XX
- [ ] Chrome (iOS) version XX
- [ ] Firefox version XX
- [ ] Safari (desktop) version XX
- [ ] Safari (iOS) version XX
- [ ] IE version XX
- [ ] Edge version XX
- [x] Brave version 1.69.160
@rms2219
Copy link
Author

rms2219 commented Sep 5, 2024

I should add, as a workaround for the time being, I've made use of both canMatch and canActivate route guards on the routes that are affected. I've used my authGuard w/ canMatch and ngxPermissionsGuard with canActivate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant