forked from nestjs/typescript-starter
-
Notifications
You must be signed in to change notification settings - Fork 246
/
googleAuthentication.service.ts
97 lines (77 loc) · 2.52 KB
/
googleAuthentication.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { ConfigService } from '@nestjs/config';
import { google, Auth } from 'googleapis';
import { AuthenticationService } from '../authentication/authentication.service';
import User from '../users/user.entity';
@Injectable()
export class GoogleAuthenticationService {
oauthClient: Auth.OAuth2Client;
constructor(
private readonly usersService: UsersService,
private readonly configService: ConfigService,
private readonly authenticationService: AuthenticationService
) {
const clientID = this.configService.get('GOOGLE_AUTH_CLIENT_ID');
const clientSecret = this.configService.get('GOOGLE_AUTH_CLIENT_SECRET');
this.oauthClient = new google.auth.OAuth2(
clientID,
clientSecret
);
}
async getUserData(token: string) {
const userInfoClient = google.oauth2('v2').userinfo;
this.oauthClient.setCredentials({
access_token: token
})
const userInfoResponse = await userInfoClient.get({
auth: this.oauthClient
});
return userInfoResponse.data;
}
async getCookiesForUser(user: User) {
const accessTokenCookie = this.authenticationService.getCookieWithJwtAccessToken(user.id);
const {
cookie: refreshTokenCookie,
token: refreshToken
} = this.authenticationService.getCookieWithJwtRefreshToken(user.id);
await this.usersService.setCurrentRefreshToken(refreshToken, user.id);
return {
accessTokenCookie,
refreshTokenCookie
}
}
async handleRegisteredUser(user: User) {
if (!user.isRegisteredWithGoogle) {
throw new UnauthorizedException();
}
const {
accessTokenCookie,
refreshTokenCookie
} = await this.getCookiesForUser(user);
return {
accessTokenCookie,
refreshTokenCookie,
user
}
}
async registerUser(token: string, email: string) {
const userData = await this.getUserData(token);
const name = userData.name;
const user = await this.usersService.createWithGoogle(email, name);
return this.handleRegisteredUser(user);
}
async authenticate(token: string) {
const tokenInfo = await this.oauthClient.getTokenInfo(token);
const email = tokenInfo.email;
try {
const user = await this.usersService.getByEmail(email);
return this.handleRegisteredUser(user);
} catch (error) {
if (error.status !== 404) {
throw new error;
}
return this.registerUser(token, email);
}
}
}