1 import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"
2 import { Context } from "@medusajs/framework/types"
3 import { MikroOrmBase } from "@medusajs/framework/utils"
4
5 export class RbacRepository extends MikroOrmBase {
6 constructor() {
7 // @ts-ignore
8 // eslint-disable-next-line prefer-rest-params
9 super(...arguments)
10 }
11
12 async listPoliciesForRole(
13 roleId: string,
14 sharedContext: Context = {}
15 ): Promise<any[]> {
16 const policiesByRole = await this.listPoliciesForRoles(
17 [roleId],
18 sharedContext
19 )
20 return policiesByRole.get(roleId) || []
21 }
22
23 async listPoliciesForRoles(
24 roleIds: string[],
25 sharedContext: Context = {}
26 ): Promise<Map<string, any[]>> {
27 const manager = this.getActiveManager<SqlEntityManager>(sharedContext)
28 const knex = manager.getKnex()
29
30 if (!roleIds?.length) {
31 return new Map()
32 }
33
34 const placeholders = roleIds.map(() => "?").join(",")
35
36 const query = `
37 WITH RECURSIVE role_hierarchy AS (
38 SELECT id, name, id as original_role_id, ARRAY[id] as path
39 FROM rbac_role
40 WHERE id IN (${placeholders}) AND deleted_at IS NULL
41
42 UNION ALL
43
44 SELECT r.id, r.name, rh.original_role_id, rh.path || r.id
45 FROM rbac_role r
46 INNER JOIN rbac_role_parent ri ON ri.parent_id = r.id
47 INNER JOIN role_hierarchy rh ON rh.id = ri.role_id
48 WHERE r.deleted_at IS NULL
49 AND ri.deleted_at IS NULL
50 AND NOT (r.id = ANY(rh.path))
51 )
52 SELECT DISTINCT
53 rh.original_role_id,
54 p.id,
55 p.key,
56 p.resource,
57 p.operation,
58 p.name,
59 p.description,
60 p.metadata,
61 p.created_at,
62 p.updated_at,
63 CASE WHEN rp.role_id = rh.original_role_id THEN NULL ELSE rp.role_id END as inherited_from_role_id
64 FROM rbac_policy p
65 INNER JOIN rbac_role_policy rp ON rp.policy_id = p.id
66 INNER JOIN role_hierarchy rh ON rh.id = rp.role_id
67 WHERE p.deleted_at IS NULL AND rp.deleted_at IS NULL
68 ORDER BY rh.original_role_id, p.resource, p.operation, p.key
69 `
70
71 const result = await knex.raw(query, roleIds)
72 const rows = result.rows || []
73
74 // Group policies by role_id
75 const policiesByRole = new Map<string, any[]>()
76
77 for (const row of rows) {
78 const roleId = row.original_role_id
79 delete row.original_role_id
80
81 if (!policiesByRole.has(roleId)) {
82 policiesByRole.set(roleId, [])
83 }
84
85 policiesByRole.get(roleId)!.push(row)
86 }
87
88 return policiesByRole
89 }
90
91 async checkForCycle(
92 roleId: string,
93 parentId: string,
94 sharedContext: Context = {}
95 ): Promise<boolean> {
96 const manager = this.getActiveManager<SqlEntityManager>(sharedContext)
97 const knex = manager.getKnex()
98
99 // Check if adding this parent would create a circular dependency
100 // A cycle exists if role_id is already an ancestor of parent_id
101 // (i.e., if we traverse up from parent_id, we reach role_id)
102 const query = `
103 WITH RECURSIVE role_hierarchy AS (
104 SELECT id, ARRAY[id] as path
105 FROM rbac_role
106 WHERE id = ? AND deleted_at IS NULL
107
108 UNION ALL
109
110 SELECT r.id, rh.path || r.id
111 FROM role_hierarchy rh
112 INNER JOIN rbac_role_parent ri ON ri.role_id = rh.id
113 INNER JOIN rbac_role r ON r.id = ri.parent_id
114 WHERE r.deleted_at IS NULL
115 AND ri.deleted_at IS NULL
116 AND NOT (r.id = ANY(rh.path))
117 )
118 SELECT EXISTS(
119 SELECT 1 FROM role_hierarchy WHERE id = ?
120 ) as has_cycle
121 `
122
123 const result = await knex.raw(query, [parentId, roleId])
124 return result.rows[0]?.has_cycle || false
125 }
126 }