1 import { generateResetPasswordTokenWorkflow } from "@medusajs/core-flows"
2 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
3 import { ContainerRegistrationKeys } from "@medusajs/utils"
4 import jwt from "jsonwebtoken"
5 import path from "path"
6 import {
7 adminHeaders,
8 createAdminUser,
9 } from "../../../../helpers/create-admin-user"
10
11 jest.setTimeout(100000)
12
13 medusaIntegrationTestRunner({
14 medusaConfigFile: path.join(__dirname, "../../../__fixtures__/auth"),
15 testSuite: ({ dbConnection, getContainer, api, dbUtils }) => {
16 let container
17 beforeAll(async () => {
18 container = getContainer()
19 await createAdminUser(dbConnection, adminHeaders, container)
20
21 await dbUtils.snapshot()
22 })
23
24 describe("Full authentication lifecycle", () => {
25 it("Invite + registration + authentication flow", async () => {
26 // Create invite
27 const { token: inviteToken } = (
28 await api.post(
29 "/admin/invites",
30 { email: "newadmin@medusa.js" },
31 adminHeaders
32 )
33 ).data.invite
34
35 // Register identity
36 const signup = await api.post("/auth/user/emailpass/register", {
37 email: "newadmin@medusa.js",
38 password: "secret_password",
39 })
40
41 expect(signup.status).toEqual(200)
42 expect(signup.data).toEqual({ token: expect.any(String) })
43
44 // Accept invite
45 const response = await api.post(
46 `/admin/invites/accept?token=${inviteToken}`,
47 {
48 email: "newadmin@medusa.js",
49 first_name: "John",
50 last_name: "Doe",
51 },
52 {
53 headers: {
54 authorization: `Bearer ${signup.data.token}`,
55 },
56 }
57 )
58
59 expect(response.status).toEqual(200)
60 expect(response.data).toEqual({
61 user: expect.objectContaining({
62 email: "newadmin@medusa.js",
63 first_name: "John",
64 last_name: "Doe",
65 }),
66 })
67
68 // Sign in
69 const login = await api.post("/auth/user/emailpass", {
70 email: "newadmin@medusa.js",
71 password: "secret_password",
72 })
73 expect(login.status).toEqual(200)
74 expect(login.data).toEqual({ token: expect.any(String) })
75
76 // Convert token to session
77 const createSession = await api.post(
78 "/auth/session",
79 {},
80 { headers: { authorization: `Bearer ${login.data.token}` } }
81 )
82 expect(createSession.status).toEqual(200)
83
84 // Extract cookie
85 const [cookie] = createSession.headers["set-cookie"][0].split(";")
86 expect(cookie).toEqual(expect.stringContaining("connect.sid"))
87
88 const cookieHeader = {
89 headers: { Cookie: cookie },
90 }
91
92 // Perform cookie authenticated request
93 const authedRequest = await api.get(
94 "/admin/products?limit=1",
95 cookieHeader
96 )
97 expect(authedRequest.status).toEqual(200)
98
99 // Sign out
100 const signOutRequest = await api.delete("/auth/session", cookieHeader)
101 expect(signOutRequest.status).toEqual(200)
102
103 // Attempt to perform authenticated request
104 const unAuthedRequest = await api
105 .get("/admin/products?limit=1", cookieHeader)
106 .catch((e) => e)
107
108 expect(unAuthedRequest.response.status).toEqual(401)
109 })
110
111 it("should respond with 401 on register, if email already exists", async () => {
112 const signup = await api
113 .post("/auth/user/emailpass/register", {
114 email: "admin@medusa.js",
115 password: "secret_password",
116 })
117 .catch((e) => e)
118
119 expect(signup.response.status).toEqual(401)
120 expect(signup.response.data.message).toEqual(
121 "Identity with email already exists"
122 )
123 })
124
125 it("should respond with 401 on sign in, if email does not exist", async () => {
126 const signup = await api
127 .post("/auth/user/emailpass", {
128 email: "john@doe.com",
129 password: "secret_password",
130 })
131 .catch((e) => e)
132
133 expect(signup.response.status).toEqual(401)
134 expect(signup.response.data.message).toEqual(
135 "Invalid email or password"
136 )
137 })
138 })
139
140 describe("Reset password flows", () => {
141 it("should generate a reset password token", async () => {
142 const response = await api.post("/auth/user/emailpass/reset-password", {
143 identifier: "admin@medusa.js",
144 })
145
146 expect(response.status).toEqual(201)
147 })
148
149 it("should fail if identifier is not provided", async () => {
150 const errResponse = await api
151 .post("/auth/user/emailpass/reset-password", {})
152 .catch((e) => e)
153
154 expect(errResponse.response.data.message).toEqual(
155 "Invalid request: Field 'identifier' is required"
156 )
157 expect(errResponse.response.status).toEqual(400)
158 })
159
160 it("should fail to generate token for non-existing user, but still respond with 201", async () => {
161 const response = await api.post("/auth/user/emailpass/reset-password", {
162 identifier: "non-existing-user@medusa.js",
163 })
164
165 expect(response.status).toEqual(201)
166 })
167
168 it("should reject a provider that is not allowed for the user actor type", async () => {
169 const response = await api
170 .post("/auth/user/non-existing-provider/reset-password", {
171 identifier: "admin@medusa.js",
172 })
173 .catch((e) => e.response)
174
175 expect(response.status).toEqual(400)
176 expect(response.data.message).toEqual(
177 "The actor type user is not allowed to use the auth provider non-existing-provider"
178 )
179 })
180
181 it("should successfully reset password", async () => {
182 // Register user
183 await api.post("/auth/user/emailpass/register", {
184 email: "test@medusa-commerce.com",
185 password: "secret_password",
186 })
187
188 // The token won't be part of the Rest API response, so we need to generate it manually
189 const { http } = container.resolve(
190 ContainerRegistrationKeys.CONFIG_MODULE
191 ).projectConfig
192 const { result } = await generateResetPasswordTokenWorkflow(
193 container
194 ).run({
195 input: {
196 entityId: "test@medusa-commerce.com",
197 actorType: "user",
198 provider: "emailpass",
199 secret: http.jwtSecret!,
200 jwtOptions: http.jwtOptions,
201 },
202 })
203
204 const response = await api.post(
205 `/auth/user/emailpass/update`,
206 {
207 password: "new_password",
208 },
209 {
210 headers: {
211 authorization: `Bearer ${result}`,
212 },
213 }
214 )
215
216 expect(response.status).toEqual(200)
217 expect(response.data).toEqual({ success: true })
218
219 const failedLogin = await api
220 .post("/auth/user/emailpass", {
221 email: "test@medusa-commerce.com",
222 password: "secret_password",
223 })
224 .catch((e) => e)
225
226 expect(failedLogin.response.status).toEqual(401)
227 expect(failedLogin.response.data.message).toEqual(
228 "Invalid email or password"
229 )
230
231 const login = await api.post("/auth/user/emailpass", {
232 email: "test@medusa-commerce.com",
233 password: "new_password",
234 })
235
236 expect(login.status).toEqual(200)
237 expect(login.data).toEqual({ token: expect.any(String) })
238 })
239
240 it("should ensure you can only update password", async () => {
241 // Register user
242 await api.post("/auth/user/emailpass/register", {
243 email: "test@medusa-commerce.com",
244 password: "secret_password",
245 })
246
247 // The token won't be part of the Rest API response, so we need to generate it manually
248 const { http } = container.resolve(
249 ContainerRegistrationKeys.CONFIG_MODULE
250 ).projectConfig
251 const { result } = await generateResetPasswordTokenWorkflow(
252 container
253 ).run({
254 input: {
255 entityId: "test@medusa-commerce.com",
256 actorType: "user",
257 provider: "emailpass",
258 secret: http.jwtSecret!,
259 jwtOptions: http.jwtOptions,
260 },
261 })
262
263 const response = await api.post(
264 `/auth/user/emailpass/update`,
265 {
266 email: "test+new@medusa-commerce.com",
267 password: "new_password",
268 },
269 {
270 headers: {
271 authorization: `Bearer ${result}`,
272 },
273 }
274 )
275
276 expect(response.status).toEqual(200)
277 expect(response.data).toEqual({ success: true })
278
279 const failedLogin = await api
280 .post("/auth/user/emailpass", {
281 email: "test+new@medusa-commerce.com",
282 password: "new_password",
283 })
284 .catch((e) => e)
285
286 expect(failedLogin.response.status).toEqual(401)
287 expect(failedLogin.response.data.message).toEqual(
288 "Invalid email or password"
289 )
290
291 const login = await api.post("/auth/user/emailpass", {
292 email: "test@medusa-commerce.com",
293 password: "new_password",
294 })
295
296 expect(login.status).toEqual(200)
297 expect(login.data).toEqual({ token: expect.any(String) })
298 })
299
300 it("should fail if token has expired", async () => {
301 // Register user
302 await api.post("/auth/user/emailpass/register", {
303 email: "test@medusa-commerce.com",
304 password: "secret_password",
305 })
306
307 // The token won't be part of the Rest API response, so we need to generate it manually
308 const { result } = await generateResetPasswordTokenWorkflow(
309 container
310 ).run({
311 input: {
312 entityId: "test@medusa-commerce.com",
313 actorType: "user",
314 provider: "emailpass",
315 secret: "test",
316 },
317 })
318
319 await dbConnection.raw(
320 `UPDATE "auth_password_reset_token" SET expires_at = NOW() - INTERVAL '1 day' WHERE entity_id = ? AND deleted_at IS NULL`,
321 ["test@medusa-commerce.com"]
322 )
323
324 const response = await api
325 .post(
326 `/auth/user/emailpass/update`,
327 {
328 password: "new_password",
329 },
330 {
331 headers: {
332 authorization: `Bearer ${result}`,
333 },
334 }
335 )
336 .catch((e) => e)
337
338 expect(response.response.status).toEqual(401)
339 expect(response.response.data.message).toEqual("Invalid token")
340 })
341
342 it("should fail if no token is passed", async () => {
343 // Register user
344 await api.post("/auth/user/emailpass/register", {
345 email: "test@medusa-commerce.com",
346 password: "secret_password",
347 })
348
349 const response = await api
350 .post(`/auth/user/emailpass/update`, {
351 email: "test@medusa-commerce.com",
352 })
353 .catch((e) => e)
354
355 expect(response.response.status).toEqual(401)
356 expect(response.response.data.message).toEqual("Invalid token")
357 })
358
359 it("should fail if update is attempted on different actor type", async () => {
360 // Register user
361 await api.post("/auth/user/emailpass/register", {
362 email: "test@medusa-commerce.com",
363 password: "secret_password",
364 })
365
366 // The token won't be part of the Rest API response, so we need to generate it manually
367 const { result } = await generateResetPasswordTokenWorkflow(
368 container
369 ).run({
370 input: {
371 entityId: "test@medusa-commerce.com",
372 actorType: "user",
373 provider: "emailpass",
374 secret: "test",
375 },
376 })
377
378 const response = await api
379 .post(
380 `/auth/customer/emailpass/update`,
381 {
382 password: "new_password",
383 },
384 {
385 headers: {
386 authorization: `Bearer ${result}`,
387 },
388 }
389 )
390 .catch((e) => e)
391
392 expect(response.response.status).toEqual(401)
393 expect(response.response.data.message).toEqual("Invalid token")
394 })
395
396 it("should fail if token secret is incorrect", async () => {
397 // Register user
398 await api.post("/auth/user/emailpass/register", {
399 email: "test@medusa-commerce.com",
400 password: "secret_password",
401 })
402
403 // The token won't be part of the Rest API response, so we need to generate it manually
404 const { result } = await generateResetPasswordTokenWorkflow(
405 container
406 ).run({
407 input: {
408 entityId: "test@medusa-commerce.com",
409 actorType: "user",
410 provider: "emailpass",
411 secret: "incorrect_secret",
412 },
413 })
414
415 const response = await api
416 .post(
417 `/auth/user/emailpass/update`,
418 {
419 password: "new_password",
420 },
421 {
422 headers: {
423 authorization: `Bearer ${result}`,
424 },
425 }
426 )
427 .catch((e) => e)
428
429 expect(response.response.status).toEqual(401)
430 expect(response.response.data.message).toEqual("Invalid token")
431 })
432 })
433
434 it("should refresh the token successfully", async () => {
435 // Make sure issue date is later than the admin one
436 await new Promise((resolve) => setTimeout(resolve, 100))
437
438 const resp = await api.post("/auth/token/refresh", {}, adminHeaders)
439 const decodedOriginalToken = jwt.decode(
440 adminHeaders.headers["authorization"].split(" ")[1]
441 ) as any
442 const decodedRefreshedToken = jwt.decode(resp.data.token) as any
443
444 expect(decodedOriginalToken).toEqual(
445 expect.objectContaining({
446 actor_id: decodedRefreshedToken.actor_id,
447 actor_type: decodedRefreshedToken.actor_type,
448 auth_identity_id: decodedRefreshedToken.auth_identity_id,
449 })
450 )
451
452 expect(decodedOriginalToken.iat).toBeLessThan(decodedRefreshedToken.iat)
453 expect(decodedOriginalToken.exp).toBeLessThan(decodedRefreshedToken.exp)
454 })
455 },
456 })