3.1.0 • Published 10 months ago

@salman3001/nest-policy-module v3.1.0

Weekly downloads
-
License
ISC
Repository
github
Last release
10 months ago

Permission policies module for Nest Js

This module can be used to manage the user permissions. we can define simple policies and register them in any nest module and inject policyService. (some inspirations from adonis js bouncer package)

Instructions

  • Install module
 npm i @salman3001/nest-policy-module
  • import policy modules in any other module and register a policy.
import { PolicyModule } from '@salman3001/nest-policy-module';
import { myPolicy } from './policies'


imports: [
  PolicyModule.register([
    { token: 'MyPolicy', policy: myPolicy },
    { token: 'SomeOtherPolicy', policy: someOtherPolicy }
  ])
  ],
  • you can create a policy as below. (keep related policies in the related modules)
  • policy object must contain only functions those returns boolean value only
const myPolicy = {
  isAdmin: (user: any) => user.role === 'admin',
  view: (user: any, resource: any) => {
    return resource.userId === user.id;
  },
};

export type IMypolicy = typeof myPolicy; // <-- export the type from here as it will be used while injecting service
  • inject service in any class in the same module
import { PolicyService } from '@salman3001/nest-policy-module';
import { myPolicy } from './policies';

export class UserService {
  constructor(
    @Inject('MyPolicy')
    private readonly policyService: PolicyService<IMypolicy>, // provide generic for typehints,
  ) {}

  anyMethod() {
    await this.policyService.authorize('isAdmin', { role: 'admin' });

    // or
    await this.policyService.authorize('view', anyResource);
  }
}
  • authorize method returns true if policy passes the provided logic otherwise throws NestPolicyError which extends HttpExceptions with unauthorized status code. You can catch this error in global exception filer like this
import { NestPolicyError } from '@salman3001/nest-policy-module';

@Catch()
export class GlobalHttpExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();

    if (exception instanceof NestPolicyError) {
      const status = exception.getStatus();
      const message = exception.message;
      //.. return custom error
    }
  }
}
  • type hints will be provided by typescript

  • instruction are written in hurry. you may expect mistakes. please try to findout yourself

3.1.0

10 months ago

3.0.0

10 months ago

2.0.1

1 year ago

2.0.0

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago