Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save loicgeek/0a92eb87a0ba57d7f1424c2324b88949 to your computer and use it in GitHub Desktop.
Save loicgeek/0a92eb87a0ba57d7f1424c2324b88949 to your computer and use it in GitHub Desktop.
NestJSX CRUD - restful role guard
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'
import { getAction } from '@nestjsx/crud'
@Injectable()
export class RestfulCrudRoleGuard implements CanActivate {
constructor(
// private readonly reflector: Reflector,
public restfulCrudOptions: {
readAllRoles: string [],
readOneRoles: string [],
createOneRoles: string [],
updateOneRoles: string [],
deleteOneRoles: string []
}
) {}
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest()
const handler = context.getHandler()
const controller = context.getClass()
// const feature = getFeature(controller)
const action = getAction(handler)
const user = request.user
switch(action) {
case 'Read-All' : {
// Do user role checking here.
}
case 'Read-One' : {
// Do user role checking here.
}
case 'Create-One' : {
// Do user role checking here.
}
case 'Update-One' : {
// Do user role checking here.
}
case 'Delete-One' : {
// Do user role checking here.
}
default : {
return true
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment