Angular Guard for Role-Based Access Control
Tags: angular, rbac
Published: 2023-07-17 00:49:54

i want to create a Angular Guard for Role-Based Access Control this is my app-routing 
` 

```
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FormComponent } from './form/form.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { NewActionComponent } from './new-action/new-action.component';
import { NavbarComponent } from './navbar/navbar.component';
import { LoginComponent } from './login/login.component';
import { NavbarUserComponent } from './navbar-user/navbar-user.component';
import { EventComponent } from './event/event.component';
import { DoneeventComponent } from './doneevent/doneevent.component';
import { RegisterComponent } from './register/register.component';
import {authGuardGuard} from './core/guard/auth-guard.guard';
import { roleGuardGuard } from './core/guard/role-guard.guard';

const routes : Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate: [authGuardGuard, roleGuardGuard], data: {expectedRoles : ['Admin']} },
  { path: 'register', component: RegisterComponent, canActivate: [authGuardGuard], data: { expectedRoles : ['Admin'] } },
  { path: 'event', component: EventComponent, canActivate: [authGuardGuard], data: { expectedRoles : ['Admin'] } },
  { path: 'form', component: FormComponent, canActivate: [authGuardGuard], data: { expectedRoles : ['technicien'] } },
  { path: 'effectuer', component: DoneeventComponent, canActivate: [authGuardGuard], data: { expectedRoles : [ 'technicien'] } },
  { path: 'NewAction', component: NewActionComponent, canActivate: [authGuardGuard], data: { expectedRoles : ['technicien'] } },
  { path: '**', redirectTo: '/login' } // Redirect to the login page for any other routes
]


```
this is my login script 

```
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
`
and this is my login script 
`import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { SharedService } from '../shared.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  username: string = '';
  password: string = '';
  Role: string[] = ['Admin', 'technicien'];
  role: string = '';

  constructor(public _shared: SharedService, private router: Router) {}

  token: any;

  login() {
    this._shared.Login({
      role: this.role,
      username: this.username,
      Password: this.password,
    }).subscribe(
      res => {
        this.token = res;
        localStorage.setItem('token', this.token.mytoken);
        
        const userRole = this.token.role;
        const allowedRoles = this.token.expectedRoles;

        if (allowedRoles.includes(userRole)) {
          this.router.navigate(['/dashboard']);
        } else {
          this.router.navigate(['/form']);
        }
      },
      err => {
        console.log(err);
      }
    );
  }
}

```

and this is my role-guard 

```
import { ActivatedRouteSnapshot, CanActivateFn } from '@angular/router';

export const roleGuardGuard: CanActivateFn = (route, state) => {
  return isAuthorized(route);
};

function isAuthorized(route: ActivatedRouteSnapshot): boolean {
  const roles = ['Admin', 'technicien'];
  const expectedRoles = route.data['expectedRoles'];
  const roleMatches = roles.findIndex(role => expectedRoles.indexOf(role) !== -1);
  return roleMatches >= 0;
}
```

but its not working please if you know the solution talk with me