我正在開發一個應用程式,我正在其中實施自定義權限。有基于訂閱的權限,我無法簽入靜態的 auth 防護,我已經實作了權限的幫助程式,該權限檢查路由,然后在用戶訂閱中簽入該路由,然后重定向到角色上的任何頁面允許。它作業正常,但我需要一種更好的方法來使用干凈的代碼來實作它。這是我的實作
主頁組件
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');
}
}
});
}
這段代碼基本上是獲取當前位置路徑,然后在訂閱MenuPermissioList 中檢查該路徑是否存在,然后它允許打開頁面,否則它會重定向到未經授權的頁面。
我不想使用此代碼資料:{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)
},
uj5u.com熱心網友回復:
您可以嘗試以下方法。我現在沒有測驗它并且已經把它寫在了我的頭上,但它基于我在一個專案中使用的一種方法。
基本上,您仍然會為此使用 Guard,但會從您的服務動態加載權限,并基于它們讓用戶激活頁面或重定向到未授權頁面。CanActivate 為您訂閱 Observable,因此您無需手動管理任何訂閱。
import { AuthService } from "src/app/services/apiServices/auth.service";
function getPathFromRoot(route: ActivatedRouteSnapshot) {
return route.pathFromRoot
.map(p => p.url.map(segment => segment.toString()).join('/'))
.join('/');
}
@Injectable()
export class SubscriptionGuard implements CanActivate {
constructor(
private readonly router: Router,
private readonly authService: AuthService,
) { }
canActivate(activatedRoute: ActivatedRouteSnapshot): Observable<boolean> {
return this.authService.loggedInUserSubscriptionDetails$.pipe(
take(1),
map((sub) => {
if (!sub) {
return false;
}
return sub.MenuPermissioList.map(x => x.url).includes(getPathFromRoot(activatedRoute));
}),
tap(hasPermission => hasPermission ? undefined : this.router.navigate(['/finance-analysis/not-authorized']))
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/398528.html
