65 lines
2.6 KiB
TypeScript
65 lines
2.6 KiB
TypeScript
// GET/PUT /api/admin/roles — 角色权限管理(admin)
|
||
import { NextRequest, NextResponse } from 'next/server'
|
||
import { verifyJwt } from '@shared/lib/auth/jwt'
|
||
import { authConfig } from '@/lib/auth-config'
|
||
import { dbQuery, dbExec } from '@/lib/db'
|
||
import { writeAuditLog } from '@/lib/audit'
|
||
import { hasPermission, PERMISSIONS } from '@/lib/permissions'
|
||
|
||
export async function GET(request: NextRequest) {
|
||
const token = request.cookies.get('tlyq_session')?.value
|
||
if (!token) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||
const payload = verifyJwt(token, authConfig.jwtSecret)
|
||
if (!payload || !hasPermission(String(payload.role || 'viewer'), 'roles:manage')) {
|
||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||
}
|
||
|
||
// 返回所有权限定义 + 各角色的权限映射
|
||
const rolePermissions = dbQuery<{ role: string; permission_key: string }>('SELECT role, permission_key FROM role_permissions')
|
||
const roles = ['admin', 'editor', 'viewer']
|
||
const permKeys = PERMISSIONS.map(p => p.key)
|
||
|
||
const result = roles.map(role => ({
|
||
role,
|
||
permissions: PERMISSIONS.map(p => ({
|
||
key: p.key,
|
||
enabled: role === 'admin' || rolePermissions.some(rp => rp.role === role && rp.permission_key === p.key),
|
||
})),
|
||
}))
|
||
|
||
return NextResponse.json({ roles: result, allPermissions: permKeys })
|
||
}
|
||
|
||
export async function PUT(request: NextRequest) {
|
||
const token = request.cookies.get('tlyq_session')?.value
|
||
if (!token) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||
const payload = verifyJwt(token, authConfig.jwtSecret)
|
||
if (!payload || !hasPermission(String(payload.role || 'viewer'), 'roles:manage')) {
|
||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||
}
|
||
|
||
const body = await request.json()
|
||
const { role, permissions } = body as { role: string; permissions: string[] }
|
||
|
||
if (!role || !permissions || !Array.isArray(permissions)) {
|
||
return NextResponse.json({ error: '参数错误' }, { status: 400 })
|
||
}
|
||
|
||
// 删除旧权限,写入新权限
|
||
dbExec(`DELETE FROM role_permissions WHERE role = '${role.replace(/'/g, "''")}'`)
|
||
for (const perm of permissions) {
|
||
dbExec(`INSERT OR IGNORE INTO role_permissions (role, permission_key) VALUES ('${role.replace(/'/g, "''")}', '${perm.replace(/'/g, "''")}')`)
|
||
}
|
||
|
||
writeAuditLog({
|
||
userId: Number(payload.sub) || null,
|
||
username: String(payload.username || ''),
|
||
action: 'update_role',
|
||
entityType: 'role',
|
||
details: { role, permissions },
|
||
ipAddress: request.headers.get('x-forwarded-for') || '127.0.0.1',
|
||
})
|
||
|
||
return NextResponse.json({ success: true })
|
||
}
|