Answer the question
In order to leave comments, you need to log in
How to properly implement roles (angular 2)?
Good day,
There was a need to create roles in the project (user, manager, admin, etc.). What is the most correct and reasonable way to implement this possibility?
Now I have "AuthGuard" service to check authorization
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean>|boolean {
if (this.authService.isLoggedIn()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
Answer the question
In order to leave comments, you need to log in
Might be useful to someone
...
{path: '', component: Test1Component, canActivate: [AuthGuard], canActivateChild: [AuthGuard],
children: [
{path: 'test2', component: Test2Component, data: {title: 'Тест 2', roles: ['admin', 'user']}},
{path: 'test3', component: Test3Component, data: {title: 'Тест 3', roles: ['admin']}},
{path: 'test4', component: Test4Component, data: {title: 'Тест 4'}},
]
},
...
...
// canActivate единожды проверяет авторизован или нет
canActivateChild(route: ActivatedRouteSnapshot): Promise<boolean>|boolean {
let myRole = 'user'; // Получаем роль при инициализации приложения запросом на backend либо по своему усмотрению
let roles = route.data['roles'] as Array<string>;
if (!roles || roles.indexOf(myRole) != -1) return true;
else {
this.router.navigate(['']);
return false;
}
}
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question