diff --git a/libs/common/src/auth/services/auth.service.ts b/libs/common/src/auth/services/auth.service.ts index af9d047..5808ce7 100644 --- a/libs/common/src/auth/services/auth.service.ts +++ b/libs/common/src/auth/services/auth.service.ts @@ -1,4 +1,4 @@ -import { BadRequestException, Injectable } from '@nestjs/common'; +import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import * as argon2 from 'argon2'; import { HelperHashService } from '../../helper/services'; @@ -6,6 +6,7 @@ import { UserRepository } from '../../../../common/src/modules/user/repositories import { UserSessionRepository } from '../../../../common/src/modules/session/repositories/session.repository'; import { UserSessionEntity } from '../../../../common/src/modules/session/entities'; import { ConfigService } from '@nestjs/config'; +import axios from 'axios'; @Injectable() export class AuthService { @@ -80,8 +81,18 @@ export class AuthService { type: user.type, sessionId: user.sessionId, roles: user?.roles, + googleCode: user.googleCode, }; + if (payload.googleCode) { + const profile = await this.getProfile(payload.googleCode); + user = await this.userRepository.findOne({ + where: { email: profile.data.email }, + }); + if (!user) { + throw new UnauthorizedException('wrong credentials'); + } + } const tokens = await this.getTokens(payload); await this.updateRefreshToken(user.uuid, tokens.refreshToken); return tokens; @@ -100,4 +111,22 @@ export class AuthService { hashData(data: string) { return argon2.hash(data); } + + async getProfile(googleCode: string) { + try { + const response = await axios.post('https://oauth2.googleapis.com/token', { + client_id: process.env.GOOGLE_CLIENT_ID, + client_secret: process.env.GOOGLE_CLIENT_SECRET, + code: googleCode, + grant_type: 'authorization_code', + redirect_uri: 'http://localhost:3000/auth/google/callback', + }); + return axios.get( + `https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=${response.data.access_token}`, + ); + } catch (error) { + console.error('Failed to get profile:', error); + throw new UnauthorizedException('google login failed'); + } + } } diff --git a/src/auth/dtos/user-login.dto.ts b/src/auth/dtos/user-login.dto.ts index 1f3662b..dedb08f 100644 --- a/src/auth/dtos/user-login.dto.ts +++ b/src/auth/dtos/user-login.dto.ts @@ -16,4 +16,8 @@ export class UserLoginDto { @IsString() @IsOptional() regionUuid?: string; + + @IsOptional() + @IsString() + googleCode?: string; } diff --git a/src/auth/services/user-auth.service.ts b/src/auth/services/user-auth.service.ts index 7b539e2..88e989e 100644 --- a/src/auth/services/user-auth.service.ts +++ b/src/auth/services/user-auth.service.ts @@ -122,6 +122,7 @@ export class UserAuthService { return { uuid: role.uuid, type: role.roleType.type }; }), sessionId: session[1].uuid, + googleCode: data.googleCode, }); } catch (error) { throw new BadRequestException('Invalid credentials');