1 import {
2 AuthTypes,
3 Context,
4 IAuthVerificationProvider,
5 Logger,
6 } from "@medusajs/framework/types"
7 import { AuthVerificationProviderRegistrationPrefix } from "@types"
8
9 type InjectedDependencies = {
10 logger?: Logger
11 [
12 key: `${typeof AuthVerificationProviderRegistrationPrefix}${string}`
13 ]: IAuthVerificationProvider
14 }
15
16 export default class AuthVerificationProviderService {
17 protected dependencies: InjectedDependencies
18 #logger: Logger
19
20 constructor(container: InjectedDependencies) {
21 this.dependencies = container
22 this.#logger = container["logger"]
23 ? container.logger
24 : (console as unknown as Logger)
25 }
26
27 protected retrieveProviderRegistration(
28 provider: string
29 ): IAuthVerificationProvider {
30 try {
31 return this.dependencies[
32 `${AuthVerificationProviderRegistrationPrefix}${provider}`
33 ] as IAuthVerificationProvider
34 } catch (err) {
35 if (err.name === "AwilixResolutionError") {
36 const errMessage = `
37 Unable to retrieve the verification provider with id: ${provider}
38 Please make sure that the provider is registered in the container and it is configured correctly in your project configuration file.`
39
40 this.#logger.error(`AwilixResolutionError: ${err.message}`, err)
41
42 throw new Error(errMessage)
43 }
44
45 const errMessage = `Unable to retrieve the verification provider with id: ${provider}, the following error occurred: ${err.message}`
46 this.#logger.error(errMessage)
47
48 throw new Error(errMessage)
49 }
50 }
51
52 async request(
53 provider: string,
54 data: AuthTypes.RequestAuthVerificationDTO,
55 sharedContext?: Context
56 ): Promise<AuthTypes.RequestAuthVerificationResponse> {
57 return await this.retrieveProviderRegistration(provider).request(
58 data,
59 sharedContext
60 )
61 }
62
63 async confirm(
64 provider: string,
65 data: AuthTypes.ConfirmAuthVerificationDTO,
66 sharedContext?: Context
67 ): Promise<AuthTypes.ConfirmAuthVerificationResponse> {
68 return await this.retrieveProviderRegistration(provider).confirm(
69 data,
70 sharedContext
71 )
72 }
73 }