how to correctly install tokens for authorization via Google in nestjs

34 Views Asked by At

I'm trying to create a nestjs application using the passport-google-oauth20 library and also with @nestjs/jwt I created a strategy for Google

import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { PassportStrategy } from '@nestjs/passport'
import { Profile, Strategy, VerifyCallback } from 'passport-google-oauth20'

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy) {
    constructor(private configService: ConfigService) {
        super({
            clientID: configService.get('CLIENT_ID'),
            clientSecret: configService.get('CLIENT_SECRET'),
            callbackURL: configService.get('CALLBACK_URL'),
            scope: ['profile', 'email'],
        })
    }

    async validate(
        accessToken: string,
        refreshToken: string,
        profile: Profile,
        done: VerifyCallback
    ) {
        const user = {
            email: profile.emails[0].value,
            name: profile.displayName,
            avatar: profile.photos[0].value
        }
        done(null, user)
    }
}

this is my controller

import { Controller, Get, Req, Res, UseGuards } from '@nestjs/common'
import { AuthGuard } from '@nestjs/passport'
import { Request, Response } from 'express'
import { AuthService } from './auth.service'
import { IUser } from './types/auth.types'

@Controller('auth')
export class AuthController {
    constructor(private readonly authService: AuthService) {}

    @Get('google')
    @UseGuards(AuthGuard('google'))
    googleAuth() {}

    @Get('google/redirect')
    @UseGuards(AuthGuard('google'))
    async googleAuthRedirect(@Req() request: Request, @Res() response: Response) {
        const {
            tokens: { accessToken, refreshToken },
            user
        } = await this.authService.googleAuthLogin(request.user as IUser)
    }
}

here you see the endpoint /google/redirect, on the client the user clicks the 'Log in with Google' button and it redirects to /google, inside the googleAuthLogin method I create or give a user from the database, I also generate two tokens accessToken and refreshToken. my goal: to give the accessToken to the client so that he can save it in his browser, and I want to save the refreshToken through server cookies and then redirect it to the profile page on the NextJS client

0

There are 0 best solutions below