1 import crypto from "crypto"
2 import {
3 AuthenticationInput,
4 AuthenticationResponse,
5 AuthIdentityProviderService,
6 GithubAuthProviderOptions,
7 Logger,
8 } from "@medusajs/framework/types"
9 import {
10 AbstractAuthModuleProvider,
11 MedusaError,
12 } from "@medusajs/framework/utils"
13
14 type InjectedDependencies = {
15 logger: Logger
16 }
17
18 interface LocalServiceConfig extends GithubAuthProviderOptions {}
19
20 export class GithubAuthService extends AbstractAuthModuleProvider {
21 static identifier = "github"
22 static DISPLAY_NAME = "Github Authentication"
23
24 protected config_: LocalServiceConfig
25 protected logger_: Logger
26
27 static validateOptions(options: GithubAuthProviderOptions) {
28 if (!options.clientId) {
29 throw new Error("Github clientId is required")
30 }
31
32 if (!options.clientSecret) {
33 throw new Error("Github clientSecret is required")
34 }
35
36 if (!options.callbackUrl) {
37 throw new Error("Github callbackUrl is required")
38 }
39 }
40
41 constructor(
42 { logger }: InjectedDependencies,
43 options: GithubAuthProviderOptions
44 ) {
45 // @ts-ignore
46 super(...arguments)
47 this.config_ = options
48 this.logger_ = logger
49 }
50
51 async register(_): Promise<AuthenticationResponse> {
52 throw new MedusaError(
53 MedusaError.Types.NOT_ALLOWED,
54 "Github does not support registration. Use method `authenticate` instead."
55 )
56 }
57
58 async authenticate(
59 req: AuthenticationInput,
60 authIdentityService: AuthIdentityProviderService
61 ): Promise<AuthenticationResponse> {
62 const query: Record<string, string> = req.query ?? {}
63 const body: Record<string, string> = req.body ?? {}
64
65 if (query.error) {
66 return {
67 success: false,
68 error: `${query.error_description}, read more at: ${query.error_uri}`,
69 }
70 }
71
72 const stateKey = crypto.randomBytes(32).toString("hex")
73 const state = {
74 callback_url: body?.callback_url ?? this.config_.callbackUrl,
75 }
76
77 await authIdentityService.setState(stateKey, state)
78 return this.getRedirect(this.config_.clientId, state.callback_url, stateKey)
79 }
80
81 async validateCallback(
82 req: AuthenticationInput,
83 authIdentityService: AuthIdentityProviderService
84 ): Promise<AuthenticationResponse> {
85 const query: Record<string, string> = req.query ?? {}
86 const body: Record<string, string> = req.body ?? {}
87
88 if (query.error) {
89 return {
90 success: false,
91 error: `${query.error_description}, read more at: ${query.error_uri}`,
92 }
93 }
94
95 const code = query?.code ?? body?.code
96 if (!code) {
97 return { success: false, error: "No code provided" }
98 }
99
100 const state = await authIdentityService.getState(query?.state as string)
101 if (!state) {
102 return { success: false, error: "No state provided, or session expired" }
103 }
104
105 const params = `client_id=${this.config_.clientId}&client_secret=${this.config_.clientSecret}&code=${code}&redirect_uri=${state.callback_url}`
106
107 const exchangeTokenUrl = new URL(
108 `https://github.com/login/oauth/access_token?${params}`
109 )
110
111 try {
112 const response = await fetch(exchangeTokenUrl.toString(), {
113 method: "POST",
114 headers: {
115 Accept: "application/json",
116 },
117 }).then((r) => {
118 if (!r.ok) {
119 throw new MedusaError(
120 MedusaError.Types.INVALID_DATA,
121 `Could not exchange token, ${r.status}, ${r.statusText}`
122 )
123 }
124
125 return r.json()
126 })
127
128 const providerMetadata = {
129 access_token: response.access_token,
130 refresh_token: response.refresh_token,
131 // The response is in seconds
132 access_token_expires_at: new Date(
133 Date.now() + response.expires_in * 1000
134 ).toISOString(),
135 refresh_token_expires_at: new Date(
136 Date.now() + response.refresh_token_expires_in * 1000
137 ).toISOString(),
138 }
139
140 const { authIdentity, success } = await this.upsert_(
141 providerMetadata,
142 authIdentityService
143 )
144
145 return {
146 success,
147 authIdentity,
148 }
149 } catch (error) {
150 return { success: false, error: error.message }
151 }
152 }
153
154 async upsert_(
155 providerMetadata: {
156 access_token: string
157 refresh_token: string
158 access_token_expires_at: string
159 refresh_token_expires_at: string
160 },
161 authIdentityService: AuthIdentityProviderService
162 ) {
163 if (!providerMetadata?.access_token) {
164 return { success: false, error: "No access token found" }
165 }
166
167 const user = await fetch("https://api.github.com/user", {
168 headers: {
169 Accept: "application/json",
170 Authorization: `Bearer ${providerMetadata.access_token}`,
171 },
172 }).then((r) => r.json())
173
174 const entity_id = user.id.toString()
175 const userMetadata = {
176 profile_url: user.url,
177 avatar: user.avatar_url,
178 email: user.email,
179 name: user.name,
180 company: user.company,
181 two_factor_authentication: user.two_factor_authentication ?? false,
182 }
183
184 let authIdentity
185
186 try {
187 // Update throws if auth identity not found
188 authIdentity = await authIdentityService.update(entity_id, {
189 provider_metadata: providerMetadata,
190 user_metadata: userMetadata,
191 })
192 } catch (error) {
193 if (error.type === MedusaError.Types.NOT_FOUND) {
194 const createdAuthIdentity = await authIdentityService.create({
195 entity_id,
196 user_metadata: userMetadata,
197 provider_metadata: providerMetadata,
198 })
199 authIdentity = createdAuthIdentity
200 } else {
201 return { success: false, error: error.message }
202 }
203 }
204
205 return {
206 success: true,
207 authIdentity,
208 }
209 }
210
211 private getRedirect(clientId: string, callbackUrl: string, stateKey: string) {
212 const authUrl = new URL(`https://github.com/login/oauth/authorize`)
213 authUrl.searchParams.set("redirect_uri", callbackUrl)
214 authUrl.searchParams.set("client_id", clientId)
215 authUrl.searchParams.set("response_type", "code")
216 authUrl.searchParams.set("state", stateKey)
217
218 return { success: true, location: authUrl.toString() }
219 }
220 }