1 import {
2 Context,
3 DAL,
4 InferEntityType,
5 InternalModuleDeclaration,
6 ModulesSdkTypes,
7 ProjectConfigOptions,
8 UserTypes,
9 } from "@medusajs/framework/types"
10 import {
11 arrayDifference,
12 CommonEvents,
13 EmitEvents,
14 generateEntityId,
15 generateJwtToken,
16 InjectManager,
17 InjectTransactionManager,
18 MedusaContext,
19 MedusaError,
20 MedusaService,
21 moduleEventBuilderFactory,
22 Modules,
23 UserEvents,
24 } from "@medusajs/framework/utils"
25 import jwt, { JwtPayload, SignOptions, VerifyOptions } from "jsonwebtoken"
26 import crypto from "node:crypto"
27
28 import { Invite, User } from "@models"
29 import { getExpiresAt } from "../utils/utils"
30
31 type InjectedDependencies = {
32 baseRepository: DAL.RepositoryService
33 userService: ModulesSdkTypes.IMedusaInternalService<any>
34 inviteService: ModulesSdkTypes.IMedusaInternalService<any>
35 }
36
37 const DEFAULT_VALID_INVITE_DURATION_SECONDS = 60 * 60 * 24
38 export default class UserModuleService
39 extends MedusaService<{
40 User: {
41 dto: UserTypes.UserDTO
42 }
43 Invite: {
44 dto: UserTypes.InviteDTO
45 }
46 }>({ User, Invite })
47 implements UserTypes.IUserModuleService
48 {
49 protected baseRepository_: DAL.RepositoryService
50
51 protected readonly userService_: ModulesSdkTypes.IMedusaInternalService<
52 InferEntityType<typeof User>
53 >
54 protected readonly inviteService_: ModulesSdkTypes.IMedusaInternalService<
55 InferEntityType<typeof Invite>
56 >
57 protected readonly config: {
58 jwtSecret: string
59 jwtPublicKey?: string
60 jwt_verify_options: ProjectConfigOptions["http"]["jwtVerifyOptions"]
61 jwtOptions: ProjectConfigOptions["http"]["jwtOptions"] & {
62 expiresIn: number
63 }
64 }
65
66 constructor(
67 { userService, inviteService, baseRepository }: InjectedDependencies,
68 moduleDeclaration: InternalModuleDeclaration
69 ) {
70 // @ts-ignore
71 super(...arguments)
72
73 this.baseRepository_ = baseRepository
74 this.userService_ = userService
75 this.inviteService_ = inviteService
76
77 this.config = {
78 jwtSecret: moduleDeclaration["jwt_secret"],
79 jwtPublicKey: moduleDeclaration["jwt_public_key"],
80 jwt_verify_options: moduleDeclaration["jwt_verify_options"],
81 jwtOptions: {
82 ...moduleDeclaration["jwt_options"],
83 expiresIn:
84 moduleDeclaration["valid_duration"] ??
85 moduleDeclaration["jwt_options"]?.expiresIn ??
86 DEFAULT_VALID_INVITE_DURATION_SECONDS,
87 },
88 }
89
90 if (!this.config.jwtSecret) {
91 throw new MedusaError(
92 MedusaError.Types.INVALID_DATA,
93 "No jwt_secret was provided in the UserModule's options. Please add one."
94 )
95 }
96 }
97
98 @InjectManager()
99 async validateInviteToken(
100 token: string,
101 @MedusaContext() sharedContext: Context = {}
102 ): Promise<UserTypes.InviteDTO> {
103 const options = {
104 ...(this.config.jwt_verify_options ?? this.config.jwtOptions),
105 complete: true,
106 } as VerifyOptions & SignOptions
107
108 if (!options.algorithms && options.algorithm) {
109 options.algorithms = [options.algorithm]
110 delete options.algorithm
111 }
112
113 const decoded = jwt.verify(
114 token,
115 this.config.jwtPublicKey ?? this.config.jwtSecret,
116 options
117 ) as JwtPayload
118
119 const invite = await this.inviteService_.retrieve(
120 decoded.payload.id,
121 {},
122 sharedContext
123 )
124
125 // Reject tokens that have been rotated (e.g. by a resend). Without this
126 // check, any previously-issued JWT remains valid for the full TTL even
127 // after `refreshInviteTokens_` writes a new token to the DB.
128 if (token !== invite.token) {
129 throw new MedusaError(
130 MedusaError.Types.INVALID_DATA,
131 "The invite token is invalid"
132 )
133 }
134
135 if (invite.expires_at < new Date()) {
136 throw new MedusaError(
137 MedusaError.Types.INVALID_DATA,
138 "The invite has expired"
139 )
140 }
141
142 return await this.baseRepository_.serialize<UserTypes.InviteDTO>(invite)
143 }
144
145 @InjectManager()
146 @EmitEvents()
147 async refreshInviteTokens(
148 inviteIds: string[],
149 @MedusaContext() sharedContext: Context = {}
150 ): Promise<UserTypes.InviteDTO[]> {
151 const invites = await this.refreshInviteTokens_(inviteIds, sharedContext)
152
153 const serializedInvites = await this.baseRepository_.serialize<
154 UserTypes.InviteDTO[]
155 >(invites)
156
157 moduleEventBuilderFactory({
158 eventName: UserEvents.INVITE_TOKEN_GENERATED,
159 source: Modules.USER,
160 action: CommonEvents.CREATED,
161 object: "invite",
162 })({
163 data: serializedInvites,
164 sharedContext,
165 })
166
167 return serializedInvites
168 }
169
170 @InjectTransactionManager()
171 async refreshInviteTokens_(
172 inviteIds: string[],
173 @MedusaContext() sharedContext: Context = {}
174 ) {
175 const [invites, count] = await this.inviteService_.listAndCount(
176 { id: inviteIds },
177 {},
178 sharedContext
179 )
180
181 if (count !== inviteIds.length) {
182 const missing = arrayDifference(
183 inviteIds,
184 invites.map((invite) => invite.id)
185 )
186
187 if (missing.length > 0) {
188 throw new MedusaError(
189 MedusaError.Types.INVALID_DATA,
190 `The following invites do not exist: ${missing.join(", ")}`
191 )
192 }
193 }
194
195 const expiresAt = getExpiresAt(this.config.jwtOptions.expiresIn)
196 const updates = invites.map((invite) => {
197 return {
198 id: invite.id,
199 expires_at: expiresAt,
200 token: this.generateToken({ id: invite.id, email: invite.email }),
201 }
202 })
203
204 return await this.inviteService_.update(updates, sharedContext)
205 }
206
207 // @ts-expect-error
208 createUsers(
209 data: UserTypes.CreateUserDTO[],
210 sharedContext?: Context
211 ): Promise<UserTypes.UserDTO[]>
212 // @ts-expect-error
213 createUsers(
214 data: UserTypes.CreateUserDTO,
215 sharedContext?: Context
216 ): Promise<UserTypes.UserDTO>
217
218 @InjectManager()
219 @EmitEvents()
220 // @ts-expect-error
221 async createUsers(
222 data: UserTypes.CreateUserDTO[] | UserTypes.CreateUserDTO,
223 @MedusaContext() sharedContext: Context = {}
224 ): Promise<UserTypes.UserDTO | UserTypes.UserDTO[]> {
225 const input = Array.isArray(data) ? data : [data]
226
227 const users = await this.userService_.create(input, sharedContext)
228
229 const serializedUsers = await this.baseRepository_.serialize<
230 UserTypes.UserDTO[] | UserTypes.UserDTO
231 >(users)
232
233 return Array.isArray(data) ? serializedUsers : serializedUsers[0]
234 }
235
236 // @ts-expect-error
237 updateUsers(
238 data: UserTypes.UpdateUserDTO[],
239 sharedContext?: Context
240 ): Promise<UserTypes.UserDTO[]>
241 // @ts-expect-error
242 updateUsers(
243 data: UserTypes.UpdateUserDTO,
244 sharedContext?: Context
245 ): Promise<UserTypes.UserDTO>
246
247 @InjectManager()
248 @EmitEvents()
249 // @ts-expect-error
250 async updateUsers(
251 data: UserTypes.UpdateUserDTO | UserTypes.UpdateUserDTO[],
252 @MedusaContext() sharedContext: Context = {}
253 ): Promise<UserTypes.UserDTO | UserTypes.UserDTO[]> {
254 const input = Array.isArray(data) ? data : [data]
255
256 const updatedUsers = await this.userService_.update(input, sharedContext)
257
258 const serializedUsers = await this.baseRepository_.serialize<
259 UserTypes.UserDTO[]
260 >(updatedUsers)
261
262 return Array.isArray(data) ? serializedUsers : serializedUsers[0]
263 }
264
265 // @ts-expect-error
266 createInvites(
267 data: UserTypes.CreateInviteDTO[],
268 sharedContext?: Context
269 ): Promise<UserTypes.InviteDTO[]>
270 // @ts-expect-error
271 createInvites(
272 data: UserTypes.CreateInviteDTO,
273 sharedContext?: Context
274 ): Promise<UserTypes.InviteDTO>
275
276 @InjectManager()
277 @EmitEvents()
278 // @ts-expect-error
279 async createInvites(
280 data: UserTypes.CreateInviteDTO[] | UserTypes.CreateInviteDTO,
281 @MedusaContext() sharedContext: Context = {}
282 ): Promise<UserTypes.InviteDTO | UserTypes.InviteDTO[]> {
283 const input = Array.isArray(data) ? data : [data]
284
285 const invites = await this.createInvites_(input, sharedContext)
286
287 const serializedInvites = await this.baseRepository_.serialize<
288 UserTypes.InviteDTO[] | UserTypes.InviteDTO
289 >(invites)
290
291 moduleEventBuilderFactory({
292 eventName: UserEvents.INVITE_TOKEN_GENERATED,
293 source: Modules.USER,
294 action: "token_generated",
295 object: "invite",
296 })({
297 data: serializedInvites,
298 sharedContext,
299 })
300
301 return Array.isArray(data) ? serializedInvites : serializedInvites[0]
302 }
303
304 @InjectTransactionManager()
305 private async createInvites_(
306 data: UserTypes.CreateInviteDTO[],
307 @MedusaContext() sharedContext: Context = {}
308 ): Promise<InferEntityType<typeof Invite>[]> {
309 const alreadyExistingUsers = await this.listUsers({
310 email: data.map((d) => d.email),
311 })
312
313 if (alreadyExistingUsers.length) {
314 throw new MedusaError(
315 MedusaError.Types.INVALID_DATA,
316 `User account for following email(s) already exist: ${alreadyExistingUsers
317 .map((u) => u.email)
318 .join(", ")}`
319 )
320 }
321
322 const expiresAt = getExpiresAt(this.config.jwtOptions.expiresIn)
323
324 const toCreate = data.map((invite) => {
325 const id = generateEntityId((invite as { id?: string }).id, "invite")
326 return {
327 ...invite,
328 id,
329 expires_at: expiresAt,
330 token: this.generateToken({ id, email: invite.email }),
331 }
332 })
333
334 return await this.inviteService_.create(toCreate, sharedContext)
335 }
336
337 // @ts-ignore
338 updateInvites(
339 data: UserTypes.UpdateInviteDTO[],
340 sharedContext?: Context
341 ): Promise<UserTypes.InviteDTO[]>
342 // @ts-expect-error
343 updateInvites(
344 data: UserTypes.UpdateInviteDTO,
345 sharedContext?: Context
346 ): Promise<UserTypes.InviteDTO>
347
348 @InjectManager()
349 @EmitEvents()
350 // @ts-expect-error
351 async updateInvites(
352 data: UserTypes.UpdateInviteDTO | UserTypes.UpdateInviteDTO[],
353 @MedusaContext() sharedContext: Context = {}
354 ): Promise<UserTypes.InviteDTO | UserTypes.InviteDTO[]> {
355 const input = Array.isArray(data) ? data : [data]
356
357 const updatedInvites = await this.inviteService_.update(
358 input,
359 sharedContext
360 )
361
362 const serializedInvites = await this.baseRepository_.serialize<
363 UserTypes.InviteDTO[]
364 >(updatedInvites)
365
366 moduleEventBuilderFactory({
367 eventName: UserEvents.INVITE_TOKEN_GENERATED,
368 source: Modules.USER,
369 action: "token_generated",
370 object: "invite",
371 })({
372 data: serializedInvites,
373 sharedContext,
374 })
375
376 return Array.isArray(data) ? serializedInvites : serializedInvites[0]
377 }
378
379 private generateToken(data: any): string {
380 const jwtId = this.config.jwtOptions.jwtid ?? crypto.randomUUID()
381 const token = generateJwtToken(data, {
382 secret: this.config.jwtSecret,
383 jwtOptions: {
384 ...this.config.jwtOptions,
385 jwtid: jwtId,
386 },
387 })
388
389 return token
390 }
391 }