Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular routing based on roles

I am using Angular and this is for my authentication check:

export class EnsureAuthenticated implements CanActivate {
    constructor(private auth: AuthService, private router: Router) {}
    canActivate(): boolean {
        if (localStorage.getItem('token')) {
            return true;
        }
        else {
            this.router.navigateByUrl('/login');
            return false;
        }
    }
}    

{ 
    path: 'path', 
    component: myComponent,
    canActivate: [EnsureAuthenticated]
}

It's working fine but my problem is this page can be accessed by both user and admin.

I know I didn't set any condition on it. How do I set the proper condition on it?

I don't want to access this page to admin

like image 741
my Test Avatar asked Dec 29 '25 05:12

my Test


1 Answers

See this example in stackblitz

In your app-routing.module.ts

const routes: Routes = [
   {
       path: "admin",
       component: AdminOnlyComponent,
       canActivate: [RoleGuardService],
       data: { roles: ['admin']}
   },
   ...
}

In your RoleGuardService

import { Injectable } from '@angular/core';
import { UserRolesService} from './user-roles.service';
import { Router, ActivatedRouteSnapshot } from '@angular/router';
@Injectable({
  providedIn: 'root'
})
export class RoleGuardService {

  constructor(private getUserRoles: UserRolesService) { }

  canActivate(route: ActivatedRouteSnapshot): boolean {
    return route.data.roles.some( ai => this.getUserRoles.getRoles().includes(ai) );
  }
}

In UserRolesService

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserRolesService {
   userRoles: string[] = [];

  constructor() { }

  setRoles(Roles: string[]){
    this.userRoles = Roles.slice(0);
  }

  getRoles(){
    return this.userRoles;
  }
}

Set roles when user logged in to the system or get those roles from your localstorage....

like image 84
dasunse Avatar answered Dec 31 '25 18:12

dasunse