44 lines
1.7 KiB
TypeScript
44 lines
1.7 KiB
TypeScript
// PUT/PATCH /api/admin/users/[id] — 修改用户角色
|
|
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 } from '@/lib/permissions'
|
|
|
|
export async function PUT(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
|
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'), 'users:manage')) {
|
|
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
|
}
|
|
|
|
const { id } = await params
|
|
const body = await request.json()
|
|
const { role, display_name, email } = body
|
|
|
|
const updates: string[] = []
|
|
if (role) updates.push(`role = '${role.replace(/'/g, "''")}'`)
|
|
if (display_name !== undefined) updates.push(`display_name = '${String(display_name).replace(/'/g, "''")}'`)
|
|
if (email !== undefined) updates.push(`email = '${String(email).replace(/'/g, "''")}'`)
|
|
if (updates.length === 0) {
|
|
return NextResponse.json({ error: '无可更新字段' }, { status: 400 })
|
|
}
|
|
updates.push(`updated_at = datetime('now', '+8 hours')`)
|
|
|
|
dbExec(`UPDATE users SET ${updates.join(', ')} WHERE id = ${Number(id)}`)
|
|
|
|
writeAuditLog({
|
|
userId: Number(payload.sub) || null,
|
|
username: String(payload.username || ''),
|
|
action: 'update_user',
|
|
entityType: 'user',
|
|
entityId: Number(id),
|
|
details: body,
|
|
ipAddress: request.headers.get('x-forwarded-for') || '127.0.0.1',
|
|
})
|
|
|
|
return NextResponse.json({ success: true })
|
|
}
|