如何防止用户在Angular中按角色进行操作 [英] How to prevent actions by user role in Angular

查看:86
本文介绍了如何防止用户在Angular中按角色进行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有一个AuthService可以对登录用户进行身份验证,而AuthGuard可以阻止未登录的用户访问.

I already have an AuthService to authenticate user on login and AuthGuard to prevent access if not logged in.

某些页面我限制了UserProfile/Role的访问,但是现在我需要阻止页面上的操作.

Some pages I restrict access by UserProfile/Role but now I need to prevent actions on page.

我从大到小都有管理员,经理,支持和代理"之类的角色.

I have roles like "Admin, Manager, Support and Agent", from greater to lower.

如何仅将级别设置为经理"或更高",以编辑所有人都可以访问的页面上的内容(支持和代理只能查看)?

How to set level only to Manager or Above to edit content on a page that all can access (Support and Agent restrict to view only)?

这是我当前的canActivate方法:

This is my current canActivate method:

canActivate(route: ActivatedRouteSnapshot) {

  const currentUser = JSON.parse(localStorage.getItem('currentUser'));
  if (currentUser) {
    // check if route is restricted by role
    if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
      // role not authorised so redirect to home page
      this.router.navigate(['/']);
      return false;
    }
    // authorised so return true
    return true;
  }
  // not logged in so redirect to login page
  this.router.navigate(['auth/login']);
  return false;
}

这是我的模块routing.module.ts

And this is my module routing.module.ts

const routes: Routes = [{
  path: '',
  component: ReportsComponent,
  canActivateChild: [AuthGuard],
  children: [
    {
      path: 'blocked-users',
      component: BlockedUsersComponent,
      data: { roles: [Role.admin, Role.manager, Role.suporte, Role.agent] },
      children: [
        { ... 

需要修复以下两个主题:

Need to fix these two topics:

1)第data: { roles: [] }行,我只想通过较低的级别(例如Agent);

1) Line data: { roles: [] } I want to pass only the lower level (like Agent);

2)内部组件告知只有Manager可以编辑数据(如果Role == Support或Agent,则只能编辑disable一个按钮)

2) Inside component tell that only Manager can edit data (or just disable a button if Role == Support or Agent)

推荐答案

将您的授权代码分解为一项服务,您的警卫和其他服务都可以使用(DRY!).从那里开始,检查整个站点角色的逻辑是相同的.

Break out your authorisation code into a service that both your guard and other services can make use of (DRY!). From there, the logic is the same for checking roles around the entire site.

@Injectable()
export class RoleAuthorisationService {
  public isAuthorised(roles: Role[]): boolean {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    if (!currentUser) return false;
    return roles.indexOf(currentUser.role) >= 0)
  }
}

警卫将使用它,但是您可以通过对该授权服务进行自己的检查来阻止使用页面的任何部分.

The guard will be making use of it, but then you can just prevent usage of any part of your pages by making your own check against that authorisation service.

您的警卫(非常近似,因为现在是23:32,我想上床睡觉):

Your guard (very approximated because it's 23:32 and I want to go to bed):

export class YourGuard {

  constructor(private readonly auth: RoleAuthorisationService) {}

  canActivate(route: ActivatedRouteSnapshot) {
    if (route.data.roles && !this.auth.isAuthorised(route.data.roles)) {
      // role not authorised so redirect to home page
      this.router.navigate(['/']);
      return false;
    } else {
      // authorised so return true
      return true;
    }

    // not logged in so redirect to login page
    this.router.navigate(['auth/login']);
    return false;
  }
}

是否要在屏幕上隐藏编辑"按钮?

Want to hide an 'Edit' button on the screen?

模板:

<h1>Some details<h1>
<button *ngIf="canEdit" (click)="enableEditing()>Edit</button>
<p>Details etc etc...</P>

Ts:

export class SomeComponent {
  private readonly editors: Role[] = [Role.Agent, Role.Administrator];

  constructor(private readonly auth: RoleAuthorisationService) {}

  public get canEdit(): boolean { return this.auth.isAuthorised(this.editors); }
}

要为锁定事物的更具体问题添加答案,除非用户是经理或更高级别",您可以(如上)非常具体地说明可以访问该功能的确切角色,或者可以使用枚举.只要按顺序指定了枚举,就可以进行基本的> = <检查.

To add an answer for your more specific question of locking things unless a user is 'a manager or higher', you can either (as above) be very specific about the exact roles that can access the functionality, or you can use enums. So long as your enums are specified in order, you can do basic > = < checks.

export enum Role {
  Admin = 1,
  Manager = 2,
  Support = 3,
  Peon = 4
}

...

return CurrentUser.Role <= Role.Manager;

这篇关于如何防止用户在Angular中按角色进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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