1 import {
2 AuthenticationInput,
3 AuthenticationResponse,
4 AuthIdentityProviderService,
5 AuthTypes,
6 Logger,
7 } from "@medusajs/framework/types"
8 import { AbstractAuthModuleProvider } from "@medusajs/framework/utils"
9 import {
10 AuthIdentifiersRegistrationName,
11 AuthProviderRegistrationPrefix,
12 } from "@types"
13
14 type InjectedDependencies = {
15 [
16 key: `${typeof AuthProviderRegistrationPrefix}${string}`
17 ]: AuthTypes.IAuthProvider
18 logger?: Logger
19 /**
20 * The list of registered auth provider instance IDs
21 */
22 auth_providers_identifier?: (string | undefined)[]
23 }
24
25 export default class AuthProviderService {
26 protected dependencies: InjectedDependencies
27 #logger: Logger
28
29 constructor(container: InjectedDependencies) {
30 this.dependencies = container
31 this.#logger = container["logger"]
32 ? container.logger
33 : (console as unknown as Logger)
34 }
35
36 protected retrieveProviderRegistration(
37 providerId: string
38 ): AuthTypes.IAuthProvider {
39 try {
40 return this.dependencies[`${AuthProviderRegistrationPrefix}${providerId}`]
41 } catch (err) {
42 if (err.name === "AwilixResolutionError") {
43 const errMessage = `
44 Unable to retrieve the auth provider with id: ${providerId}
45 Please make sure that the provider is registered in the container and it is configured correctly in your project configuration file.`
46
47 // Log full error for debugging
48 this.#logger.error(`AwilixResolutionError: ${err.message}`, err)
49
50 throw new Error(errMessage)
51 }
52
53 const errMessage = `Unable to retrieve the auth provider with id: ${providerId}, the following error occurred: ${err.message}`
54 this.#logger.error(errMessage)
55
56 throw new Error(errMessage)
57 }
58 }
59
60 /**
61 * Lists the public information of every registered auth provider instance.
62 * The IDs are read from the container registry populated by the providers
63 * loader, and the display metadata is read from each resolved provider
64 * instance. Provider options and secrets are never exposed.
65 *
66 * A provider instance that fails to resolve from the container is skipped
67 * (with a warning) so that a single broken registration does not prevent
68 * the healthy providers from being listed.
69 */
70 listProviders(filters?: {
71 id: string | string[]
72 }): AuthTypes.AuthProviderInfoDTO[] {
73 let identifiers = (
74 this.dependencies[AuthIdentifiersRegistrationName] ?? []
75 ).filter((id): id is string => Boolean(id))
76
77 if (filters?.id) {
78 const normalizedId = Array.isArray(filters.id) ? filters.id : [filters.id]
79 identifiers = identifiers.filter((id) => normalizedId.includes(id))
80 }
81
82 return identifiers
83 .map((id): AuthTypes.AuthProviderInfoDTO | null => {
84 let provider:
85 | (AuthTypes.IAuthProvider & {
86 identifier?: string
87 displayName?: string
88 })
89 | undefined
90
91 try {
92 provider = this.retrieveProviderRegistration(id)
93 } catch (error) {
94 this.#logger.warn(
95 `Skipping auth provider "${id}" when listing providers, as it could not be resolved: ${error.message}`
96 )
97
98 return null
99 }
100
101 return {
102 id,
103 identifier: provider?.identifier ?? id,
104 display_name: provider?.displayName ?? id,
105 flow: this.deriveFlow(provider),
106 }
107 })
108 .filter(
109 (provider): provider is AuthTypes.AuthProviderInfoDTO =>
110 provider !== null
111 )
112 }
113
114 /**
115 * Derives the authentication flow of a provider instance. A provider is
116 * `redirect`-based if it implements `validateCallback`, which exists
117 * solely for the redirect/callback flow.
118 */
119 protected deriveFlow(
120 provider?: AuthTypes.IAuthProvider
121 ): "credentials" | "redirect" {
122 const validateCallback = provider?.validateCallback
123
124 const isRedirect =
125 typeof validateCallback === "function" &&
126 validateCallback !== AbstractAuthModuleProvider.prototype.validateCallback
127
128 return isRedirect ? "redirect" : "credentials"
129 }
130
131 async authenticate(
132 provider: string,
133 auth: AuthenticationInput,
134 authIdentityProviderService: AuthIdentityProviderService
135 ): Promise<AuthenticationResponse> {
136 const providerHandler = this.retrieveProviderRegistration(provider)
137 return await providerHandler.authenticate(auth, authIdentityProviderService)
138 }
139
140 async register(
141 provider: string,
142 auth: AuthenticationInput,
143 authIdentityProviderService: AuthIdentityProviderService
144 ): Promise<AuthenticationResponse> {
145 const providerHandler = this.retrieveProviderRegistration(provider)
146 return await providerHandler.register(auth, authIdentityProviderService)
147 }
148
149 async update(
150 provider: string,
151 data: Record<string, unknown>,
152 authIdentityProviderService: AuthIdentityProviderService
153 ): Promise<AuthenticationResponse> {
154 const providerHandler = this.retrieveProviderRegistration(provider)
155 return await providerHandler.update(data, authIdentityProviderService)
156 }
157
158 async validateCallback(
159 provider: string,
160 auth: AuthenticationInput,
161 authIdentityProviderService: AuthIdentityProviderService
162 ): Promise<AuthenticationResponse> {
163 const providerHandler = this.retrieveProviderRegistration(provider)
164 return await providerHandler.validateCallback(
165 auth,
166 authIdentityProviderService
167 )
168 }
169 }