[UPD] add function to login with google on mobile

This commit is contained in:
Quentin TREHEUX
2023-05-29 11:21:53 +02:00
parent af9a099bf1
commit aea4ad0fd3
+29 -1
View File
@@ -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();
}
}
}