Skip to content

Commit a26b45f

Browse files
committed
feat: add match guard for private routes
1 parent 7c86678 commit a26b45f

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { TestBed } from '@angular/core/testing';
2+
import { CanActivateFn } from '@angular/router';
3+
4+
import { canCanGuard } from './can-can.guard';
5+
6+
describe('canCanGuard', () => {
7+
const executeGuard: CanActivateFn = (...guardParameters) =>
8+
TestBed.runInInjectionContext(() => canCanGuard(...guardParameters));
9+
10+
beforeEach(() => {
11+
TestBed.configureTestingModule({});
12+
});
13+
14+
it('should be created', () => {
15+
expect(executeGuard).toBeTruthy();
16+
});
17+
});
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { inject } from '@angular/core';
2+
import { CanActivateFn } from '@angular/router';
3+
import { Role } from '../user.model';
4+
import { UserStore } from '../user.store';
5+
6+
export const canCanGuard: CanActivateFn = (route, state) => {
7+
const userStore = inject(UserStore);
8+
9+
const activeUser = userStore.currentUser;
10+
const routeData = route.data;
11+
const roles = routeData?.['roles'] as string[] | undefined;
12+
13+
if (activeUser?.isAdmin && routeData?.['isAdmin']) {
14+
return true;
15+
}
16+
17+
if ([roles ?? []]?.length <= 0) return false;
18+
19+
const hasRole = roles?.some((roleName) =>
20+
activeUser?.roles.includes(roleName as Role),
21+
);
22+
return !!hasRole;
23+
};

0 commit comments

Comments
 (0)