Skip to content

Commit

Permalink
feat: Enhance role management by adding role assignment functionality…
Browse files Browse the repository at this point in the history
… and checks for existing roles
  • Loading branch information
beilunyang committed Dec 28, 2024
1 parent 1183f0d commit fbd65a5
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 8 deletions.
19 changes: 13 additions & 6 deletions app/api/roles/init-emperor/route.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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)
Expand All @@ -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) {
Expand Down
16 changes: 15 additions & 1 deletion app/api/roles/promote/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
});
Expand Down
5 changes: 4 additions & 1 deletion app/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit fbd65a5

Please sign in to comment.