I
I
Ivan Stroykin2017-01-23 14:15:28
Angular
Ivan Stroykin, 2017-01-23 14:15:28

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;
        }
    }

All roles are registered on the backend (for accurate verification on the server side). It is most logical to make a request to the back when initializing the application in order to get the entire list and then work with it. Lest there was a hardcode.
But here is when it is better to execute a request, where it is better to store all this and how best to process it, I would like to clarify with the experienced
. Some pages should not have access at all. On some pages, some roles have access, but there is no access to certain components on these pages.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Stroykin, 2017-06-30
@StivinKing

Might be useful to someone

routing
...
{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'}},
    ]
},
...

auth guard
...
// 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;
    }
}
...

Now, if roles is not set in data, then all authorized people have access (because it costs canActivate),
if roles in data are set, then only those roles that are listed will have access, the rest will be redirected to the specified page (in my primer - to the main )

T
TekVanDo, 2017-01-23
@TekVanDo

Реализую доступ на основе ui-роутера при заходе на страницу проверяется права доступа к ней. В качестве имплантации могу посоветовать https://github.com/Narzerus/angular-permission

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question