在我的登录路线之前,使用护照登录可以很好地使用 @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;
}
}
我应该采取不同的方式来解决这个问题吗?我在网上找不到任何解决方案。
对于任何发现此问题并且可能处于相同情况的人,我最终使用中间件在数据库中创建用户。由于中间件在 Guards 之前运行,因此它工作得很好。