mirror of
https://github.com/beilunyang/moemail.git
synced 2026-05-07 05:32:49 +08:00
feat: Enhance role management by adding role assignment functionality and checks for existing roles
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { auth, assignRoleToUser } from "@/lib/auth";
|
||||
import { createDb } from "@/lib/db";
|
||||
import { roles, userRoles } from "@/lib/schema";
|
||||
import { ROLES } from "@/lib/permissions";
|
||||
@@ -26,6 +26,17 @@ export async function GET() {
|
||||
}
|
||||
|
||||
try {
|
||||
const currentUserRole = await db.query.userRoles.findFirst({
|
||||
where: eq(userRoles.userId, session.user.id),
|
||||
with: {
|
||||
role: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (currentUserRole?.role.name === ROLES.EMPEROR) {
|
||||
return Response.json({ message: "你已经是皇帝了" });
|
||||
}
|
||||
|
||||
let roleId = emperorRole?.id;
|
||||
if (!roleId) {
|
||||
const [newRole] = await db.insert(roles)
|
||||
@@ -37,11 +48,7 @@ export async function GET() {
|
||||
roleId = newRole.id;
|
||||
}
|
||||
|
||||
await db.insert(userRoles)
|
||||
.values({
|
||||
userId: session.user.id,
|
||||
roleId,
|
||||
});
|
||||
await assignRoleToUser(db, session.user.id, roleId);
|
||||
|
||||
return Response.json({ message: "登基成功,你已成为皇帝" });
|
||||
} catch (error) {
|
||||
|
||||
@@ -17,13 +17,27 @@ export async function POST(request: Request) {
|
||||
|
||||
if (roleName !== ROLES.KNIGHT) {
|
||||
return Response.json(
|
||||
{ error: "角色不合法" },
|
||||
{ error: "只能册封骑士" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const db = createDb();
|
||||
|
||||
const isEmperor = await db.query.userRoles.findFirst({
|
||||
where: eq(userRoles.userId, userId),
|
||||
with: {
|
||||
role: true,
|
||||
},
|
||||
}).then(userRole => userRole?.role.name === ROLES.EMPEROR);
|
||||
|
||||
if (isEmperor) {
|
||||
return Response.json(
|
||||
{ error: "不能降级皇帝" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
let targetRole = await db.query.roles.findFirst({
|
||||
where: eq(roles.name, roleName),
|
||||
});
|
||||
|
||||
@@ -36,7 +36,10 @@ async function findOrCreateRole(db: Db, roleName: Role) {
|
||||
return role
|
||||
}
|
||||
|
||||
async function assignRoleToUser(db: Db, userId: string, roleId: string) {
|
||||
export async function assignRoleToUser(db: Db, userId: string, roleId: string) {
|
||||
await db.delete(userRoles)
|
||||
.where(eq(userRoles.userId, userId))
|
||||
|
||||
await db.insert(userRoles)
|
||||
.values({
|
||||
userId,
|
||||
|
||||
Reference in New Issue
Block a user