issue-ai/src/lib/permissions.ts

34 lines
1.2 KiB
TypeScript

import { getDb } from './db'
import type { UserPayload } from './auth'
export function hasPermission(user: UserPayload, permission: string): boolean {
if (user.role === 'admin') return true
const db = getDb()
const role = db.prepare('SELECT permissions FROM roles WHERE name = ?').get(user.role) as { permissions: string } | undefined
if (!role) return false
try {
const perms: string[] = JSON.parse(role.permissions)
return perms.includes('*') || perms.includes(permission)
} catch {
return false
}
}
export function checkPermission(role: string, permission: string): boolean {
if (role === 'admin') return true
const db = getDb()
const roleRow = db.prepare('SELECT permissions FROM roles WHERE name = ?').get(role) as { permissions: string } | undefined
if (!roleRow) return false
try {
const perms: string[] = JSON.parse(roleRow.permissions)
return perms.includes('*') || perms.includes(permission)
} catch {
return false
}
}
export function requirePermission(user: UserPayload | null, permission: string): void {
if (!user) throw new Error('未登录')
if (!hasPermission(user, permission)) throw new Error('权限不足')
}