mirror of
https://github.com/beilunyang/moemail.git
synced 2025-09-26 19:41:22 +08:00
refactor: support demotion and improve error handling in role management
This commit is contained in:
@@ -2,12 +2,16 @@ import { createDb } from "@/lib/db";
|
||||
import { roles, userRoles } from "@/lib/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { ROLES } from "@/lib/permissions";
|
||||
import { assignRoleToUser } from "@/lib/auth";
|
||||
|
||||
export const runtime = "edge";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const { userId, roleName } = await request.json() as { userId: string, roleName: string };
|
||||
const { userId, roleName } = await request.json() as {
|
||||
userId: string,
|
||||
roleName: typeof ROLES.KNIGHT | typeof ROLES.CIVILIAN
|
||||
};
|
||||
if (!userId || !roleName) {
|
||||
return Response.json(
|
||||
{ error: "缺少必要参数" },
|
||||
@@ -15,23 +19,23 @@ export async function POST(request: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
if (roleName !== ROLES.KNIGHT) {
|
||||
if (![ROLES.KNIGHT, ROLES.CIVILIAN].includes(roleName)) {
|
||||
return Response.json(
|
||||
{ error: "只能册封骑士" },
|
||||
{ error: "角色不合法" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const db = createDb();
|
||||
|
||||
const isEmperor = await db.query.userRoles.findFirst({
|
||||
const currentUserRole = await db.query.userRoles.findFirst({
|
||||
where: eq(userRoles.userId, userId),
|
||||
with: {
|
||||
role: true,
|
||||
},
|
||||
}).then(userRole => userRole?.role.name === ROLES.EMPEROR);
|
||||
});
|
||||
|
||||
if (isEmperor) {
|
||||
if (currentUserRole?.role.name === ROLES.EMPEROR) {
|
||||
return Response.json(
|
||||
{ error: "不能降级皇帝" },
|
||||
{ status: 400 }
|
||||
@@ -43,29 +47,29 @@ export async function POST(request: Request) {
|
||||
});
|
||||
|
||||
if (!targetRole) {
|
||||
const description = roleName === ROLES.KNIGHT
|
||||
? "高级用户"
|
||||
: "普通用户";
|
||||
|
||||
const [newRole] = await db.insert(roles)
|
||||
.values({
|
||||
name: roleName,
|
||||
description: "高级用户",
|
||||
description,
|
||||
})
|
||||
.returning();
|
||||
targetRole = newRole;
|
||||
}
|
||||
|
||||
await db.delete(userRoles)
|
||||
.where(eq(userRoles.userId, userId));
|
||||
await assignRoleToUser(db, userId, targetRole.id);
|
||||
|
||||
await db.insert(userRoles)
|
||||
.values({
|
||||
userId,
|
||||
roleId: targetRole.id,
|
||||
});
|
||||
|
||||
return Response.json({ success: true });
|
||||
return Response.json({
|
||||
success: true,
|
||||
message: roleName === ROLES.KNIGHT ? "册封成功" : "贬为平民"
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to promote user:", error);
|
||||
console.error("Failed to change user role:", error);
|
||||
return Response.json(
|
||||
{ error: "升级用户失败" },
|
||||
{ error: "操作失败" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
@@ -1,25 +1,25 @@
|
||||
"use client"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Sword, Search, Loader2 } from "lucide-react"
|
||||
import { Sword, Loader2, UserMinus } from "lucide-react"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { useState } from "react"
|
||||
import { useToast } from "@/components/ui/use-toast"
|
||||
import { ROLES } from "@/lib/permissions"
|
||||
|
||||
|
||||
export function PromotePanel() {
|
||||
const [email, setEmail] = useState("")
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [action, setAction] = useState<"promote" | "demote">("promote")
|
||||
const { toast } = useToast()
|
||||
|
||||
const handlePromote = async () => {
|
||||
const handleAction = async () => {
|
||||
if (!email) return
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await fetch(`/api/roles/users?email=${encodeURIComponent(email)}`)
|
||||
const data = await res.json() as { user?: { id: string; name?: string; email: string }; error?: string }
|
||||
const data = await res.json() as { user?: { id: string; name?: string; email: string; role?: string }; error?: string }
|
||||
|
||||
if (!res.ok) throw new Error(data.error || '未知错误')
|
||||
if (!data.user) {
|
||||
@@ -31,26 +31,43 @@ export function PromotePanel() {
|
||||
return
|
||||
}
|
||||
|
||||
if (action === "promote" && data.user.role === ROLES.KNIGHT) {
|
||||
toast({
|
||||
title: "用户已是骑士",
|
||||
description: "无需重复册封",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (action === "demote" && data.user.role === ROLES.CIVILIAN) {
|
||||
toast({
|
||||
title: "用户已是平民",
|
||||
description: "无需重复贬为平民",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const promoteRes = await fetch('/api/roles/promote', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
userId: data.user.id,
|
||||
roleName: ROLES.KNIGHT
|
||||
roleName: action === "promote" ? ROLES.KNIGHT : ROLES.CIVILIAN
|
||||
})
|
||||
})
|
||||
|
||||
if (!promoteRes.ok) throw new Error('册封失败')
|
||||
const result = await promoteRes.json() as { error: string }
|
||||
if (!promoteRes.ok) throw new Error(result.error)
|
||||
|
||||
toast({
|
||||
title: "册封成功",
|
||||
description: `已将 ${data.user.email} 册封为骑士`
|
||||
title: action === "promote" ? "册封成功" : "贬为平民",
|
||||
description: `已将 ${data.user.email} ${action === "promote" ? "册封为骑士" : "贬为平民"}`
|
||||
})
|
||||
setEmail("")
|
||||
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "册封失败",
|
||||
title: "操作失败",
|
||||
description: error instanceof Error ? error.message : "请稍后重试",
|
||||
variant: "destructive"
|
||||
})
|
||||
@@ -63,10 +80,10 @@ export function PromotePanel() {
|
||||
<div className="bg-background rounded-lg border-2 border-primary/20 p-6">
|
||||
<div className="flex items-center gap-2 mb-6">
|
||||
<Sword className="w-5 h-5 text-primary" />
|
||||
<h2 className="text-lg font-semibold">册封骑士</h2>
|
||||
<h2 className="text-lg font-semibold">角色管理</h2>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
<div className="flex-1">
|
||||
<Input
|
||||
placeholder="输入用户邮箱"
|
||||
@@ -75,18 +92,39 @@ export function PromotePanel() {
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handlePromote}
|
||||
disabled={!email || loading}
|
||||
className="gap-2"
|
||||
>
|
||||
{loading ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<Search className="w-4 h-4" />
|
||||
)}
|
||||
{loading ? "册封中..." : "册封"}
|
||||
</Button>
|
||||
<div className="flex gap-2 sm:flex-shrink-0">
|
||||
<Button
|
||||
onClick={() => {
|
||||
setAction("promote")
|
||||
handleAction()
|
||||
}}
|
||||
disabled={!email || loading}
|
||||
className="flex-1 sm:flex-initial gap-2"
|
||||
>
|
||||
{loading && action === "promote" ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<Sword className="w-4 h-4" />
|
||||
)}
|
||||
册封骑士
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setAction("demote")
|
||||
handleAction()
|
||||
}}
|
||||
disabled={!email || loading}
|
||||
variant="destructive"
|
||||
className="flex-1 sm:flex-initial gap-2"
|
||||
>
|
||||
{loading && action === "demote" ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<UserMinus className="w-4 h-4" />
|
||||
)}
|
||||
贬为平民
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
@@ -13,13 +13,11 @@ export default async function ProfilePage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-gradient-to-b from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 h-screen">
|
||||
<div className="container mx-auto h-full px-4 lg:px-8 max-w-[1600px]">
|
||||
<div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800">
|
||||
<div className="container mx-auto px-4 lg:px-8 max-w-[1600px]">
|
||||
<Header />
|
||||
<main className="h-full">
|
||||
<div className="pt-20 pb-5 h-full">
|
||||
<ProfileCard user={session.user} />
|
||||
</div>
|
||||
<main className="pt-20 pb-5">
|
||||
<ProfileCard user={session.user} />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
|
Reference in New Issue
Block a user