'NestJS context is wrong whenever I try to pass through role guard
I have created an API that successfully logs a user in, and returns a JWT access token with an ID, email and name. I then try to use this access token to perform a 'getAllUsers' request which requires admin privileges. I know that the user is logging in, because I decode the token returned from the login and it provides the correct details. However, when I console log the user from the context in the role guard, it is showing a different user in the database. I think I need to be setting the context somewhere but I'm not sure how. Please help! First time making a project in NestJS :)
User Controller
@HttpCode(200)
@UseGuards(LocalAuthGuard)
@Post('login')
@ApiOperation({summary: 'Log in with an email and password'})
login(@Body() user: any) {
return this.authService.login(user);
}
Auth Service
async login(userDetails: any) {
const email = userDetails.email;
const user = await this.userService.getUserByEmail({where: {email}});
const payload = { email: user.email, role: user.role, id: user.id };
return {
access_token: this.jwtService.sign(payload),
}
}
Role Guard
const RoleGuard = (role: Role): Type<CanActivate> => {
class RoleGuardMixin extends JwtAuthGuard {
async canActivate(context: ExecutionContext) {
await super.canActivate(context);
const request = context.switchToHttp().getRequest<RequestWithUser>();
const user = request.user;
console.log(user);
return user?.role.includes(role);
}
}
return mixin(RoleGuardMixin);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
