google login done

This commit is contained in:
unknown
2024-10-01 16:52:42 +03:00
parent 20156568e2
commit c0c41cf91d
6 changed files with 227 additions and 212 deletions

View File

@ -1,4 +1,8 @@
import { BadRequestException, Injectable, UnauthorizedException } 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';
@ -7,16 +11,20 @@ import { UserSessionRepository } from '../../../../common/src/modules/session/re
import { UserSessionEntity } from '../../../../common/src/modules/session/entities';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';
import { OAuth2Client } from 'google-auth-library';
@Injectable()
export class AuthService {
private client: OAuth2Client;
constructor(
private jwtService: JwtService,
private readonly userRepository: UserRepository,
private readonly sessionRepository: UserSessionRepository,
private readonly helperHashService: HelperHashService,
private readonly configService: ConfigService,
) {}
) {
this.client = new OAuth2Client(this.configService.get('GOOGLE_CLIENT_ID'));
}
async validateUser(
email: string,
@ -83,14 +91,13 @@ export class AuthService {
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 },
where: { email: profile.email },
});
if (!user) {
throw new UnauthorizedException('wrong credentials');
return { profile };
}
}
const tokens = await this.getTokens(payload);
@ -114,19 +121,16 @@ export class AuthService {
async getProfile(googleCode: string) {
try {
const response = await axios.post('https://oauth2.googleapis.com/token', {
client_id: this.configService('GOOGLE_CLIENT_ID'),
client_secret: this.configService('GOOGLE_CLIENT_SECRET'),
code: googleCode,
grant_type: 'authorization_code',
redirect_uri: 'http://localhost:3000/auth/google/callback',
const ticket = await this.client.verifyIdToken({
idToken: googleCode,
audience: this.configService.get('GOOGLE_CLIENT_ID'),
});
return axios.get(
`https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=${response.data.access_token}`,
);
const payload = ticket.getPayload();
return {
...payload,
};
} catch (error) {
console.error('Failed to get profile:', error);
throw new UnauthorizedException('google login failed');
throw new UnauthorizedException('Google login failed');
}
}
}