assets-ai/src/app/api/roles/[id]/route.ts

58 lines
2.2 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import db from '@/lib/db'
import { getSession } from '@/lib/auth'
import { checkPermission } from '@/lib/permissions'
import { initDatabase } from '@/lib/db-schema'
const BUILTIN_ROLES = ['admin', 'editor', 'viewer']
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
initDatabase()
const session = await getSession()
if (!session) return NextResponse.json({ error: '未登录' }, { status: 401 })
if (!checkPermission(session.role, 'roles:write')) return NextResponse.json({ error: '权限不足' }, { status: 403 })
const { id } = await params
const body = await request.json()
const existing = db.prepare('SELECT * FROM roles WHERE id = ?').get(id) as Record<string, unknown> | undefined
if (!existing) return NextResponse.json({ error: '角色不存在' }, { status: 404 })
const fields: string[] = []
const values: unknown[] = []
if (body.display_name) { fields.push('display_name = ?'); values.push(body.display_name) }
if (body.permissions) { fields.push('permissions = ?'); values.push(JSON.stringify(body.permissions)) }
if (fields.length > 0) {
values.push(id)
db.prepare(`UPDATE roles SET ${fields.join(', ')} WHERE id = ?`).run(...values)
}
const role = db.prepare('SELECT * FROM roles WHERE id = ?').get(id)
return NextResponse.json({ role })
}
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
initDatabase()
const session = await getSession()
if (!session) return NextResponse.json({ error: '未登录' }, { status: 401 })
if (!checkPermission(session.role, 'roles:write')) return NextResponse.json({ error: '权限不足' }, { status: 403 })
const { id } = await params
const existing = db.prepare('SELECT * FROM roles WHERE id = ?').get(id) as Record<string, unknown> | undefined
if (!existing) return NextResponse.json({ error: '角色不存在' }, { status: 404 })
if (BUILTIN_ROLES.includes(existing.name as string)) {
return NextResponse.json({ error: '系统内置角色不能删除' }, { status: 400 })
}
db.prepare('DELETE FROM roles WHERE id = ?').run(id)
return NextResponse.json({ success: true })
}