1 import {
2 AuthenticationInput,
3 AuthenticationResponse,
4 AuthIdentityDTO,
5 AuthIdentityProviderService,
6 EmailPassAuthProviderOptions,
7 Logger,
8 } from "@medusajs/framework/types"
9 import {
10 AbstractAuthModuleProvider,
11 isString,
12 MedusaError,
13 } from "@medusajs/framework/utils"
14 import Scrypt from "scrypt-kdf"
15 import { isPresent } from "@medusajs/utils"
16
17 type InjectedDependencies = {
18 logger: Logger
19 }
20
21 type AuthIdentityParams = {
22 email: string
23 password: string
24 authIdentityService: AuthIdentityProviderService
25 }
26
27 type ProviderMetadata = {
28 password?: unknown
29 }
30
31 interface LocalServiceConfig extends EmailPassAuthProviderOptions {}
32
33 export class EmailPassAuthService extends AbstractAuthModuleProvider {
34 static identifier = "emailpass"
35 static DISPLAY_NAME = "Email/Password Authentication"
36
37 protected config_: LocalServiceConfig
38 protected logger_: Logger
39
40 constructor(
41 { logger }: InjectedDependencies,
42 options: EmailPassAuthProviderOptions
43 ) {
44 // @ts-ignore
45 super(...arguments)
46 this.config_ = options
47 this.logger_ = logger
48 }
49
50 protected async hashPassword(password: string) {
51 const hashConfig = this.config_.hashConfig ?? { logN: 15, r: 8, p: 1 }
52 const passwordHash = await Scrypt.kdf(password, hashConfig)
53 return passwordHash.toString("base64")
54 }
55
56 async update(
57 data: { password: string; entity_id: string },
58 authIdentityService: AuthIdentityProviderService
59 ) {
60 const { password, entity_id } = data ?? {}
61
62 if (!entity_id) {
63 return {
64 success: false,
65 error: `Cannot update ${this.provider} provider identity without entity_id`,
66 }
67 }
68
69 if (!password || !isString(password)) {
70 return { success: true }
71 }
72
73 let authIdentity
74
75 try {
76 const passwordHash = await this.hashPassword(password)
77 const providerMetadata = await this.getProviderMetadata_(
78 entity_id,
79 authIdentityService
80 )
81
82 authIdentity = await authIdentityService.update(entity_id, {
83 provider_metadata: {
84 ...providerMetadata,
85 password: passwordHash,
86 },
87 })
88 } catch (error) {
89 return { success: false, error: error.message }
90 }
91
92 return {
93 success: true,
94 authIdentity: this.sanitizeAuthIdentity_(authIdentity),
95 }
96 }
97
98 async authenticate(
99 userData: AuthenticationInput,
100 authIdentityService: AuthIdentityProviderService
101 ): Promise<AuthenticationResponse> {
102 const { email, password } = userData.body ?? {}
103
104 if (!password || !isString(password)) {
105 return {
106 success: false,
107 error: "Password should be a string",
108 }
109 }
110
111 if (!email || !isString(email)) {
112 return {
113 success: false,
114 error: "Email should be a string",
115 }
116 }
117
118 let authIdentity: AuthIdentityDTO | undefined
119
120 try {
121 authIdentity = await authIdentityService.retrieve({
122 entity_id: email,
123 })
124 } catch (error) {
125 if (error.type === MedusaError.Types.NOT_FOUND) {
126 return {
127 success: false,
128 error: "Invalid email or password",
129 }
130 }
131
132 return { success: false, error: error.message }
133 }
134
135 if (await this.isPasswordMatch_(password, authIdentity)) {
136 return {
137 success: true,
138 authIdentity: this.sanitizeAuthIdentity_(authIdentity),
139 }
140 }
141
142 return {
143 success: false,
144 error: "Invalid email or password",
145 }
146 }
147
148 async register(
149 userData: AuthenticationInput,
150 authIdentityService: AuthIdentityProviderService
151 ): Promise<AuthenticationResponse> {
152 const { email, password } = userData.body ?? {}
153
154 if (!password || !isString(password)) {
155 return {
156 success: false,
157 error: "Password should be a string",
158 }
159 }
160
161 if (!email || !isString(email)) {
162 return {
163 success: false,
164 error: "Email should be a string",
165 }
166 }
167
168 try {
169 const identity = await authIdentityService.retrieve({
170 entity_id: email,
171 })
172
173 if (
174 !isPresent(identity.app_metadata) &&
175 (await this.isPasswordMatch_(password, identity))
176 ) {
177 return {
178 success: true,
179 authIdentity: this.sanitizeAuthIdentity_(identity),
180 }
181 }
182
183 return {
184 success: false,
185 error: "Identity with email already exists",
186 }
187 } catch (error) {
188 if (error.type === MedusaError.Types.NOT_FOUND) {
189 const createdAuthIdentity = await this.createAuthIdentity({
190 email,
191 password,
192 authIdentityService,
193 })
194
195 return {
196 success: true,
197 authIdentity: createdAuthIdentity,
198 }
199 }
200
201 return { success: false, error: error.message }
202 }
203 }
204
205 private async createAuthIdentity({
206 email,
207 password,
208 authIdentityService,
209 }: AuthIdentityParams) {
210 const authIdentity = await authIdentityService.create({
211 entity_id: email,
212 provider_metadata: {
213 password: await this.hashPassword(password),
214 },
215 })
216
217 return this.sanitizeAuthIdentity_(authIdentity)
218 }
219
220 private async isPasswordMatch_(
221 password: string,
222 authIdentity: AuthIdentityDTO
223 ): Promise<boolean> {
224 const providerIdentity = this.getProviderIdentity_(authIdentity)
225 const passwordHash = providerIdentity?.provider_metadata?.password
226
227 if (!isString(passwordHash)) {
228 return false
229 }
230
231 return await Scrypt.verify(Buffer.from(passwordHash, "base64"), password)
232 }
233
234 private async getProviderMetadata_(
235 entityId: string,
236 authIdentityService: AuthIdentityProviderService
237 ): Promise<ProviderMetadata> {
238 const authIdentity = await authIdentityService.retrieve({
239 entity_id: entityId,
240 })
241 const providerIdentity = this.getProviderIdentity_(authIdentity)
242
243 return {
244 ...(providerIdentity.provider_metadata ?? {}),
245 }
246 }
247
248 private sanitizeAuthIdentity_(
249 authIdentity: AuthIdentityDTO
250 ): AuthIdentityDTO {
251 const copy = JSON.parse(JSON.stringify(authIdentity))
252 const providerIdentity = this.getProviderIdentity_(copy)
253
254 delete providerIdentity.provider_metadata?.password
255
256 return copy
257 }
258
259 private getProviderIdentity_(authIdentity: AuthIdentityDTO) {
260 return authIdentity.provider_identities?.find(
261 (pi) => pi.provider === this.provider
262 )!
263 }
264 }