67 lines
2.1 KiB
TypeScript
67 lines
2.1 KiB
TypeScript
|
|
#!/usr/bin/env ts-node
|
||
|
|
import * as fs from 'fs'
|
||
|
|
import * as path from 'path'
|
||
|
|
import { prisma } from '../src/lib/prisma'
|
||
|
|
|
||
|
|
function findModules(dir: string): string[] {
|
||
|
|
const results: string[] = []
|
||
|
|
const entries = fs.readdirSync(dir, { withFileTypes: true })
|
||
|
|
for (const e of entries) {
|
||
|
|
const full = path.join(dir, e.name)
|
||
|
|
if (e.isDirectory()) {
|
||
|
|
results.push(...findModules(full))
|
||
|
|
} else if (e.isFile() && e.name.endsWith('.module.ts')) {
|
||
|
|
results.push(full)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return results
|
||
|
|
}
|
||
|
|
|
||
|
|
function moduleNameFromFile(filePath: string) {
|
||
|
|
const name = path.basename(filePath).replace('.module.ts', '')
|
||
|
|
return name.replace(/-module$|\.module$/i, '')
|
||
|
|
}
|
||
|
|
|
||
|
|
function makePermissionsFor(moduleName: string) {
|
||
|
|
const base = moduleName.replace(/\W+/g, '_').toLowerCase()
|
||
|
|
return [`${base}:create`, `${base}:read`, `${base}:update`, `${base}:delete`]
|
||
|
|
}
|
||
|
|
|
||
|
|
async function main() {
|
||
|
|
const srcDir = path.resolve(__dirname, '..', 'src')
|
||
|
|
const moduleFiles = findModules(srcDir)
|
||
|
|
const modules = moduleFiles.map(moduleNameFromFile)
|
||
|
|
|
||
|
|
const permsMap: Record<string, boolean> = {}
|
||
|
|
for (const m of modules) {
|
||
|
|
for (const p of makePermissionsFor(m)) permsMap[p] = false
|
||
|
|
}
|
||
|
|
|
||
|
|
// Upsert roles: ensure admin has full permissions, others get entries added
|
||
|
|
const roles = await prisma.role.findMany()
|
||
|
|
for (const r of roles) {
|
||
|
|
const current: Record<string, any> = (r.permissions as any) || {}
|
||
|
|
const merged = { ...permsMap, ...current }
|
||
|
|
|
||
|
|
// If role name is admin (case-insensitive), set all permissions to true
|
||
|
|
if (r.name && r.name.toLowerCase() === 'admin') {
|
||
|
|
for (const key of Object.keys(merged)) merged[key] = true
|
||
|
|
} else {
|
||
|
|
// keep existing truthy values, otherwise false
|
||
|
|
for (const key of Object.keys(merged)) merged[key] = merged[key] || false
|
||
|
|
}
|
||
|
|
|
||
|
|
await prisma.role.update({ where: { id: r.id }, data: { permissions: merged } })
|
||
|
|
console.log(
|
||
|
|
`Updated role ${r.name} (id=${r.id}) with ${Object.keys(merged).length} permissions`,
|
||
|
|
)
|
||
|
|
}
|
||
|
|
|
||
|
|
await prisma.$disconnect()
|
||
|
|
}
|
||
|
|
|
||
|
|
main().catch(e => {
|
||
|
|
console.error(e)
|
||
|
|
process.exit(1)
|
||
|
|
})
|