node.jsnestjspassport.jssession-cookiespassport-local

How do I automatically sign a user in (create session and send cookie back) after they sign up using a Nest.js backend with Passport?


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.


Solution

  • 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.