如何阻止路由访问特定用户



我的app.router.ts文件中有一些路由:

export const ROUTES: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'home', redirectTo: '/requisicao', pathMatch: 'full' },
{ path: 'requisicao', component: PageRequisicaoComponent, canActivate: [ AuthGuard ] },
{ path: 'pacientes', component: PagePacienteComponent, canActivate: [ AuthGuard ] },
{ path: 'resultados', component: PageResultadoComponent, canActivate: [ AuthGuard ]},
{ path: 'administrativo', component: PagePainelAdministrativoComponent, canActivate: [ AuthGuard ]},
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent}
]

我有两种类型的用户。 如何阻止类型 1 的用户访问某些路由?

@Injectable()
export class AuthGuard implements CanActivate{
constructor(
private router: Router
){}
canActivate(): boolean{
}
}

定义路由防护

有两种方法可以定义守卫。更简单的方法就是创建一个函数,如下所示:

// file app.routing.ts
const appRoutes: Routes = [
{path: "", redirectTo: "board", pathMatch: "full"},
{path: "board", component: BoardComponent, canActivate: ["boardGuard"]}
];
export const routingProviders = [
{provide: "boardGuard", useValue: boardGuard}
];
export function boardGuard(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return true;
}
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
// file app.module.ts
import {routing, routingProviders} from "./app.routing";
@NgModule({
import: [routing],
providers: [routingProviders]
})
export class AppComponent {}

你也可以在 guard 函数中使用依赖注入,如下所示:

export const tpRoutingProviders = [
{provide: "authenticatedGuard", useFactory: (authService: AuthService) => {
return () => authService.isUserAuthenticated();
},
deps: [AuthService]
}
];

第二个选项是定义一个实现"可以激活"接口的类。遵循这个:

// file app.routing.ts
const appRoutes: Routes = [
{path: "worksheet", component: WorksheetComponent, canActivate: [WorksheetAccessGuard]}     
];
// file ActivationGuards.ts
@Injectable()
export class WorksheetAccessGuard implements CanActivate {
private static USER_PARAM = "userId";
constructor(private router: Router, private userService: CurrentUserService) {}
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.userService.currentUser;
const paramUser = route.params[WorksheetAccessGuard.USER_PARAM];
if (paramUser && paramUser !== currentUser.id && !currentUser.admin) {
this.router.navigate(["worksheet"]);
return false;
}
return true;
}
}
// file app.module.ts
@NgModule({
providers: [WorksheetAccessGuard]
})
export class AppComponent {}

你基本上需要一些机制来获取用户类型。 然后,您可以根据用户类型轻松返回truefalse

@Injectable()
export class AuthGuard implements CanActivate {
canActivate(): boolean {
// 1 fetch the type of use
const type = 1;
if (type === 1) return false;
else return true;
}
}

最新更新