1.0.1 • Published 2 years ago

midway-typeorm-casbin v1.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

This is a midwayjs component, use to make the casbin work on midwayjs

Installation

npm install midway-typeorm-casbin

Simple Example

We need to add new Casbin configuration to the config.default.ts of Midway project

config.default.ts

  casbin: {
    model: `
    [request_definition]
    r = sub, obj, act
    
    [policy_definition]
    p = sub, obj, act
    
    [role_definition]
    g = _, _
    
    [policy_effect]
    e = some(where (p.eft == allow))
    
    [matchers]
    m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act"
    `,
  },

Then import the component to the midwayjs configuration.ts

import * as orm from '@midwayjs/orm';
import * as casbin from 'midway-typeorm-casbin';

@Configuration({
  imports: [
    orm, // needs
    casbin,
    ...
  ],
  importConfigs: [join(__dirname, './config')],
})

Now you can use casbin in your project,

casbin.middleware.ts

@Middleware()
export class CasbinMiddleware implements IMiddleware<Context, NextFunction> {
  
  @Inject('casbin')
  casbin;

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      const { path, method } = ctx;

      const hasPermission = await this.casbin.enforce(
        ctx.state?.user?.role,
        path,
        method
      );
      if (!hasPermission) {
        throw new Error('Permission denied');
      }
      await next();
    };
  }

Getting Help