The system ensures only authorized users can access specific routes based on their assigned roles.
src/app/app-routing.module.ts
...
{
path: '',
component: AdminLayout,
canActivateChild: [AuthGuardChild],
children: [
{
path: 'dashboard',
loadChildren: () => import('./demo/dashboard/dashboard.module').then((m) => m.DashboardModule),
data: { roles: [Role.Admin, Role.User] }
},
{
path: 'widget/statistics',
loadComponent: () => import('./demo/widget/statistics/statistics.component').then((c) => c.StatisticsComponent),
data: {
roles: [Role.Admin, Role.User]
}
},
]
}
...
src/app/demo/dashboard/dashboard-routing.module.ts
const routes: Routes = [
{
path: '',
children: [
{
path: 'analytics',
loadComponent: () => import('./dash-analytics/dash-analytics.component').then((c) => c.DashAnalyticsComponent),
data: { roles: [Role.Admin, Role.User] }
},
{
path: 'sale',
loadComponent: () => import('./dash-sale/dash-sale.component').then((c) => c.DashSaleComponent),
data: { roles: [Role.Admin, Role.User] }
},
{
path: 'finance',
loadComponent: () => import('./finance/finance.component').then((c) => c.FinanceComponent),
data: { roles: [Role.Admin] }
}
]
}
];
src/app/theme/shared/_helpers/role.ts
export enum Role {
User = 'User',
Admin = 'Admin'
}
src/app/theme/shared/_helpers/auth.guard.ts
import { Injectable, inject } from '@angular/core';
import { Router, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild } from '@angular/router';
import { AuthenticationService } from '../service/authentication.service';
@Injectable({ providedIn: 'root' })
export class AuthGuardChild implements CanActivateChild {
private router = inject(Router);
private authenticationService = inject(AuthenticationService);
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authenticationService.currentUserValue;
if (currentUser && this.authenticationService.isLoggedIn()) {
const { roles } = route.data;
if (roles && !roles.includes(currentUser.user.role)) {
// User not authorized, redirect to unauthorized page
this.router.navigate(['/unauthorized']);
return false;
}
// User is logged in and authorized for child routes
return true;
}
// User not logged in, redirect to login page
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}