Role Base Authentication

The system ensures only authorized users can access specific routes based on their assigned roles.

  1. The main routing file defines route paths and lazy-loaded modules for various components based on the user's role.

src/app-routing.module.ts
`
// Angular Imports
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

// project import
import { AdminComponent } from './theme/layout/admin/admin.component';
import { GuestComponent } from './theme/layout/guest/guest.component';
import { AuthGuardChild } from './theme/shared/_helpers/auth.guard';
import { Role } from './theme/shared/_helpers/role';

const routes: Routes = [
 .....
{
    path: '',
    component: AdminComponent,
    canActivateChild: [AuthGuardChild],
    children: [
      {
        path: '',
        loadComponent: () => import('./demo/dashboard/default/default.component').then((c) => c.DefaultComponent),
        data: { roles: [Role.Admin, Role.User] }
      },
      {
        path: 'default',
        loadComponent: () => import('./demo/dashboard/default/default.component').then((c) => c.DefaultComponent),
        data: { roles: [Role.Admin, Role.User] }
      },
      {
        path: 'analytics',
        loadComponent: () => import('./demo/dashboard/analytics/analytics.component').then((c) => c.AnalyticsComponent),
        data: { roles: [Role.Admin] }
      },
      ....
    ]
    ....
}
 
  1. Child Routing Module: Defines the child routes and applies role-based access.

src/app/demo/admin-panel/online-courses/online-courses-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

// project import
import { Role } from 'src/app/theme/shared/_helpers/role';

const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'dashboard',
        loadComponent: () => import('./online-dashboard/online-dashboard.component').then((c) => c.OnlineDashboardComponent),
        data: { roles: [Role.Admin] }
      },
      {
        path: 'teacher',
        loadChildren: () => import('./teacher/teacher.module').then((m) => m.TeacherModule),
        data: { roles: [Role.Admin, Role.User] }
      },
      ...
      {
        path: 'setting',
        loadChildren: () => import('./setting/setting.module').then((m) => m.SettingModule),
        data: { roles: [Role.Admin, Role.User] }
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class OnlineCoursesRoutingModule {}
  1. Role Management

src/app/theme/shared/_helpers/role.ts
export enum Role {
  User = 'User',
  Admin = 'Admin'
}
  1. Authentication Guard: This AuthGuardChild ensures that users can only access authorized routes.

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);

  /**
   * Determines whether a child route can be activated based on user authentication and authorization.
   *
   * @param route - The activated route snapshot that contains the route configuration and parameters.
   * @param state - The router state snapshot containing the current state.
   * @returns A boolean indicating whether the route can be activated. Redirects to an appropriate page if not.
   *
   * If the user is logged in and their role is authorized for the route, it returns true.
   * If the user is logged in but not authorized, redirects to the unauthorized page and returns false.
   * If the user is not logged in, redirects to the login page with the return URL and returns false.
   */

  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;
  }
}

Last updated