守卫不返回经过身份验证的用户

Guard not returning authenticated user

我创建了一个守卫

@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;
    }
}

我正在我的端点上使用它

    @UseGuards(JwtAuthGuard)
    @UseGuards(EmailConfirmationGuard)
    @Post("/update-profile")
    @UseInterceptors(FileInterceptor("file"))
    async updateProfile(@UploadedFile() file: Express.Multer.File, @Body("full-name") fullname: string,@Request() req) {

关键是它失败了,因为 getRequest 不是 return 认证用户,它是 return 未定义的

const request: RequestWithUser = context.switchToHttp().getRequest();

如何从响应中 return 验证用户?

您应该在控制器级别使用 JwtAuthGuard,因为 nest 没有命令 运行 装饰器。

@UseGuards(JwtAuthGuard)
export class YourController{

@UseGuards(EmailConfirmationGuard)
@Post()
public async yourFunction() {}
    
}