I'm a newcomer to Nestjs
and I am currently working on implementing Authorization
using Casl
.
To achieve this, I have created a custom decorator
as shown below:
import { SetMetadata } from '@nestjs/common';
export const Permission = (action:string,subject: string) => SetMetadata(action, subject);
In addition, I have also developed a Permission guard
:
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { CaslAbilityFactory } from './ability.factory';
import { Action } from './action.enum';
import { User } from 'src/persistent/entity/user.entity';
@Injectable()
export class PermissionGuard implements CanActivate {
constructor(
private reflector: Reflector,
private caslAbilityFactory: CaslAbilityFactory
) { }
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const action = this.reflector.get<Action>('action', context.getHandler());
const subject = this.reflector.get<string>('subject', context.getHandler());
const request = context.switchToHttp().getRequest();
const user = request.user
console.log('**',action,subject) // undefined undefined
return this.matchPermission(user, action, subject)
}
}
Lastly, here is how I am utilizing the decorator and guard in my user controller
:
@Controller('user')
export class UserController {
constructor( private readonly userUsecase: UserUsecase) { }
@UseGuards(JwtAuthGuard,PermissionGuard)
@Permission(Action.Create,'User')
@Post()
create(@Body() createUserDto: CreateUserDto,@Request() req) {
return this.userUsecase.create(createUserDto,req.user)
}
}
While implementing these, I encountered an issue with the permission guard where I am unable to retrieve the value from the decorator.
Instead, it prints undefined.
Can anyone help me understand what the problem might be and how I can resolve it?