When developing an application, I encountered the need to implement authorization to protect routes using AuthGuard. However, I now face the challenge of securing child routes based on a role system obtained from the backend during login. For example, if the user's role is 'admin,' they should have access to all routes; if the role is 'user,' they should only be able to access the 'notification' route. I attempted to use *ngIf, but it only hides the route and does not prevent users from accessing it via the URL.
auth.guard.ts
// Implementing the canActivate method with AuthService logic for authentication
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const isAuth = this.authService.getIsAuth();
if (!isAuth) {
this.router.navigate(['/sign-in']);
}
return isAuth;
}
roleAuth.guard.ts
// Implementation of canActivate for role-based authorization
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const role = this.authService.role();
if (role ==='Admin') {
// Stuck at handling admin authorization
}
if (role ==='moderator') {
// Stuck at moderator authorization
}
if (role ==='user') {
// Stuck at user authorization
}
return role;
}
app-routing.ts
// Setting up the routes with AuthGuard protection and children routes configuration
const routes: Routes = [
{ path: 'sign-in', component: SignInComponent },
{
path: '',
canActivate: [AuthGuard],
component: SideNavComponent,
children: [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{
path: 'dashboard',
loadChildren: () => import('./components/sidenav/pages/dashboard/dashboard.module')
.then(m => m.DashboardModule)
},
{
path: 'notifications',
loadChildren: () => import('./components/sidenav/pages/notifications/notifications.module')
.then(m => m.NotificationsModule)
},
],
},
];