1 import {
2 Context,
3 FilterableRbacRoleProps,
4 FindConfig,
5 RbacRoleDTO,
6 } from "@medusajs/framework/types"
7 import {
8 InjectManager,
9 InjectTransactionManager,
10 MedusaContext,
11 MedusaService,
12 Policy,
13 promiseAll,
14 WILDCARD,
15 } from "@medusajs/framework/utils"
16 import {
17 CreateRbacRoleParentDTO,
18 InferEntityType,
19 IRbacModuleService,
20 ModulesSdkTypes,
21 RbacRoleParentDTO,
22 UpdateRbacRoleParentDTO,
23 } from "@medusajs/types"
24 import { RbacPolicy, RbacRole, RbacRoleParent, RbacRolePolicy } from "@models"
25 import { RbacRepository } from "../repositories"
26
27 type InjectedDependencies = {
28 rbacRepository: RbacRepository
29 rbacRolePolicyService: ModulesSdkTypes.IMedusaInternalService<
30 InferEntityType<typeof RbacRolePolicy>
31 >
32 rbacRoleService: ModulesSdkTypes.IMedusaInternalService<
33 InferEntityType<typeof RbacRole>
34 >
35 rbacPolicyService: ModulesSdkTypes.IMedusaInternalService<
36 InferEntityType<typeof RbacPolicy>
37 >
38 }
39
40 const SUPER_ADMIN_KEY = `${WILDCARD}:${WILDCARD}`
41
42 export default class RbacModuleService
43 extends MedusaService({
44 RbacRole,
45 RbacPolicy,
46 RbacRoleParent,
47 RbacRolePolicy,
48 })
49 implements IRbacModuleService
50 {
51 protected readonly rbacRepository_: RbacRepository
52 protected readonly rbacRolePolicyService: ModulesSdkTypes.IMedusaInternalService<
53 InferEntityType<typeof RbacRolePolicy>
54 >
55 protected readonly rbacRoleService: ModulesSdkTypes.IMedusaInternalService<
56 InferEntityType<typeof RbacRole>
57 >
58 protected readonly rbacPolicyService: ModulesSdkTypes.IMedusaInternalService<
59 InferEntityType<typeof RbacPolicy>
60 >
61
62 constructor({
63 rbacRepository,
64 rbacRoleService,
65 rbacPolicyService,
66 rbacRolePolicyService,
67 }: InjectedDependencies) {
68 // @ts-ignore
69 super(...arguments)
70 this.rbacRepository_ = rbacRepository
71 this.rbacRolePolicyService = rbacRolePolicyService
72 this.rbacRoleService = rbacRoleService
73 this.rbacPolicyService = rbacPolicyService
74 }
75
76 __hooks = {
77 onApplicationStart: async () => {
78 await this.syncRegisteredPolicies()
79 },
80 }
81
82 @InjectTransactionManager()
83 private async syncRegisteredPolicies(
84 @MedusaContext() sharedContext: Context = {}
85 ): Promise<void> {
86 const registeredPolicies = Object.entries(Policy).map(
87 ([name, { resource, operation, description }]) => ({
88 key: `${resource}:${operation}`,
89 name,
90 resource,
91 operation,
92 description,
93 })
94 )
95
96 const registeredKeys = registeredPolicies.map((p) => p.key)
97
98 // Fetch all existing policies (including soft-deleted ones)
99 const existingPolicies = await this.listRbacPolicies(
100 {},
101 { withDeleted: true },
102 sharedContext
103 )
104
105 const existingPoliciesMap = new Map(existingPolicies.map((p) => [p.key, p]))
106
107 const policiesToCreate: any[] = []
108 const policiesToUpdate: any[] = []
109 const policiesToRestore: string[] = []
110
111 // Process registered policies
112 for (const registeredPolicy of registeredPolicies) {
113 if (registeredPolicy.key === SUPER_ADMIN_KEY) {
114 continue
115 }
116
117 const existing = existingPoliciesMap.get(registeredPolicy.key)
118
119 const hasChanges =
120 existing &&
121 (existing.name !== registeredPolicy.name ||
122 existing.description !== registeredPolicy.description)
123
124 if (!existing) {
125 policiesToCreate.push(registeredPolicy)
126 } else if (existing.deleted_at) {
127 policiesToRestore.push(existing.id)
128 if (hasChanges) {
129 policiesToUpdate.push({
130 id: existing.id,
131 name: registeredPolicy.name,
132 description: registeredPolicy.description,
133 })
134 }
135 } else if (hasChanges) {
136 policiesToUpdate.push({
137 id: existing.id,
138 name: registeredPolicy.name,
139 description: registeredPolicy.description,
140 })
141 }
142 }
143
144 const policiesToSoftDelete = existingPolicies
145 .filter(
146 (p) =>
147 !p.deleted_at &&
148 !registeredKeys.includes(p.key) &&
149 p.key !== SUPER_ADMIN_KEY
150 )
151 .map((p) => p.id)
152
153 // First restore any soft-deleted policies
154 if (policiesToRestore.length > 0) {
155 await this.restoreRbacPolicies(policiesToRestore, {}, sharedContext)
156 }
157
158 await promiseAll([
159 policiesToCreate.length > 0 &&
160 this.rbacPolicyService.create(policiesToCreate, sharedContext),
161 policiesToUpdate.length > 0 &&
162 this.rbacPolicyService.upsert(policiesToUpdate, sharedContext),
163 policiesToSoftDelete.length > 0 &&
164 this.rbacPolicyService.softDelete(policiesToSoftDelete, sharedContext),
165 ])
166 }
167
168 @InjectManager()
169 async listPoliciesForRole(
170 roleId: string,
171 @MedusaContext() sharedContext: Context = {}
172 ): Promise<any[]> {
173 return await this.rbacRepository_.listPoliciesForRole(roleId, sharedContext)
174 }
175
176 @InjectManager()
177 // @ts-expect-error
178 async listRbacRoles(
179 filters: FilterableRbacRoleProps = {},
180 config: FindConfig<RbacRoleDTO> = {},
181 @MedusaContext() sharedContext: Context = {}
182 ): Promise<RbacRoleDTO[]> {
183 const roles = await super.listRbacRoles(
184 filters,
185 config as any,
186 sharedContext
187 )
188
189 const shouldIncludePolicies =
190 config.relations?.includes("policies") ||
191 config.select?.includes("policies")
192
193 if (shouldIncludePolicies && roles.length > 0) {
194 const roleIds = roles.map((role) => role.id)
195 const policiesByRole = await this.rbacRepository_.listPoliciesForRoles(
196 roleIds,
197 sharedContext
198 )
199
200 for (const role of roles) {
201 role.policies = policiesByRole.get(role.id) || []
202 }
203 }
204
205 return roles as unknown as RbacRoleDTO[]
206 }
207
208 @InjectManager()
209 // @ts-expect-error
210 async listAndCountRbacRoles(
211 filters: FilterableRbacRoleProps = {},
212 config: FindConfig<RbacRoleDTO> = {},
213 @MedusaContext() sharedContext: Context = {}
214 ): Promise<[RbacRoleDTO[], number]> {
215 const [roles, count] = await super.listAndCountRbacRoles(
216 filters,
217 config as any,
218 sharedContext
219 )
220
221 const shouldIncludePolicies =
222 config.relations?.includes("policies") ||
223 config.select?.includes("policies")
224
225 if (shouldIncludePolicies && roles.length > 0) {
226 const roleIds = roles.map((role) => role.id)
227 const policiesByRole = await this.rbacRepository_.listPoliciesForRoles(
228 roleIds,
229 sharedContext
230 )
231
232 for (const role of roles) {
233 role.policies = policiesByRole.get(role.id) || []
234 }
235 }
236
237 return [roles as unknown as RbacRoleDTO[], count]
238 }
239
240 @InjectManager()
241 // @ts-expect-error
242 async createRbacRoleParents(
243 data: CreateRbacRoleParentDTO[],
244 @MedusaContext() sharedContext: Context = {}
245 ): Promise<RbacRoleParentDTO[]> {
246 for (const parent of data) {
247 const { role_id, parent_id } = parent
248
249 if (role_id === parent_id) {
250 throw new Error(
251 `Cannot create role parent relationship: a role cannot be its own parent (role_id: ${role_id})`
252 )
253 }
254
255 const wouldCreateCycle = await this.rbacRepository_.checkForCycle(
256 role_id,
257 parent_id,
258 sharedContext
259 )
260
261 if (wouldCreateCycle) {
262 throw new Error(
263 `Cannot create role parent relationship: this would create a circular dependency (role_id: ${role_id}, parent_id: ${parent_id})`
264 )
265 }
266 }
267
268 return await super.createRbacRoleParents(data, sharedContext)
269 }
270
271 @InjectManager()
272 // @ts-expect-error
273 async updateRbacRoleParents(
274 data: UpdateRbacRoleParentDTO[],
275 @MedusaContext() sharedContext: Context = {}
276 ): Promise<RbacRoleParentDTO[]> {
277 for (const parent of data) {
278 const { role_id, parent_id } = parent
279
280 if (parent_id) {
281 if (role_id === parent_id) {
282 throw new Error(
283 `Cannot update role parent relationship: a role cannot be its own parent (role_id: ${role_id})`
284 )
285 }
286
287 const wouldCreateCycle = await this.rbacRepository_.checkForCycle(
288 role_id!,
289 parent_id,
290 sharedContext
291 )
292
293 if (wouldCreateCycle) {
294 throw new Error(
295 `Cannot update role parent relationship: this would create a circular dependency (role_id: ${role_id}, parent_id: ${parent_id})`
296 )
297 }
298 }
299 }
300
301 return await super.updateRbacRoleParents(data, sharedContext)
302 }
303 }