nestjs扩展了JWT保护



我扩展了JWT保护,目的是检查用户是否存在于用户表中,下面是我的代码:

import {
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { error } from 'console';
import { UsersService } from 'src/users/users.service';
import { Role } from './role.enum';
@Injectable()
export class JwtUserGuard extends AuthGuard('jwt') {
constructor(private readonly userService: UsersService) {
super();
}
canActivate(context: ExecutionContext) {
return super.canActivate(context);
}
handleRequest(err, user, info) {
this.userService.findByEmail(user.email).then((user) => {
if (user === undefined) {
throw new UnauthorizedException();
}
return user;
}).catch(error=>{
throw new UnauthorizedException();
});
if (user.role !== Role.User) {
throw new UnauthorizedException();
}
return user;
}
}

但是我总是得到一个错误

(node:4504) UnhandledPromiseRejectionWarning: Error: Unauthorized
at /media/ridwan/storage/workspace/backend/javascript/nestjs/queueing/dist/auth/jwt-user.guard.js:28:23
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:4504) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:4504) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我的问题是如何处理UnhandledPromiseRejectionWarning我的代码仍然运行,即使用户不存在?提前感谢……

您通过使用承诺(与链接的thencatch)并且首先不返回承诺来混合同步和异步编程方法。我相信Nest的handleRequest方法不允许异步方法。因此,正在发生的事情是,您正在启动一个异步进程(对this.userService.findByEmail的承诺调用),并且它抛出一个错误,但是您正在(同步地)返回user属性(或抛出一个正确处理的不同错误)。然后,当承诺解析(拒绝)时,您有一个未处理的throw,意味着UnhandledPromiseRejection

我不明白为什么你不能在一个策略文件中做所有这些逻辑,因为handleRequest发生在validate被调用之后。

使用PassportStrategymixin并将findByEmail逻辑移动到位置。他们在这里解释如何做到这一点:https://docs.nestjs.com/security/authentication#implement-protected-route-and-jwt-strategy-guards

最新更新