Nest-CASL 使用教程
nest-casl Casl integration for NestJS 项目地址: https://gitcode.com/gh_mirrors/ne/nest-casl
1. 项目介绍
Nest-CASL 是一个为 NestJS 应用提供基于角色的访问控制(RBAC)解决方案的开源项目。它整合了 CASL(Climate Access Control List)库,允许开发者在应用中定义灵活的权限控制规则,从而管理用户对不同资源的访问权限。
2. 项目快速启动
安装
首先,确保你已经安装了 Node.js。然后,通过以下命令安装 Nest-CASL:
npm install nest-casl
# 或者
yarn add nest-casl
创建角色和权限
在应用中定义角色和权限。例如:
// app.roles.ts
export enum Roles {
admin = 'admin',
operator = 'operator',
customer = 'customer',
}
// post.permissions.ts
import { Permissions, Actions } from 'nest-casl';
import { Roles } from './app.roles';
import { Post } from './dtos/post.dto';
export const permissions: Permissions<Roles, Post, Actions> = {
everyone: ({ can }) => {
can(Actions.read, Post);
can(Actions.create, Post);
},
customer: ({ user, can }) => {
can(Actions.update, Post, { userId: user.id });
},
operator: ({ can, cannot, extend }) => {
extend(Roles.customer);
can(Actions.manage, PostCategory);
can(Actions.manage, Post);
cannot(Actions.delete, Post);
},
};
配置应用
在你的模块文件中配置 CaslModule:
// app.module.ts
import { Module } from '@nestjs/common';
import { CaslModule } from 'nest-casl';
import { Roles } from './app.roles';
import { permissions } from './post.permissions';
@Module({
imports: [
CaslModule.forRoot<Roles>({
superuserRole: Roles.admin,
getUserFromRequest: (request) => request.user,
}),
CaslModule.forFeature({ permissions }),
],
})
export class AppModule {}
使用权限装饰器
在你的控制器中,使用 UseGuards
和 UseAbility
装饰器来限制对方法的访问:
// post.resolver.ts
import { UseGuards } from '@nestjs/common';
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { AccessGuard, UseAbility, Actions } from 'nest-casl';
import { CreatePostInput } from './dtos/create-post-input.dto';
import { UpdatePostInput } from './dtos/update-post-input.dto';
import { PostService } from './post.service';
import { Post } from './dtos/post.dto';
@Resolver(() => Post)
export class PostResolver {
constructor(private postService: PostService) {}
@Query(() => [Post])
posts() {
return this.postService.findAll();
}
@Query(() => Post)
@UseGuards(AccessGuard)
async post(@Args('id') id: string) {
return this.postService.findById(id);
}
@Mutation(() => Post)
@UseGuards(AccessGuard, AccessGuard)
@UseAbility(Actions.create, Post)
async createPost(@Args('input') input: CreatePostInput) {
return this.postService.create(input);
}
@Mutation(() => Post)
@UseGuards(AccessGuard, AccessGuard)
@UseAbility(Actions.update, Post)
async updatePost(@Args('input') input: UpdatePostInput) {
return this.postService.update(input);
}
}
3. 应用案例和最佳实践
在开发具有复杂权限需求的应用时,最佳实践是:
- 明确定义角色和权限,保持它们的粒度适中,既不过于宽泛也不过于细致。
- 使用
UseAbility
装饰器来注解控制器方法,确保只有具有相应权限的用户可以访问。 - 利用 Nest-CASL 提供的钩子(Hooks)功能来处理复杂的权限逻辑。
4. 典型生态项目
Nest-CASL 作为 NestJS 生态的一部分,通常与以下项目一起使用:
- NestJS:用于构建高效、可扩展的服务端应用程序的框架。
- CASL:用于在应用中实现灵活的权限控制。
- GraphQL:用于构建客户端和服务器之间类型安全的 API。
nest-casl Casl integration for NestJS 项目地址: https://gitcode.com/gh_mirrors/ne/nest-casl
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考