|
1
|
import crypto from "crypto" |
|
2
|
import { |
|
3
|
AuthenticationInput, |
|
4
|
AuthenticationResponse, |
|
5
|
AuthIdentityProviderService, |
|
6
|
GoogleAuthProviderOptions, |
|
7
|
Logger, |
|
8
|
} from "@medusajs/framework/types" |
|
9
|
import { |
|
10
|
AbstractAuthModuleProvider, |
|
11
|
MedusaError, |
|
12
|
} from "@medusajs/framework/utils" |
|
13
|
import jwt, { type JwtHeader, type JwtPayload } from "jsonwebtoken" |
|
14
|
import jwksClient, { JwksClient } from "jwks-rsa" |
|
15
|
import { promisify } from "util" |
|
16
|
|
|
17
|
const verifyJwt = promisify< |
|
18
|
string, |
|
19
|
jwt.Secret | jwt.GetPublicKeyOrSecret, |
|
20
|
jwt.VerifyOptions, |
|
21
|
JwtPayload | string | undefined |
|
22
|
>(jwt.verify) |
|
23
|
|
|
24
|
type InjectedDependencies = { |
|
25
|
logger: Logger |
|
26
|
} |
|
27
|
|
|
28
|
const GOOGLE_JWKS_URI = "https://www.googleapis.com/oauth2/v3/certs" |
|
29
|
const GOOGLE_ISSUERS = ["https://accounts.google.com", "accounts.google.com"] |
|
30
|
|
|
31
|
interface LocalServiceConfig extends GoogleAuthProviderOptions {} |
|
32
|
export class GoogleAuthService extends AbstractAuthModuleProvider { |
|
33
|
static identifier = "google" |
|
34
|
static DISPLAY_NAME = "Google Authentication" |
|
35
|
|
|
36
|
protected config_: LocalServiceConfig |
|
37
|
protected logger_: Logger |
|
38
|
protected jwks_: JwksClient |
|
39
|
|
|
40
|
static validateOptions(options: GoogleAuthProviderOptions) { |
|
41
|
if (!options.clientId) { |
|
42
|
throw new Error("Google clientId is required") |
|
43
|
} |
|
44
|
|
|
45
|
if (!options.clientSecret) { |
|
46
|
throw new Error("Google clientSecret is required") |
|
47
|
} |
|
48
|
|
|
49
|
if (!options.callbackUrl) { |
|
50
|
throw new Error("Google callbackUrl is required") |
|
51
|
} |
|
52
|
} |
|
53
|
|
|
54
|
constructor( |
|
55
|
{ logger }: InjectedDependencies, |
|
56
|
options: GoogleAuthProviderOptions |
|
57
|
) { |
|
58
|
// @ts-ignore |
|
59
|
super(...arguments) |
|
60
|
this.config_ = options |
|
61
|
this.logger_ = logger |
|
62
|
this.jwks_ = jwksClient({ |
|
63
|
jwksUri: GOOGLE_JWKS_URI, |
|
64
|
cache: true, |
|
65
|
rateLimit: true, |
|
66
|
}) |
|
67
|
} |
|
68
|
|
|
69
|
protected getSigningKey_ = ( |
|
70
|
header: JwtHeader, |
|
71
|
callback: (err: Error | null, key?: string) => void |
|
72
|
) => { |
|
73
|
if (!header.kid) { |
|
74
|
callback(new Error("ID token is missing 'kid' header")) |
|
75
|
return |
|
76
|
} |
|
77
|
this.jwks_.getSigningKey(header.kid, (err, key) => { |
|
78
|
if (err || !key) { |
|
79
|
callback(err ?? new Error("Unable to resolve signing key")) |
|
80
|
return |
|
81
|
} |
|
82
|
callback(null, key.getPublicKey()) |
|
83
|
}) |
|
84
|
} |
|
85
|
|
|
86
|
async register(_): Promise<AuthenticationResponse> { |
|
87
|
throw new MedusaError( |
|
88
|
MedusaError.Types.NOT_ALLOWED, |
|
89
|
"Google does not support registration. Use method `authenticate` instead." |
|
90
|
) |
|
91
|
} |
|
92
|
|
|
93
|
async authenticate( |
|
94
|
req: AuthenticationInput, |
|
95
|
authIdentityService: AuthIdentityProviderService |
|
96
|
): Promise<AuthenticationResponse> { |
|
97
|
const query: Record<string, string> = req.query ?? {} |
|
98
|
const body: Record<string, string> = req.body ?? {} |
|
99
|
|
|
100
|
if (query.error) { |
|
101
|
return { |
|
102
|
success: false, |
|
103
|
error: `${query.error_description}, read more at: ${query.error_uri}`, |
|
104
|
} |
|
105
|
} |
|
106
|
|
|
107
|
const stateKey = crypto.randomBytes(32).toString("hex") |
|
108
|
const state = { |
|
109
|
callback_url: body?.callback_url ?? this.config_.callbackUrl, |
|
110
|
} |
|
111
|
|
|
112
|
await authIdentityService.setState(stateKey, state) |
|
113
|
return this.getRedirect(this.config_.clientId, state.callback_url, stateKey) |
|
114
|
} |
|
115
|
|
|
116
|
async validateCallback( |
|
117
|
req: AuthenticationInput, |
|
118
|
authIdentityService: AuthIdentityProviderService |
|
119
|
): Promise<AuthenticationResponse> { |
|
120
|
const query: Record<string, string> = req.query ?? {} |
|
121
|
const body: Record<string, string> = req.body ?? {} |
|
122
|
|
|
123
|
if (query.error) { |
|
124
|
return { |
|
125
|
success: false, |
|
126
|
error: `${query.error_description}, read more at: ${query.error_uri}`, |
|
127
|
} |
|
128
|
} |
|
129
|
|
|
130
|
const code = query?.code ?? body?.code |
|
131
|
if (!code) { |
|
132
|
return { success: false, error: "No code provided" } |
|
133
|
} |
|
134
|
|
|
135
|
const state = await authIdentityService.getState(query?.state as string) |
|
136
|
if (!state) { |
|
137
|
return { success: false, error: "No state provided, or session expired" } |
|
138
|
} |
|
139
|
|
|
140
|
const params = `client_id=${this.config_.clientId}&client_secret=${this.config_.clientSecret}&code=${code}&redirect_uri=${state.callback_url}&grant_type=authorization_code` |
|
141
|
const exchangeTokenUrl = new URL( |
|
142
|
`https://oauth2.googleapis.com/token?${params}` |
|
143
|
) |
|
144
|
|
|
145
|
try { |
|
146
|
const response = await fetch(exchangeTokenUrl.toString(), { |
|
147
|
method: "POST", |
|
148
|
}).then((r) => { |
|
149
|
if (!r.ok) { |
|
150
|
throw new MedusaError( |
|
151
|
MedusaError.Types.INVALID_DATA, |
|
152
|
`Could not exchange token, ${r.status}, ${r.statusText}` |
|
153
|
) |
|
154
|
} |
|
155
|
|
|
156
|
return r.json() |
|
157
|
}) |
|
158
|
|
|
159
|
const { authIdentity, success } = await this.verify_( |
|
160
|
response.id_token as string, |
|
161
|
authIdentityService |
|
162
|
) |
|
163
|
|
|
164
|
return { |
|
165
|
success, |
|
166
|
authIdentity, |
|
167
|
} |
|
168
|
} catch (error) { |
|
169
|
return { success: false, error: error.message } |
|
170
|
} |
|
171
|
} |
|
172
|
|
|
173
|
async verify_( |
|
174
|
idToken: string | undefined, |
|
175
|
authIdentityService: AuthIdentityProviderService |
|
176
|
) { |
|
177
|
if (!idToken) { |
|
178
|
return { success: false, error: "No ID found" } |
|
179
|
} |
|
180
|
|
|
181
|
let payload: JwtPayload |
|
182
|
try { |
|
183
|
const decoded = await verifyJwt(idToken, this.getSigningKey_, { |
|
184
|
algorithms: ["RS256"], |
|
185
|
audience: this.config_.clientId, |
|
186
|
issuer: GOOGLE_ISSUERS, |
|
187
|
}) |
|
188
|
if (!decoded || typeof decoded === "string") { |
|
189
|
throw new Error("Invalid id_token") |
|
190
|
} |
|
191
|
payload = decoded |
|
192
|
} catch (err) { |
|
193
|
throw new MedusaError( |
|
194
|
MedusaError.Types.UNAUTHORIZED, |
|
195
|
`Could not verify Google id_token: ${err.message}` |
|
196
|
) |
|
197
|
} |
|
198
|
|
|
199
|
if (!payload.email_verified) { |
|
200
|
throw new MedusaError( |
|
201
|
MedusaError.Types.INVALID_DATA, |
|
202
|
"Email not verified, cannot proceed with authentication" |
|
203
|
) |
|
204
|
} |
|
205
|
|
|
206
|
if (!payload.sub) { |
|
207
|
throw new MedusaError( |
|
208
|
MedusaError.Types.INVALID_DATA, |
|
209
|
"id_token is missing 'sub' claim" |
|
210
|
) |
|
211
|
} |
|
212
|
|
|
213
|
const entity_id = payload.sub |
|
214
|
const userMetadata = { |
|
215
|
name: payload.name, |
|
216
|
email: payload.email, |
|
217
|
picture: payload.picture, |
|
218
|
given_name: payload.given_name, |
|
219
|
family_name: payload.family_name, |
|
220
|
} |
|
221
|
|
|
222
|
let authIdentity |
|
223
|
|
|
224
|
try { |
|
225
|
authIdentity = await authIdentityService.retrieve({ |
|
226
|
entity_id, |
|
227
|
}) |
|
228
|
} catch (error) { |
|
229
|
if (error.type === MedusaError.Types.NOT_FOUND) { |
|
230
|
const createdAuthIdentity = await authIdentityService.create({ |
|
231
|
entity_id, |
|
232
|
user_metadata: userMetadata, |
|
233
|
}) |
|
234
|
authIdentity = createdAuthIdentity |
|
235
|
} else { |
|
236
|
return { success: false, error: error.message } |
|
237
|
} |
|
238
|
} |
|
239
|
|
|
240
|
return { |
|
241
|
success: true, |
|
242
|
authIdentity, |
|
243
|
} |
|
244
|
} |
|
245
|
|
|
246
|
private getRedirect(clientId: string, callbackUrl: string, stateKey: string) { |
|
247
|
const authUrl = new URL(`https://accounts.google.com/o/oauth2/v2/auth`) |
|
248
|
authUrl.searchParams.set("redirect_uri", callbackUrl) |
|
249
|
authUrl.searchParams.set("client_id", clientId) |
|
250
|
authUrl.searchParams.set("response_type", "code") |
|
251
|
authUrl.searchParams.set("scope", "email profile openid") |
|
252
|
authUrl.searchParams.set("state", stateKey) |
|
253
|
|
|
254
|
return { success: true, location: authUrl.toString() } |
|
255
|
} |
|
256
|
} |