使用 Passport 的 Nest.js 后端注册后,如何自动登录用户(创建会话并发回 cookie)?

问题描述 投票:0回答:1

在我的登录路线之前,使用护照登录可以很好地使用 @UseGuard(LocalAuthGuard) ,如下所示:

@UseGuards(LocalAuthGuard)
@Post('login')
async loginUser(@Request() req) {
  return req.user;
}

但是我不能在注册时使用相同的方法,因为实际创建用户的 UseGuard 下的逻辑尚未运行,因此身份验证始终会失败。

我应该在 LocalAuthGuard 运行之前使用中间件创建新用户吗?

我目前正在使用 req.login 函数,该函数成功生成了一个会话(我可以在我的 Redis DB 中看到它),但我不知道如何使用护照将该会话作为 cookie 发送回来:

@Post('signup')
  async signupUser(
    @Body('email') email: string,
    @Body('password') password: string,
    @Request() req,
  ) {
    const result = await this.authService.registerUser(email, password);
    if (result instanceof HttpException) {
      // There was an error
      throw result;
    } else {
      // successful
      const user = { email: result.email, password: result.password };
      await req.login(user, (err: Error) => {
        if (err) console.log(err);
        return new HttpException(
          'Internal Server Error.',
          HttpStatus.INTERNAL_SERVER_ERROR,
        );
      });

      return req.user;
    }
  }

我应该采取不同的方式来解决这个问题吗?我在网上找不到任何解决方案。

node.js nestjs passport.js session-cookies passport-local
1个回答
0
投票

对于任何发现此问题并且可能处于相同情况的人,我最终使用中间件在数据库中创建用户。由于中间件在 Guards 之前运行,因此它工作得很好。

© www.soinside.com 2019 - 2024. All rights reserved.