Logging in with passport is working just fine with @UseGuard(LocalAuthGuard) before my login route like so:
@UseGuards(LocalAuthGuard)
@Post('login')
async loginUser(@Request() req) {
return req.user;
}
But I can't use that same approach on signup because the logic underneath the UseGuard that actually creates the user hasn't run yet, so the authentication will always fail.
Should I use a middleware to create the new user before the LocalAuthGuard runs?
I'm currently using the req.login function which successfully generates a session (I can see it in my Redis DB) but I don't know how to send that session back as a cookie using passport:
@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;
}
}
Is there a different way I should be approaching this? I couldn't find any solution online.
For anyone who finds this and might be in the same situation, I ended up using middleware to create the user in the database. Since middleware runs before Guards, it worked perfectly.