1 import {
2 AuthTypes,
3 Context,
4 IAuthVerificationProvider,
5 ModulesSdkTypes,
6 } from "@medusajs/framework/types"
7 import { MedusaError } from "@medusajs/framework/utils"
8 import { AuthVerification } from "@models"
9 import { TokenVerificationProviderOptions } from "@types"
10 import {
11 generateVerificationToken,
12 getVerificationTokenTtlMs,
13 hashVerificationToken,
14 } from "../../utils/verification-token"
15
16 type InjectedDependencies = {
17 authVerificationService: ModulesSdkTypes.IMedusaInternalService<
18 typeof AuthVerification
19 >
20 }
21
22 export class TokenVerificationProvider implements IAuthVerificationProvider {
23 static identifier = "token"
24
25 readonly identifier = TokenVerificationProvider.identifier
26
27 protected authVerificationService_: ModulesSdkTypes.IMedusaInternalService<
28 typeof AuthVerification
29 >
30 protected options_: TokenVerificationProviderOptions
31
32 constructor(
33 { authVerificationService }: InjectedDependencies,
34 options: TokenVerificationProviderOptions = {}
35 ) {
36 this.authVerificationService_ = authVerificationService
37 this.options_ = options
38 }
39
40 async request(
41 data: AuthTypes.RequestAuthVerificationDTO,
42 sharedContext: Context = {}
43 ): Promise<AuthTypes.RequestAuthVerificationResponse> {
44 const existingVerifications = await this.authVerificationService_.list(
45 {
46 auth_identity_id: data.auth_identity_id,
47 entity_id: data.entity_id,
48 entity_type: data.entity_type,
49 },
50 { take: 1, skip: 0 },
51 sharedContext
52 )
53
54 if (existingVerifications.length && existingVerifications[0].verified_at) {
55 return existingVerifications[0]
56 }
57
58 const token = generateVerificationToken()
59 const tokenHash = hashVerificationToken(token)
60 const requestedAt = new Date(Date.now())
61 const expiresAt = new Date(requestedAt.getTime() + this.getTokenTtlMs_())
62
63 let verification
64 if (existingVerifications.length) {
65 verification = await this.authVerificationService_.update(
66 {
67 id: existingVerifications[0].id,
68 code_provider: data.code_provider,
69 provider_metadata: { token_hash: tokenHash },
70 requested_at: requestedAt,
71 verified_at: null,
72 },
73 sharedContext
74 )
75 } else {
76 verification = await this.authVerificationService_.create(
77 {
78 auth_identity_id: data.auth_identity_id,
79 entity_id: data.entity_id,
80 entity_type: data.entity_type,
81 code_provider: data.code_provider,
82 provider_metadata: { token_hash: tokenHash },
83 requested_at: requestedAt,
84 metadata: data.metadata ?? null,
85 },
86 sharedContext
87 )
88 }
89
90 return {
91 ...verification,
92 code: token,
93 expires_at: expiresAt,
94 }
95 }
96
97 async confirm(
98 data: AuthTypes.ConfirmAuthVerificationDTO,
99 sharedContext: Context = {}
100 ): Promise<AuthTypes.ConfirmAuthVerificationResponse> {
101 if (!data.code) {
102 throw new MedusaError(
103 MedusaError.Types.INVALID_DATA,
104 "Verification code is required"
105 )
106 }
107
108 const [verification] = await this.authVerificationService_.list(
109 {
110 provider_metadata: {
111 token_hash: hashVerificationToken(data.code),
112 },
113 },
114 {},
115 sharedContext
116 )
117
118 if (!verification || verification.verified_at) {
119 throw new MedusaError(
120 MedusaError.Types.NOT_ALLOWED,
121 "Verification code is invalid or already used"
122 )
123 }
124
125 if (
126 data.code_provider &&
127 data.code_provider !== verification.code_provider
128 ) {
129 throw new MedusaError(
130 MedusaError.Types.NOT_ALLOWED,
131 `Verification code does not belong to provider "${data.code_provider}"`
132 )
133 }
134
135 const expiresAt =
136 new Date(verification.requested_at).getTime() + this.getTokenTtlMs_()
137
138 if (expiresAt <= Date.now()) {
139 throw new MedusaError(
140 MedusaError.Types.NOT_ALLOWED,
141 "Verification code has expired"
142 )
143 }
144
145 return await this.authVerificationService_.update(
146 {
147 id: verification.id,
148 verified_at: new Date(Date.now()),
149 },
150 sharedContext
151 )
152 }
153
154 protected getTokenTtlMs_(): number {
155 return getVerificationTokenTtlMs(this.options_.ttl_seconds ?? 900)
156 }
157 }