nest-casbin
v1.0.8
Published
NestJS's Casbin one-click integration solutions.
Downloads
567
Maintainers
Readme
Nest Casbin
Nest Casbin is an integration solution for Nest modularity.
Installation
npm install nest-casbin
# or
yarn add nest-casbin
# or
pnpm add nest-casbin
Usage
import { Module } from '@nestjs/common';
import { CasbinModule } from 'nest-casbin';
@Module({
imports: [
CasbinModule.forRootAsync({
useFactory: async (config: ConfigService) => ({
confPath: config.get('CASBIN_CONF_PATH'),
adapter: new TypeormAdapter({
type: 'mysql',
host: config.get('DB_HOST'),
port: config.get('DB_PORT'),
username: config.get('DB_USERNAME'),
password: config.get('DB_PASSWORD'),
database: config.get('DB_DATABASE'),
}),
watcher: new RedisWatcher({
host: config.get('REDIS_HOST'),
port: config.get('REDIS_PORT'),
password: config.get('REDIS_PASSWORD'),
db: config.get('REDIS_DB'),
}),
autoSave: config.get('CASBIN_AUTO_SAVE'),
}),
imports: [ConfigModule],
}),
],
})
export class AppModule {}
import { Injectable } from '@nestjs/common';
import { CasbinWrapper } from 'nest-casbin';
@Injectable()
export class CasbinService {
constructor(private readonly casbin: CasbinWrapper) {
}
}
Decorators
If you need to use Nest Guard to authenticate permissions, see the following steps:
// 1. You'll need to inherit from these classes to implement custom guards:PermsGuard、RolesGuard、AttributeGuard
// 2. Override these methods: [convertRole() | convertPerm() | convertAttribute()] 、userID()、validate()
import { CasbinWrapper, RolesGuard, TUserID } from 'nest-casbin';
import { Reflector } from '@nestjs/core';
import { ExecutionContext, Injectable } from '@nestjs/common';
@Injectable()
export class UserRoleGuard extends RolesGuard {
constructor(reflector: Reflector, casbin: CasbinWrapper) {
super(reflector, casbin);
}
async convertRole(
roles: Array<string | number>,
): Promise<Array<string | number>> {
// ...
// TODO: Convert the ID of the associated table to the corresponding value (name) and return.
// ...
return roles;
}
userID(context: ExecutionContext): TUserID {
const request = context.switchToHttp().getRequest();
// ...
// TODO: Read information about a user from a context, or read a user other info and query user information.
// TODO: This is provided that you have written user information into the context at or before the token validation.
// ...
return request.user.id;
}
async validate(context: ExecutionContext): Promise<TUserID> {
const request = context.switchToHttp().getRequest();
const token = request.headers.authorization;
if (!token) {
throw new UnauthorizedException('No token provided');
}
// ...
// TODO: Verify that the token is valid, and if you don't need to use it, then you don't need to implement it.
// ...
return uid;
}
}
Use the decorator in the controller:
@Get('remove-user')
@UseGuards(UserRoleGuard) // The check guards in UseGuards must be of the same type as the decorator with the required permissions.
@HasRole(['admin', 'manager']) // admin && manager.
@Validate() // The token needs to be verified, and if it is not needed, please do not use this decorator.
async removeUser(@Request() req: Request): Promise<void> {
// ...
}
RBAC and ABAC are supported, and the validation rules for attributes are determined by the Casbin configuration file.
// @...
@HasPerm(['add-user']) // user && remove.
async addUser(@Request() req: Request):Promise < void > {
// ...
}
// The validation rules for attributes are determined by the Casbin configuration file.
// @...
@HasAttribute([
{
resource: 'oss',
action: 'read',
}
]) // user && remove.
async readOSS(@Request() req: Request): Promise<void> {
// ...
}