1 import {
2 AuthIdentityDTO,
3 IAuthModuleService,
4 UserDTO,
5 } from "@medusajs/framework/types"
6 import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
7 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
8 import jwt from "jsonwebtoken"
9 import {
10 adminHeaders,
11 createAdminUser,
12 } from "../../../../helpers/create-admin-user"
13
14 jest.setTimeout(100000)
15
16 medusaIntegrationTestRunner({
17 testSuite: ({ getContainer, api, dbConnection, dbUtils }) => {
18 let authModule: IAuthModuleService
19 let jwtSecret: string
20 let existingUser: UserDTO
21 let existingAuthIdentity: AuthIdentityDTO
22
23 beforeAll(async () => {
24 const container = getContainer()
25 authModule = container.resolve(Modules.AUTH)
26
27 const config = container.resolve(ContainerRegistrationKeys.CONFIG_MODULE)
28 jwtSecret = config.projectConfig.http.jwtSecret!.toString()
29
30 const adminUser = await createAdminUser(
31 dbConnection,
32 adminHeaders,
33 getContainer()
34 )
35 existingUser = adminUser.user
36 existingAuthIdentity = adminUser.authIdentity
37
38 await dbUtils.snapshot()
39 })
40
41 describe("POST /cloud/auth/users", () => {
42 it("should create a new user when user doesn't exist", async () => {
43 // Create an auth identity (simulating cloud auth callback)
44 const authIdentity = await authModule.createAuthIdentities({
45 provider_identities: [
46 {
47 provider: "cloud",
48 entity_id: "cloud-user-123",
49 user_metadata: {
50 email: "john@doe.com",
51 given_name: "John",
52 family_name: "Doe",
53 },
54 },
55 ],
56 })
57
58 // Generate a token for this auth identity (without actor_id since user doesn't exist yet)
59 const token = jwt.sign(
60 {
61 actor_id: "",
62 actor_type: "user",
63 auth_identity_id: authIdentity.id,
64 auth_provider: "cloud",
65 user_metadata: {
66 email: "john@doe.com",
67 given_name: "John",
68 family_name: "Doe",
69 },
70 },
71 jwtSecret,
72 { expiresIn: "1d" }
73 )
74
75 // Call the endpoint to create the user
76 const createUserResponse = await api.post(
77 "/cloud/auth/users",
78 {},
79 { headers: { authorization: `Bearer ${token}` } }
80 )
81 expect(createUserResponse.status).toEqual(200)
82 expect(createUserResponse.data.user).toMatchObject({
83 id: expect.any(String),
84 email: "john@doe.com",
85 first_name: "John",
86 last_name: "Doe",
87 })
88 const createdUserId = createUserResponse.data.user.id
89 expect(createdUserId).not.toEqual(existingUser.id)
90
91 // Refresh the token to get updated actor_id which should be the user's id
92 const refreshResponse = await api.post(
93 "/auth/token/refresh",
94 {},
95 { headers: { authorization: `Bearer ${token}` } }
96 )
97 expect(refreshResponse.status).toEqual(200)
98 const refreshedToken = refreshResponse.data.token
99 expect(jwt.decode(refreshResponse.data.token)).toMatchObject({
100 actor_type: "user",
101 auth_identity_id: authIdentity.id,
102 actor_id: createdUserId,
103 })
104
105 // Verify the user was created
106 const meResponse = await api.get("/admin/users/me", {
107 headers: {
108 authorization: `Bearer ${refreshedToken}`,
109 },
110 })
111 expect(meResponse.status).toEqual(200)
112 expect(meResponse.data.user).toMatchObject({
113 id: createdUserId,
114 email: "john@doe.com",
115 first_name: "John",
116 last_name: "Doe",
117 })
118 })
119
120 it("should link existing user to auth identity when user with same email already exists", async () => {
121 // Create an auth identity (simulating cloud auth callback)
122 const authIdentity = await authModule.createAuthIdentities({
123 provider_identities: [
124 {
125 provider: "cloud",
126 entity_id: "cloud-user-123",
127 user_metadata: {
128 email: existingUser.email,
129 given_name: "John",
130 family_name: "Doe",
131 },
132 },
133 ],
134 })
135
136 // Generate a token for this auth identity (without actor_id since user doesn't exist yet)
137 const token = jwt.sign(
138 {
139 actor_id: "",
140 actor_type: "user",
141 auth_identity_id: authIdentity.id,
142 auth_provider: "cloud",
143 user_metadata: {
144 email: existingUser.email,
145 given_name: "John",
146 family_name: "Doe",
147 },
148 },
149 jwtSecret,
150 { expiresIn: "1d" }
151 )
152
153 // Call the endpoint to create the user
154 const createUserResponse = await api.post(
155 "/cloud/auth/users",
156 {},
157 { headers: { authorization: `Bearer ${token}` } }
158 )
159 expect(createUserResponse.status).toEqual(200)
160 expect(createUserResponse.data.user).toMatchObject({
161 id: existingUser.id,
162 email: existingUser.email,
163 })
164
165 // Refresh the token to get updated actor_id, which should be the user id
166 const refreshResponse = await api.post(
167 "/auth/token/refresh",
168 {},
169 { headers: { authorization: `Bearer ${token}` } }
170 )
171 expect(refreshResponse.status).toEqual(200)
172 expect(jwt.decode(refreshResponse.data.token)).toMatchObject({
173 actor_type: "user",
174 auth_identity_id: authIdentity.id,
175 actor_id: existingUser.id,
176 })
177
178 // Verify the previous auth identity is still linked to the user
179 const updatedAuthIdentity = await authModule.retrieveAuthIdentity(
180 existingAuthIdentity.id
181 )
182 expect(updatedAuthIdentity.app_metadata?.user_id).toEqual(
183 existingUser.id
184 )
185 })
186
187 it("should not allow non-cloud identities to create a user", async () => {
188 // Create an auth identity
189 const authIdentity = await authModule.createAuthIdentities({
190 provider_identities: [
191 {
192 provider: "github",
193 entity_id: "github-user-123",
194 user_metadata: {
195 email: "john@doe.com",
196 given_name: "John",
197 family_name: "Doe",
198 },
199 },
200 ],
201 })
202
203 // Generate a token for this auth identity (without actor_id since user doesn't exist yet)
204 const token = jwt.sign(
205 {
206 actor_id: "",
207 actor_type: "user",
208 auth_identity_id: authIdentity.id,
209 user_metadata: {
210 email: "john@doe.com",
211 given_name: "John",
212 family_name: "Doe",
213 },
214 },
215 jwtSecret,
216 { expiresIn: "1d" }
217 )
218
219 // Call the endpoint to create the user
220 const createUserResponse = await api
221 .post(
222 "/cloud/auth/users",
223 {},
224 { headers: { authorization: `Bearer ${token}` } }
225 )
226 .catch((error) => error.response)
227 expect(createUserResponse.status).toEqual(401)
228 })
229 })
230 },
231 })