Angular 2角色和权限 [英] Angular 2 roles and permissions

查看:252
本文介绍了Angular 2角色和权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用了angular2和laravel 5.3.在laravel中,当用户登录服务器时,将向该用户发送处理角度授权的权限.所以我写了一个保护措施,以保护无法访问的用户的路由. 这是我的警卫班级代码:

I have used angular2 and laravel 5.3 in my project. in laravel when user logged in server will be send the permissions of the user to handle authorization in angular. so I wrote a guard to protect routes from users that cannot access. here is my guard class code:

export class AccessGuard implements CanActivate{

permissions;
currentRoute;
constructor(private authService:AuthService,private router:Router){
    this.permissions = this.authService.getPermissions();
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
    return this.checkHavePermission(state.url);
}

canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
    return this.checkHavePermission(state.url);
}

private checkHavePermission(url){
    switch (true) {
        case url.match(/^\/panel\/users[\/.*]?/):
            return this.getPermission('user.view');
        case url.match(/^\/panel\/dashboard/):
            return true;
        case url.match(/^\/panel\/permissions/):
            return this.getPermission('permissions.manager');
        case url.match(/^\/panel\/candidates[\/.*]?/):
            return this.getPermission('candidate.view');
    }
}


getPermission(perm){
    for(var i=0;i<this.permissions.length;i++){
        if(this.permissions[i].name == perm ){
            return true;
        }
    }
    return false;
}

}

现在,路由已得到保护,我想知道如何访问组件类中的用户权限.因为有时用户可以访问一条路线,但看不到dom的特定部分.我该如何处理这种情况?

Now that the routes are secured I wondering that how can I access the user permission inside component class. Because sometimes user can access to a route but he can't see a specific part of dom. how can I handle this kind of situation?

推荐答案

您应将权限存储在服务本身中,而不是在保护中.

You should store the permissions in the service itself instead of in the guard.

因此,当使用进行身份验证时,会将权限存储在身份验证服务的属性中.然后在守护程序中,调用this.authService.<property>以使用权限.在任何其他组件中,您都可以执行相同的操作>以获得用户的权限级别

So when the use authenticates, you store the permission in a property of the Authentication Service. Then in the guard, you call the this.authService.<property> to use the permission. In any other component, you can do the same, this.authService.<property> to get the user's permission level

由于服务将作为单例传递,因此所有组件都可以访问相同的属性.

Since the service will be passed around as a singleton, all components will have access to the same property.

这篇关于Angular 2角色和权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆