I have created a guard
@Injectable() export class EmailConfirmationGuard implements CanActivate { canActivate(context: ExecutionContext) { const request: RequestWithUser = context.switchToHttp().getRequest(); console.log(request.user); if (!request.user?.hasEmailConfirmed) { throw new UnauthorizedException("Confirm your email first before updating your profile"); } return true; } }
And i am using it on of my endpoints
@UseGuards(JwtAuthGuard) @UseGuards(EmailConfirmationGuard) @Post("/update-profile") @UseInterceptors(FileInterceptor("file")) async updateProfile(@UploadedFile() file: Express.Multer.File, @Body("full-name") fullname: string,@Request() req) {
The point is it is faling because getRequest is not returning the authenticated user it is returning undefined
const request: RequestWithUser = context.switchToHttp().getRequest();
How can i return the authenticated user from the response ?
Advertisement
Answer
You should use your JwtAuthGuard at your controller level since nest doesn’t have an order to run the decorators.
@UseGuards(JwtAuthGuard) export class YourController{ @UseGuards(EmailConfirmationGuard) @Post() public async yourFunction() {} }