59 lines
1.7 KiB
TypeScript
Executable File
59 lines
1.7 KiB
TypeScript
Executable File
import Admins from '#base_modules/Admin/model/admin'
|
|
import { readdirSync, existsSync } from 'node:fs'
|
|
import { join } from 'node:path'
|
|
import { pathToFileURL } from 'node:url'
|
|
import db from '@adonisjs/lucid/services/db'
|
|
|
|
interface PermissionItem {
|
|
slug: string
|
|
name: string
|
|
}
|
|
|
|
export async function getAdminPermissionSlugs(admin: Admins): Promise<Set<string>> {
|
|
await admin.load('roles')
|
|
const roles = admin.roles.map((role) => role.id)
|
|
const permissions = await db
|
|
.from('role_permissions')
|
|
.whereIn('role_id', roles)
|
|
.select('permission_slug')
|
|
|
|
const slugs = new Set<string>()
|
|
permissions.map((perm) => slugs.add(perm.permission_slug))
|
|
return slugs
|
|
}
|
|
|
|
export async function getAllPermissions(): Promise<PermissionItem[]> {
|
|
const appRoot = process.cwd()
|
|
const baseModulesPath = join(appRoot, 'app', 'base_modules')
|
|
const modulesPath = join(appRoot, 'modules')
|
|
|
|
const result: PermissionItem[] = []
|
|
|
|
const loadPermissionsFromDir = async (dir: string) => {
|
|
if (!existsSync(dir)) return
|
|
|
|
const modules = readdirSync(dir, { withFileTypes: true })
|
|
.filter((d) => d.isDirectory())
|
|
.map((d) => d.name)
|
|
|
|
for (const moduleName of modules) {
|
|
const configPath = join(dir, moduleName, 'config', 'permissions.ts')
|
|
if (existsSync(configPath)) {
|
|
try {
|
|
const fileUrl = pathToFileURL(configPath)
|
|
const mod = await import(fileUrl.href)
|
|
const perms = mod.default || []
|
|
if (Array.isArray(perms)) result.push(...perms)
|
|
} catch (err) {
|
|
console.error(`Failed to load permissions for module "${moduleName}":`, err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
await loadPermissionsFromDir(baseModulesPath)
|
|
await loadPermissionsFromDir(modulesPath)
|
|
|
|
return result
|
|
}
|