BUG FIX && 权限验证
This commit is contained in:
@@ -1,8 +1,11 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache"
|
||||
import { and, eq, sql } from "drizzle-orm"
|
||||
import { auth } from "@/auth"
|
||||
|
||||
import { db } from "@/shared/db"
|
||||
import { grades } from "@/shared/db/schema"
|
||||
import type { ActionState } from "@/shared/types/action-state"
|
||||
import {
|
||||
createAdminClass,
|
||||
@@ -44,6 +47,26 @@ export async function createTeacherClassAction(
|
||||
return { success: false, message: "Grade is required" }
|
||||
}
|
||||
|
||||
const session = await auth()
|
||||
if (!session?.user) return { success: false, message: "Unauthorized" }
|
||||
|
||||
const role = String(session.user.role ?? "")
|
||||
if (role !== "admin") {
|
||||
const userId = String(session.user.id ?? "").trim()
|
||||
if (!userId) return { success: false, message: "Unauthorized" }
|
||||
|
||||
const normalizedGradeId = typeof gradeId === "string" ? gradeId.trim() : ""
|
||||
const normalizedGradeName = grade.trim().toLowerCase()
|
||||
const where = normalizedGradeId
|
||||
? and(eq(grades.id, normalizedGradeId), eq(grades.gradeHeadId, userId))
|
||||
: and(eq(grades.gradeHeadId, userId), sql`LOWER(${grades.name}) = ${normalizedGradeName}`)
|
||||
|
||||
const [ownedGrade] = await db.select({ id: grades.id }).from(grades).where(where).limit(1)
|
||||
if (!ownedGrade) {
|
||||
return { success: false, message: "Only admins and grade heads can create classes" }
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const id = await createTeacherClass({
|
||||
schoolName: typeof schoolName === "string" ? schoolName : null,
|
||||
@@ -311,6 +334,11 @@ export async function createAdminClassAction(
|
||||
prevState: ActionState<string> | undefined,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id || String(session.user.role ?? "") !== "admin") {
|
||||
return { success: false, message: "Unauthorized" }
|
||||
}
|
||||
|
||||
const schoolName = formData.get("schoolName")
|
||||
const schoolId = formData.get("schoolId")
|
||||
const name = formData.get("name")
|
||||
|
||||
Reference in New Issue
Block a user