Mantis Angular
  • ✨Introduction
  • 🚀Quick Installation
  • 📂Directory Structure
  • 📄Page Structure
  • 🛠️Theme Configuration
  • 🎨Theme Layouts
  • ✏️How to
    • Dashboard as First Page
    • Login as First Page
    • Remove Authentication
    • Remove Role Base Authentication
    • Guard Children Routes
    • Role Base Authentication
  • 📦Dependencies
  • 🆘Support
  • 📅Changelog
Powered by GitBook
On this page
  1. How to

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
...
{
    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]
        }
      },
    ]
}
...
  1. Child Routing Module: Defines the child routes and applies role-based access.

src/app/demo/dashboard/dashboard-routing.module.ts
const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'default',
        loadComponent: () => import('./default/default.component').then((c) => c.DefaultComponent),
        data: {
          roles: [Role.Admin, Role.User]
        }
      },
      {
        path: 'analytics',
        loadComponent: () => import('./analytics/analytics.component').then((c) => c.AnalyticsComponent),
        data: {
          roles: [Role.Admin]
        }
      },
      {
        path: 'finance',
        loadComponent: () => import('./finance/finance.component').then((c) => c.FinanceComponent),
        data: {
          roles: [Role.Admin]
        }
      }
    ]
  }
];
  1. Role Management

src/app/theme/shared/components/_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/components/_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;
  }
}
PreviousGuard Children RoutesNextDependencies

Last updated 5 months ago

✏️