mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-11-26 08:04:53 +00:00
added google login
This commit is contained in:
@ -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');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -16,4 +16,8 @@ export class UserLoginDto {
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
regionUuid?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
googleCode?: string;
|
||||
}
|
||||
|
||||
@ -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');
|
||||
|
||||
Reference in New Issue
Block a user