-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgoogle.adapter.ts
61 lines (54 loc) · 1.79 KB
/
google.adapter.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
import axios from 'axios'
import {injectable} from 'inversify'
import * as queryString from 'query-string'
import {Config} from '@libs/config'
interface UserInfo {
id: string
email: string
verified_email: boolean
name: string
given_name: string
picture: string
locale: string
}
enum GoogleApi {
EmailScope = 'https://www.googleapis.com/auth/userinfo.email',
ProfileScope = 'https://www.googleapis.com/auth/userinfo.profile',
SignIn = 'https://accounts.google.com/o/oauth2/v2/auth',
Token = 'https://oauth2.googleapis.com/token',
UserInfo = 'https://www.googleapis.com/oauth2/v2/userinfo',
}
@injectable()
export class GoogleAdapter {
private readonly googleClientId = this.config.get('GOOGLE_SIGN_IN_CLIENT_ID')
private readonly googleClientSecret = this.config.get('GOOGLE_SIGN_IN_CLIENT_SECRET')
private readonly googleRedirectUrl = this.config.get('CLIENT_URL')
constructor(private config: Config) {}
get signInUrl() {
const params = queryString.stringify({
client_id: this.googleClientId,
redirect_uri: this.googleRedirectUrl,
scope: [GoogleApi.EmailScope, GoogleApi.ProfileScope].join(' '),
response_type: 'code',
access_type: 'offline',
prompt: 'consent',
})
return `${GoogleApi.SignIn}?${params}`
}
async getAccessToken(code: string) {
const tokenResponse = await axios.post(GoogleApi.Token, {
client_id: this.googleClientId,
client_secret: this.googleClientSecret,
redirect_uri: this.googleRedirectUrl,
grant_type: 'authorization_code',
code,
})
return tokenResponse.data.access_token as string
}
async getUserInfo(accessToken: string) {
const {data} = await axios.get<UserInfo>(GoogleApi.UserInfo, {
headers: {Authorization: `Bearer ${accessToken}`},
})
return data
}
}