From aea4ad0fd36a26282480980365d89cf5ae3f49d8 Mon Sep 17 00:00:00 2001 From: Quentin TREHEUX Date: Mon, 29 May 2023 11:21:53 +0200 Subject: [PATCH] [UPD] add function to login with google on mobile --- back/src/auth/auth.service.ts | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/back/src/auth/auth.service.ts b/back/src/auth/auth.service.ts index 1568cd8..307f3a6 100644 --- a/back/src/auth/auth.service.ts +++ b/back/src/auth/auth.service.ts @@ -1,14 +1,21 @@ import { BadRequestException, Injectable } from '@nestjs/common'; import { UsersService } from '../users/users.service'; import { JwtService } from '@nestjs/jwt'; +import { ConfigService } from '@nestjs/config'; +import { OAuth2Client } from 'google-auth-library'; import * as bcrypt from 'bcryptjs'; import PayloadInterface from './interface/payload.interface'; @Injectable() export class AuthService { + private readonly client : OAuth2Client; + constructor( private userService: UsersService, + private readonly configService: ConfigService, private jwtService: JwtService, - ) {} + ) { + this.client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID); + } async validateUser( username: string, @@ -31,4 +38,25 @@ export class AuthService { access_token, }; } + + async loginWithGoogleMobile(idToken: string) { + const ticket = await this.client.verifyIdToken({ + idToken, + audience: this.configService.get("GOOGLE_CLIENT_ID"), + }); + const payload = ticket.getPayload(); + if (payload) { + const user = await this.userService.findOrCreate({ + email: payload.email, + firstName: payload.given_name, + lastName: payload.family_name, + picture: payload.picture, + googleId: payload.sub, + }); + const jwt = await this.login(user); + return { user, jwt }; + } else { + throw new BadRequestException(); + } + } }