Last active
January 18, 2023 10:15
-
-
Save lukichev/2e7819a688cdd1fc1ea0460bdf5aee10 to your computer and use it in GitHub Desktop.
Role based router permissions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// auth.guard.ts | |
import {Injectable} from '@angular/core'; | |
import {Router, CanActivate, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router'; | |
import {AuthService} from './auth.service'; | |
@Injectable() | |
export class AuthGuard implements CanActivate { | |
constructor(private router: Router, | |
private authService: AuthService) { | |
} | |
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { | |
const userRole: string = this.authService.userRole; | |
const permission = route.data["permission"]; | |
let canActivate: boolean; | |
if (!permission) throw new Error('Permissions is not setup!'); | |
if (!permission.only.length) throw new Error('Roles are not setup!'); | |
canActivate = permission.only.includes(userRole); | |
if (!canActivate) this.router.navigate([permission.redirectTo]); | |
return canActivate; | |
} | |
} | |
// app.route.ts | |
import {Route} from "@angular/router"; | |
import {AuthGuard} from "../_auth/auth.guard"; | |
export const AppRoute: Route = { | |
path: "/", | |
component: AppComponent, | |
canActivate: [AuthGuard], | |
data: { | |
permission: { | |
only: ['user', 'admin'], | |
redirectTo: 'signin' | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment