1 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
2 import {
3 adminHeaders,
4 createAdminUser,
5 } from "../../../../helpers/create-admin-user"
6
7 jest.setTimeout(30000)
8
9 process.env.MEDUSA_FF_RBAC = "true"
10
11 medusaIntegrationTestRunner({
12 testSuite: ({ dbConnection, api, getContainer, dbUtils }) => {
13 let invite
14 beforeAll(async () => {
15 const appContainer = getContainer()
16 await createAdminUser(dbConnection, adminHeaders, appContainer)
17
18 invite = (
19 await api.post(
20 "/admin/invites",
21 {
22 email: "invite@medusa-commerce.com",
23 },
24 adminHeaders
25 )
26 ).data.invite
27
28 await dbUtils.snapshot()
29 })
30
31 afterEach(() => {
32 jest.useRealTimers()
33 })
34
35 describe("Admin invites", () => {
36 it("should create, list, retrieve, and accept (deleting) an invite", async () => {
37 const createdInvite = (
38 await api.post(
39 "/admin/invites",
40 {
41 email: "test@medusa-commerce.com",
42 },
43 adminHeaders
44 )
45 ).data.invite
46
47 expect(createdInvite).toEqual(
48 expect.objectContaining({
49 email: "test@medusa-commerce.com",
50 })
51 )
52
53 const listInvites = (await api.get("/admin/invites", adminHeaders)).data
54 .invites
55
56 expect(listInvites).toEqual([
57 expect.objectContaining({
58 email: "invite@medusa-commerce.com",
59 }),
60 expect.objectContaining({
61 email: "test@medusa-commerce.com",
62 }),
63 ])
64
65 const getInvite = (
66 await api.get(`/admin/invites/${createdInvite.id}`, adminHeaders)
67 ).data.invite
68
69 expect(getInvite).toEqual(
70 expect.objectContaining({
71 email: "test@medusa-commerce.com",
72 })
73 )
74
75 const signup = await api.post("/auth/user/emailpass/register", {
76 email: "test@medusa-commerce.com",
77 password: "secret_password",
78 })
79
80 expect(signup.status).toEqual(200)
81 expect(signup.data).toEqual({ token: expect.any(String) })
82
83 const acceptedInvite = (
84 await api.post(
85 `/admin/invites/accept?token=${createdInvite.token}`,
86 {
87 first_name: "Test",
88 last_name: "User",
89 },
90 { headers: { authorization: `Bearer ${signup.data.token}` } }
91 )
92 ).data.user
93
94 expect(acceptedInvite).toEqual(
95 expect.objectContaining({
96 email: "test@medusa-commerce.com",
97 })
98 )
99 })
100
101 it("should fail to accept an invite given an invalid token", async () => {
102 expect.assertions(2)
103 const signup = await api.post("/auth/user/emailpass/register", {
104 email: "test@medusa-commerce.com",
105 password: "secret_password",
106 })
107
108 // Some malformed token
109 const token =
110 "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpbnZpdGVfaWQiOiJpbnZpdGVfMDFGSFFWNlpBOERRRlgySjM3UVo5SjZTOTAiLCJyb2xlIjoiYWRtaW4iLCJ1c2VyX2VtYWlsIjoic2ZAc2RmLmNvbSIsImlhdCI6MTYzMzk2NDAyMCwiZXhwIjoxNjM0NTY4ODIwfQ.ZsmDvunBxhRW1iRqvfEfWixJLZ1zZVzaEYST38Vbl00"
111
112 await api
113 .post(
114 `/admin/invites/accept?token=${token}`,
115 {
116 first_name: "test",
117 last_name: "testesen",
118 },
119 {
120 headers: { authorization: `Bearer ${signup.data.token}` },
121 }
122 )
123 .catch((err) => {
124 expect(err.response.status).toEqual(401)
125 expect(err.response.data.message).toEqual("Unauthorized")
126 })
127 })
128
129 it("should fail to accept an already accepted invite ", async () => {
130 const signup = await api.post("/auth/user/emailpass/register", {
131 email: "test@medusa-commerce.com",
132 password: "secret_password",
133 })
134
135 await api.post(
136 `/admin/invites/accept?token=${invite.token}`,
137 {
138 first_name: "Test",
139 last_name: "User",
140 },
141 {
142 headers: { authorization: `Bearer ${signup.data.token}` },
143 }
144 )
145
146 const signupAgain = await api.post("/auth/user/emailpass/register", {
147 email: "another-test@medusa-commerce.com",
148 password: "secret_password",
149 })
150
151 const error = await api
152 .post(
153 `/admin/invites/accept?token=${invite.token}`,
154 {
155 first_name: "Another Test",
156 last_name: "User",
157 },
158 {
159 headers: { authorization: `Bearer ${signupAgain.data.token}` },
160 }
161 )
162 .catch((e) => e.response)
163
164 expect(error.status).toEqual(401)
165 expect(error.data.message).toEqual("Unauthorized")
166 })
167
168 it("should fail to accept with an expired token", async () => {
169 const signup = await api.post("/auth/user/emailpass/register", {
170 email: "test@medusa-commerce.com",
171 password: "secret_password",
172 })
173
174 await dbConnection.raw(
175 `UPDATE "invite" SET expires_at = NOW() - INTERVAL '1 day' WHERE id = ?`,
176 [invite.id]
177 )
178
179 const error = await api
180 .post(
181 `/admin/invites/accept?token=${invite.token}`,
182 {
183 first_name: "Another Test",
184 last_name: "User",
185 },
186 {
187 headers: { authorization: `Bearer ${signup.data.token}` },
188 }
189 )
190 .catch((e) => e.response)
191
192 expect(error.status).toEqual(401)
193 expect(error.data.message).toEqual("Unauthorized")
194 })
195
196 it("should resend an invite", async () => {
197 const resendResponse = (
198 await api.post(`/admin/invites/${invite.id}/resend`, {}, adminHeaders)
199 ).data.invite
200
201 // Resending an invite regenerates the token
202 expect(resendResponse.token).toBeDefined()
203 expect(resendResponse.token).not.toEqual(invite.token)
204 })
205 it("should delete an invite", async () => {
206 const deleteResponse = (
207 await api.delete(`/admin/invites/${invite.id}`, adminHeaders)
208 ).data
209
210 expect(deleteResponse).toEqual({
211 id: invite.id,
212 object: "invite",
213 deleted: true,
214 })
215 })
216 })
217
218 describe("Admin invites with roles", () => {
219 let viewerRole, editorRole, superAdminRole
220
221 beforeEach(async () => {
222 // Create test roles
223 const viewerResponse = await api.post(
224 "/admin/rbac/roles",
225 {
226 name: "Product Viewer",
227 description: "Can view products",
228 },
229 adminHeaders
230 )
231 viewerRole = viewerResponse.data.role
232
233 const editorResponse = await api.post(
234 "/admin/rbac/roles",
235 {
236 name: "Product Editor",
237 description: "Can edit products",
238 },
239 adminHeaders
240 )
241 editorRole = editorResponse.data.role
242
243 // Get the super admin role created by migration
244 const superAdminResponse = await api.get(
245 "/admin/rbac/roles?id=role_super_admin",
246 adminHeaders
247 )
248 superAdminRole = superAdminResponse.data.roles[0]
249 })
250
251 it("should create invite with roles and assign them to user on acceptance", async () => {
252 // Create invite with multiple roles
253 const createdInvite = (
254 await api.post(
255 "/admin/invites",
256 {
257 email: "role-test@medusa-commerce.com",
258 roles: [viewerRole.id, editorRole.id],
259 },
260 adminHeaders
261 )
262 ).data.invite
263
264 expect(createdInvite).toEqual(
265 expect.objectContaining({
266 email: "role-test@medusa-commerce.com",
267 })
268 )
269
270 // Verify invite is linked to roles
271 const container = getContainer()
272 const {
273 ContainerRegistrationKeys,
274 Modules,
275 } = require("@medusajs/framework/utils")
276 const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
277
278 const inviteLinkService = remoteLink.getLinkModule(
279 Modules.USER,
280 "invite_id",
281 Modules.RBAC,
282 "rbac_role_id"
283 )
284
285 const inviteRoles = await inviteLinkService.list({
286 invite_id: createdInvite.id,
287 })
288
289 expect(inviteRoles).toHaveLength(2)
290 expect(inviteRoles.map((link) => link.rbac_role_id)).toEqual(
291 expect.arrayContaining([viewerRole.id, editorRole.id])
292 )
293
294 // Register and accept the invite
295 const signup = await api.post("/auth/user/emailpass/register", {
296 email: "role-test@medusa-commerce.com",
297 password: "secret_password",
298 })
299
300 expect(signup.status).toEqual(200)
301
302 const acceptedUser = (
303 await api.post(
304 `/admin/invites/accept?token=${createdInvite.token}`,
305 {
306 first_name: "Role",
307 last_name: "Test",
308 },
309 { headers: { authorization: `Bearer ${signup.data.token}` } }
310 )
311 ).data.user
312
313 expect(acceptedUser).toEqual(
314 expect.objectContaining({
315 email: "role-test@medusa-commerce.com",
316 first_name: "Role",
317 last_name: "Test",
318 })
319 )
320
321 const userLinkService = remoteLink.getLinkModule(
322 Modules.USER,
323 "user_id",
324 Modules.RBAC,
325 "rbac_role_id"
326 )
327
328 // Verify user was assigned the roles
329 const userRoles = await userLinkService.list({
330 user_id: acceptedUser.id,
331 })
332
333 expect(userRoles).toHaveLength(2)
334 expect(userRoles.map((link) => link.rbac_role_id)).toEqual(
335 expect.arrayContaining([viewerRole.id, editorRole.id])
336 )
337 })
338
339 it("should create invite with super admin role and assign it to user", async () => {
340 // Create invite with super admin role
341 const createdInvite = (
342 await api.post(
343 "/admin/invites",
344 {
345 email: "admin-test@medusa-commerce.com",
346 roles: [superAdminRole.id],
347 },
348 adminHeaders
349 )
350 ).data.invite
351
352 // Register and accept the invite
353 const signup = await api.post("/auth/user/emailpass/register", {
354 email: "admin-test@medusa-commerce.com",
355 password: "secret_password",
356 })
357
358 const acceptedUser = (
359 await api.post(
360 `/admin/invites/accept?token=${createdInvite.token}`,
361 {
362 first_name: "Admin",
363 last_name: "Test",
364 },
365 { headers: { authorization: `Bearer ${signup.data.token}` } }
366 )
367 ).data.user
368
369 // Verify user was assigned the super admin role
370 const container = getContainer()
371 const {
372 ContainerRegistrationKeys,
373 Modules,
374 } = require("@medusajs/framework/utils")
375 const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
376
377 const linkService = remoteLink.getLinkModule(
378 Modules.USER,
379 "user_id",
380 Modules.RBAC,
381 "rbac_role_id"
382 )
383
384 const userRoles = await linkService.list({
385 user_id: acceptedUser.id,
386 })
387
388 expect(userRoles).toHaveLength(1)
389 expect(userRoles[0].rbac_role_id).toEqual(superAdminRole.id)
390 })
391
392 it("should create invite without roles and work normally", async () => {
393 // Create invite without roles (existing behavior)
394 const createdInvite = (
395 await api.post(
396 "/admin/invites",
397 {
398 email: "no-roles-test@medusa-commerce.com",
399 },
400 adminHeaders
401 )
402 ).data.invite
403
404 // Register and accept the invite
405 const signup = await api.post("/auth/user/emailpass/register", {
406 email: "no-roles-test@medusa-commerce.com",
407 password: "secret_password",
408 })
409
410 const acceptedUser = (
411 await api.post(
412 `/admin/invites/accept?token=${createdInvite.token}`,
413 {
414 first_name: "No Roles",
415 last_name: "Test",
416 },
417 { headers: { authorization: `Bearer ${signup.data.token}` } }
418 )
419 ).data.user
420
421 // Verify user has no roles assigned
422 const container = getContainer()
423 const {
424 ContainerRegistrationKeys,
425 Modules,
426 } = require("@medusajs/framework/utils")
427 const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
428
429 const linkService = remoteLink.getLinkModule(
430 Modules.USER,
431 "user_id",
432 Modules.RBAC,
433 "rbac_role_id"
434 )
435
436 const userRoles = await linkService.list({
437 user_id: acceptedUser.id,
438 })
439
440 expect(userRoles).toHaveLength(0)
441 })
442
443 it("should handle invite with non-existent role gracefully", async () => {
444 // Try to create invite with non-existent role
445 const error = await api
446 .post(
447 "/admin/invites",
448 {
449 email: "invalid-role-test@medusa-commerce.com",
450 roles: ["non_existent_role_id"],
451 },
452 adminHeaders
453 )
454 .catch((e) => e.response)
455
456 expect(error.status).toEqual(400)
457 expect(error.data.message).toContain("role")
458 })
459 })
460 },
461 })