DEV Community

Discussion on: How to Implement Login with Google in Nest JS

Collapse
 
villekaa profile image
Goffy • Edited

Hi, I think this example is for jwt.
If you want to use a cookie session you can add a route guard that creates a session cookie for you.

Controller

    @Post('/signin')
    @UseGuards(LoginGuard)
    signin(@Request() req: IUserRequest): void {
        console.log(`@AuthController ${JSON.stringify(req.user)}`)
    }
Enter fullscreen mode Exit fullscreen mode

Guard

import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class LoginGuard extends AuthGuard('local') {
    async canActivate(context: ExecutionContext): Promise<boolean> {
        const result = (await super.canActivate(context)) as boolean;
        const request = context.switchToHttp().getRequest();
        await super.logIn(request);
        return result;
    }
}
Enter fullscreen mode Exit fullscreen mode

At this point you have a cookie and you can redirect the user back to front end ( if you have one ) and do another request to ask user information.