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