added exception filter and removed controller error handling

This commit is contained in:
unknown
2024-10-06 11:04:25 +03:00
26 changed files with 780 additions and 1345 deletions

View File

@ -1,4 +1,8 @@
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';
@ -10,13 +14,16 @@ 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,
@ -81,8 +88,17 @@ 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.email },
});
if (!user) {
return { profile };
}
}
const tokens = await this.getTokens(payload);
await this.updateRefreshToken(user.uuid, tokens.refreshToken);
return tokens;
@ -101,4 +117,19 @@ export class AuthService {
hashData(data: string) {
return argon2.hash(data);
}
async getProfile(googleCode: string) {
try {
const ticket = await this.client.verifyIdToken({
idToken: googleCode,
audience: this.configService.get('GOOGLE_CLIENT_ID'),
});
const payload = ticket.getPayload();
return {
...payload,
};
} catch (error) {
throw new UnauthorizedException('Google login failed');
}
}
}