代码之家  ›  专栏  ›  技术社区  ›  Kamran Khan

使用Angular 11自定义页面权限

  •  1
  • Kamran Khan  · 技术社区  · 4 年前

    我正在开发一个应用程序,其中我正在实现自定义权限。有一个基于订阅的权限,我无法在auth guard中签入,它将是静态的,并且我已经实现了权限帮助器,它检查路由,然后在该路由的用户订阅中签入,然后重定向到角色权限的任何页面。它工作得很好,但我需要一种更好的方法来用干净的代码实现它。这是我的实现

    主组件

    import { Component, OnInit } from "@angular/core";
    import { Location } from '@angular/common';   
    import { AuthService } from "src/app/services/apiServices/auth.service";
    
    @Component({
      selector: "app-home",
      templateUrl: "./home.component.html"
    })
    export class HomeComponent implements OnInit {
      constructor(private readonly location: Location, private readonly authService : AuthService ) {
      }
      ngOnInit() {
        this.authService.getPermission(this.location.path());
      }
    }
    

    身份验证服务代码

    getPermission(currentRoute: string) {
        this.userPermissions = this.loggedInUserSubscriptionDetails$.subscribe(sub => {
          if (sub) {
            if (sub.MenuPermissioList.map(x => x.url).indexOf(currentRoute) === -1) {
              this.router.navigate(["/finance-analysis/not-authorized"]);
              return;
            }else{
              console.log('exists');
            }
          }
        });
    
      }
    

    这段代码基本上是获取当前位置路径,然后在订阅中检查该路径 男超人主义者 如果存在,则允许打开该页面,否则会重定向到未经授权的页面。

    我不想使用这个代码 数据:{roles:[ApplicationRolesEnum.CompanyAdmin]} 因为我必须从数据中添加或删除角色,以允许该用户访问特定页面,而且基本上是静态绑定。在这里,我添加了这张支票,它工作正常,但我的权限可能因用户而异。这使得它很难维护。

         {
            path: "home",
            canActivate: [AuthGuard, SubscriptionGuard],data : {roles: [ApplicationRolesEnum.CompanyAdmin, ApplicationRolesEnum.ExternalUser]},
            loadChildren: () => import("src/app/pages/dashboard/dashboard.module").then(m => m.DashboardModule)
          },
    
    0 回复  |  直到 4 年前
        1
  •  2
  •   Lukasz Gawrys    4 年前

    你可以尝试以下方法。我现在没有测试它,我已经把它写下来了,但它基于我在一个项目中使用的方法。

    基本上,您仍然会为此使用一个防护,但会动态地从您的服务加载权限,并基于这些权限,让用户激活页面或重定向到未经授权的页面。可以为您激活对可观察对象的订阅,这样您就不必手动管理任何订阅。

    import { AuthService } from "src/app/services/apiServices/auth.service";
    
    
    @Injectable()
    export class SubscriptionGuard implements CanActivate {
    
      constructor(
        private readonly router: Router,
        private readonly authService: AuthService,
      ) { }
    
      canActivate(activatedRoute: ActivatedRouteSnapshot, routerState: RouterStateSnapshot): Observable<boolean> {
        return this.authService.loggedInUserSubscriptionDetails$.pipe(
          take(1),
          map((sub) => {
            if (!sub) {
              return false;
            }
            return sub.MenuPermissioList.map(x => x.url).includes(routerState.url);
          }),
          tap(hasPermission => hasPermission ? undefined : this.router.navigate(['/finance-analysis/not-authorized']))
        );
      }
    }
    

    编辑:更改了在评论中讨论后提取当前url的方式。