nest-authz
基于 node-casbin 实现的 RBAC 权限控制模块。
如何使用
@Module({
imports: [
AuthZModule.register({
model: 'model.conf',
policy: 'policy.csv'
})
],
controllers: [AppController],
providers: [AppService]
})
export class AppModule {}
其中 policy
也可以为 adapter, 如:
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
AuthZModule.register({
model: 'model.conf',
policy: TypeORMAdapter.newAdapter({
name: 'casbin',
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'nestdb'
})
}),
],
controllers: [AppController],
providers: [AppService]
})
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import {
AuthZGuard,
AuthZService,
AuthAction,
AuthPossession,
UsePermissions
} from 'nest-authz';
@Controller()
export class AppController {
constructor(
private readonly authzSrv: AuthZService,
private readonly appService: AppService
) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
@Get('users')
@UseGuards(AuthZGuard)
@UsePermissions({
action: AuthAction.READ,
resource: 'USER',
possession: AuthPossession.ANY
})
async findAllUsers() {
}
@Get(':id/roles')
@UseGuards(AuthZGuard)
@UsePermissions({
action: AuthAction.READ,
resource: 'USER_ROLES',
possession: AuthPossession.OWN_ANY,
isOwn: (req: any): boolean => {
return Number(req.user.id) === Number(req.params.id);
}
})
async findUserRoles(@Param('id') id: string): Promise<string[]> {
return this.authzSrv.getRolesForUser(username);
}
}
一般来说,认证后的用户数据保存于请求对象的 user
属性中。
AuthGuard 使用从请求对象 user
属性中获取到的 username
属性判别用户权限。