Skip to content

Instantly share code, notes, and snippets.

@markpenaranda
Last active December 9, 2020 01:17
Show Gist options
  • Save markpenaranda/c43f0c48b9a54a62f5cc2e631d6cd173 to your computer and use it in GitHub Desktop.
Save markpenaranda/c43f0c48b9a54a62f5cc2e631d6cd173 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
}
}
}
}
@markpenaranda
Copy link
Author

markpenaranda commented Jul 23, 2019

Sample Use Case


@Controller('users')
@UseGuards(
    AuthGuard('jwt'),
    new RestfulCrudGuard({
        readAllRoles: ['admin'],
        readOneRoles: ['admin'],
        createOneRoles: ['admin'],
        updateOneRoles: ['admin'],
        deleteOneRoles: ['admin']
    })
)

export class UsersController implements CrudController<User>{

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment