89 lines
2.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 设置用户角色API
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { isSystemAdmin } from '@/lib/department-permission';
// POST - 设置用户角色(仅系统管理员)
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user || !(session.user as any).id) {
return NextResponse.json(
{ error: '未登录' },
{ status: 401 }
);
}
// 使用兼容性检查:ADMIN 和 SYSTEM_ADMIN 都可以
const userRole = (session.user as any).role;
if (!isSystemAdmin(userRole)) {
return NextResponse.json(
{ error: '权限不足' },
{ status: 403 }
);
}
const { userId, role } = await request.json();
if (!userId || !role) {
return NextResponse.json(
{ error: '参数错误' },
{ status: 400 }
);
}
// 支持所有角色:USER, ADMIN(兼容), DEPT_ADMIN, SYSTEM_ADMIN
const validRoles = ['USER', 'ADMIN', 'DEPT_ADMIN', 'SYSTEM_ADMIN'];
if (!validRoles.includes(role)) {
return NextResponse.json(
{ error: '角色值无效,支持的角色:' + validRoles.join(', ') },
{ status: 400 }
);
}
// 检查用户是否存在
const user = await prisma.user.findUnique({
where: { id: userId },
});
if (!user) {
return NextResponse.json(
{ error: '用户不存在' },
{ status: 404 }
);
}
// 不能修改自己的角色
const sessionUserEmail = (session.user as any).email;
if (user.email === sessionUserEmail) {
return NextResponse.json(
{ error: '不能修改自己的角色' },
{ status: 400 }
);
}
// 更新角色
const updatedUser = await prisma.user.update({
where: { id: userId },
data: { role },
});
return NextResponse.json({
success: true,
user: {
id: updatedUser.id,
email: updatedUser.email,
username: updatedUser.username,
role: updatedUser.role,
},
});
} catch (error) {
console.error('Error updating user role:', error);
return NextResponse.json(
{ error: '设置角色失败' },
{ status: 500 }
);
}
}