BUG FIX && 权限验证
This commit is contained in:
@@ -170,6 +170,9 @@ Seed 脚本已覆盖班级相关数据,以便在开发环境快速验证页面
|
|||||||
- Next dev 锁文件:出现 `.next/dev/lock` 无法获取锁时,需要确保只有一个 dev 实例在运行,并清理残留 lock。
|
- Next dev 锁文件:出现 `.next/dev/lock` 无法获取锁时,需要确保只有一个 dev 实例在运行,并清理残留 lock。
|
||||||
- 头像资源 404:移除 Header 中硬编码的本地头像资源引用,避免 `public/avatars/...` 不存在导致的 404 噪音(见 `src/modules/layout/components/site-header.tsx`)。
|
- 头像资源 404:移除 Header 中硬编码的本地头像资源引用,避免 `public/avatars/...` 不存在导致的 404 噪音(见 `src/modules/layout/components/site-header.tsx`)。
|
||||||
- 班级人数统计查询失败:`class_enrollments` 表实际列名为 `class_enrollment_status`,修复查询中引用的列名以恢复教师端班级列表渲染。
|
- 班级人数统计查询失败:`class_enrollments` 表实际列名为 `class_enrollment_status`,修复查询中引用的列名以恢复教师端班级列表渲染。
|
||||||
|
- Students 页面 key 冲突:学生列表跨班级汇总时,`<TableRow key={studentId}>` 会重复,改为使用 `classId:studentId` 作为 key。
|
||||||
|
- Build 预渲染失败(/login):`LoginForm` 使用 `useSearchParams()` 获取回跳地址,需在 `/login` 页面用 `Suspense` 包裹以避免 CSR bailout 报错。
|
||||||
|
- 构建警告(middleware):Next.js 16 将文件约定从 `middleware.ts` 改为 `proxy.ts`,已迁移以消除警告。
|
||||||
|
|
||||||
### 6.6 班级详情页(聚合视图 + Schedule Builder + Homework 统计)
|
### 6.6 班级详情页(聚合视图 + Schedule Builder + Homework 统计)
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,10 @@
|
|||||||
import { Metadata } from "next"
|
import { Metadata } from "next"
|
||||||
|
import { createId } from "@paralleldrive/cuid2"
|
||||||
|
import { eq } from "drizzle-orm"
|
||||||
|
|
||||||
|
import { db } from "@/shared/db"
|
||||||
|
import { users } from "@/shared/db/schema"
|
||||||
|
import type { ActionState } from "@/shared/types/action-state"
|
||||||
import { RegisterForm } from "@/modules/auth/components/register-form"
|
import { RegisterForm } from "@/modules/auth/components/register-form"
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
@@ -7,5 +13,33 @@ export const metadata: Metadata = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function RegisterPage() {
|
export default function RegisterPage() {
|
||||||
return <RegisterForm />
|
async function registerAction(formData: FormData): Promise<ActionState> {
|
||||||
|
"use server"
|
||||||
|
|
||||||
|
const name = String(formData.get("name") ?? "").trim()
|
||||||
|
const email = String(formData.get("email") ?? "").trim().toLowerCase()
|
||||||
|
const password = String(formData.get("password") ?? "")
|
||||||
|
|
||||||
|
if (!email) return { success: false, message: "Email is required" }
|
||||||
|
if (!password) return { success: false, message: "Password is required" }
|
||||||
|
if (password.length < 6) return { success: false, message: "Password must be at least 6 characters" }
|
||||||
|
|
||||||
|
const existing = await db.query.users.findFirst({
|
||||||
|
where: eq(users.email, email),
|
||||||
|
columns: { id: true },
|
||||||
|
})
|
||||||
|
if (existing) return { success: false, message: "Email already registered" }
|
||||||
|
|
||||||
|
await db.insert(users).values({
|
||||||
|
id: createId(),
|
||||||
|
name: name.length ? name : null,
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
role: "student",
|
||||||
|
})
|
||||||
|
|
||||||
|
return { success: true, message: "Account created" }
|
||||||
|
}
|
||||||
|
|
||||||
|
return <RegisterForm registerAction={registerAction} />
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
|
import { eq } from "drizzle-orm"
|
||||||
import { getTeacherClasses } from "@/modules/classes/data-access"
|
import { getTeacherClasses } from "@/modules/classes/data-access"
|
||||||
import { MyClassesGrid } from "@/modules/classes/components/my-classes-grid"
|
import { MyClassesGrid } from "@/modules/classes/components/my-classes-grid"
|
||||||
|
import { auth } from "@/auth"
|
||||||
|
import { db } from "@/shared/db"
|
||||||
|
import { grades } from "@/shared/db/schema"
|
||||||
|
|
||||||
export const dynamic = "force-dynamic"
|
export const dynamic = "force-dynamic"
|
||||||
|
|
||||||
@@ -9,6 +13,16 @@ export default function MyClassesPage() {
|
|||||||
|
|
||||||
async function MyClassesPageImpl() {
|
async function MyClassesPageImpl() {
|
||||||
const classes = await getTeacherClasses()
|
const classes = await getTeacherClasses()
|
||||||
|
const session = await auth()
|
||||||
|
const role = String(session?.user?.role ?? "")
|
||||||
|
const userId = String(session?.user?.id ?? "").trim()
|
||||||
|
|
||||||
|
const canCreateClass = await (async () => {
|
||||||
|
if (role === "admin") return true
|
||||||
|
if (!userId) return false
|
||||||
|
const [row] = await db.select({ id: grades.id }).from(grades).where(eq(grades.gradeHeadId, userId)).limit(1)
|
||||||
|
return Boolean(row)
|
||||||
|
})()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-full flex-col space-y-8 p-8">
|
<div className="flex h-full flex-col space-y-8 p-8">
|
||||||
@@ -21,7 +35,7 @@ async function MyClassesPageImpl() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<MyClassesGrid classes={classes} />
|
<MyClassesGrid classes={classes} canCreateClass={canCreateClass} />
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import NextAuth from "next-auth"
|
|||||||
import Credentials from "next-auth/providers/credentials"
|
import Credentials from "next-auth/providers/credentials"
|
||||||
|
|
||||||
export const { handlers, auth, signIn, signOut } = NextAuth({
|
export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||||
|
trustHost: true,
|
||||||
|
secret: process.env.NEXTAUTH_SECRET,
|
||||||
session: { strategy: "jwt" },
|
session: { strategy: "jwt" },
|
||||||
pages: { signIn: "/login" },
|
pages: { signIn: "/login" },
|
||||||
providers: [
|
providers: [
|
||||||
|
|||||||
@@ -2,24 +2,44 @@
|
|||||||
|
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
import Link from "next/link"
|
import Link from "next/link"
|
||||||
|
import { useRouter } from "next/navigation"
|
||||||
|
import { toast } from "sonner"
|
||||||
import { Button } from "@/shared/components/ui/button"
|
import { Button } from "@/shared/components/ui/button"
|
||||||
import { Input } from "@/shared/components/ui/input"
|
import { Input } from "@/shared/components/ui/input"
|
||||||
import { Label } from "@/shared/components/ui/label"
|
import { Label } from "@/shared/components/ui/label"
|
||||||
import { cn } from "@/shared/lib/utils"
|
import { cn } from "@/shared/lib/utils"
|
||||||
import { Loader2, Github } from "lucide-react"
|
import { Loader2, Github } from "lucide-react"
|
||||||
|
import type { ActionState } from "@/shared/types/action-state"
|
||||||
|
|
||||||
type RegisterFormProps = React.HTMLAttributes<HTMLDivElement>
|
type RegisterFormProps = React.HTMLAttributes<HTMLDivElement> & {
|
||||||
|
registerAction: (formData: FormData) => Promise<ActionState>
|
||||||
|
}
|
||||||
|
|
||||||
export function RegisterForm({ className, ...props }: RegisterFormProps) {
|
export function RegisterForm({ className, registerAction, ...props }: RegisterFormProps) {
|
||||||
const [isLoading, setIsLoading] = React.useState<boolean>(false)
|
const [isLoading, setIsLoading] = React.useState<boolean>(false)
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
async function onSubmit(event: React.SyntheticEvent) {
|
async function onSubmit(event: React.SyntheticEvent) {
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
setIsLoading(true)
|
setIsLoading(true)
|
||||||
|
|
||||||
setTimeout(() => {
|
try {
|
||||||
|
const form = event.currentTarget as HTMLFormElement
|
||||||
|
const formData = new FormData(form)
|
||||||
|
const res = await registerAction(formData)
|
||||||
|
|
||||||
|
if (res.success) {
|
||||||
|
toast.success(res.message || "Account created")
|
||||||
|
router.push("/login")
|
||||||
|
router.refresh()
|
||||||
|
} else {
|
||||||
|
toast.error(res.message || "Failed to create account")
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
toast.error("Failed to create account")
|
||||||
|
} finally {
|
||||||
setIsLoading(false)
|
setIsLoading(false)
|
||||||
}, 3000)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -38,6 +58,7 @@ export function RegisterForm({ className, ...props }: RegisterFormProps) {
|
|||||||
<Label htmlFor="name">Full Name</Label>
|
<Label htmlFor="name">Full Name</Label>
|
||||||
<Input
|
<Input
|
||||||
id="name"
|
id="name"
|
||||||
|
name="name"
|
||||||
placeholder="John Doe"
|
placeholder="John Doe"
|
||||||
type="text"
|
type="text"
|
||||||
autoCapitalize="words"
|
autoCapitalize="words"
|
||||||
@@ -50,6 +71,7 @@ export function RegisterForm({ className, ...props }: RegisterFormProps) {
|
|||||||
<Label htmlFor="email">Email</Label>
|
<Label htmlFor="email">Email</Label>
|
||||||
<Input
|
<Input
|
||||||
id="email"
|
id="email"
|
||||||
|
name="email"
|
||||||
placeholder="name@example.com"
|
placeholder="name@example.com"
|
||||||
type="email"
|
type="email"
|
||||||
autoCapitalize="none"
|
autoCapitalize="none"
|
||||||
@@ -62,6 +84,7 @@ export function RegisterForm({ className, ...props }: RegisterFormProps) {
|
|||||||
<Label htmlFor="password">Password</Label>
|
<Label htmlFor="password">Password</Label>
|
||||||
<Input
|
<Input
|
||||||
id="password"
|
id="password"
|
||||||
|
name="password"
|
||||||
type="password"
|
type="password"
|
||||||
autoComplete="new-password"
|
autoComplete="new-password"
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
"use server";
|
"use server";
|
||||||
|
|
||||||
import { revalidatePath } from "next/cache"
|
import { revalidatePath } from "next/cache"
|
||||||
|
import { and, eq, sql } from "drizzle-orm"
|
||||||
import { auth } from "@/auth"
|
import { auth } from "@/auth"
|
||||||
|
|
||||||
|
import { db } from "@/shared/db"
|
||||||
|
import { grades } from "@/shared/db/schema"
|
||||||
import type { ActionState } from "@/shared/types/action-state"
|
import type { ActionState } from "@/shared/types/action-state"
|
||||||
import {
|
import {
|
||||||
createAdminClass,
|
createAdminClass,
|
||||||
@@ -44,6 +47,26 @@ export async function createTeacherClassAction(
|
|||||||
return { success: false, message: "Grade is required" }
|
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 {
|
try {
|
||||||
const id = await createTeacherClass({
|
const id = await createTeacherClass({
|
||||||
schoolName: typeof schoolName === "string" ? schoolName : null,
|
schoolName: typeof schoolName === "string" ? schoolName : null,
|
||||||
@@ -311,6 +334,11 @@ export async function createAdminClassAction(
|
|||||||
prevState: ActionState<string> | undefined,
|
prevState: ActionState<string> | undefined,
|
||||||
formData: FormData
|
formData: FormData
|
||||||
): Promise<ActionState<string>> {
|
): 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 schoolName = formData.get("schoolName")
|
||||||
const schoolId = formData.get("schoolId")
|
const schoolId = formData.get("schoolId")
|
||||||
const name = formData.get("name")
|
const name = formData.get("name")
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ import {
|
|||||||
updateTeacherClassAction,
|
updateTeacherClassAction,
|
||||||
} from "../actions"
|
} from "../actions"
|
||||||
|
|
||||||
export function MyClassesGrid({ classes }: { classes: TeacherClass[] }) {
|
export function MyClassesGrid({ classes, canCreateClass }: { classes: TeacherClass[]; canCreateClass: boolean }) {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const [isWorking, setIsWorking] = useState(false)
|
const [isWorking, setIsWorking] = useState(false)
|
||||||
const [createOpen, setCreateOpen] = useState(false)
|
const [createOpen, setCreateOpen] = useState(false)
|
||||||
@@ -133,12 +133,13 @@ export function MyClassesGrid({ classes }: { classes: TeacherClass[] }) {
|
|||||||
<Dialog
|
<Dialog
|
||||||
open={createOpen}
|
open={createOpen}
|
||||||
onOpenChange={(open) => {
|
onOpenChange={(open) => {
|
||||||
|
if (!canCreateClass) return
|
||||||
if (isWorking) return
|
if (isWorking) return
|
||||||
setCreateOpen(open)
|
setCreateOpen(open)
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<DialogTrigger asChild>
|
<DialogTrigger asChild>
|
||||||
<Button className="gap-2" disabled={isWorking}>
|
<Button className="gap-2" disabled={isWorking || !canCreateClass}>
|
||||||
<Plus className="size-4" />
|
<Plus className="size-4" />
|
||||||
New class
|
New class
|
||||||
</Button>
|
</Button>
|
||||||
@@ -209,7 +210,7 @@ export function MyClassesGrid({ classes }: { classes: TeacherClass[] }) {
|
|||||||
title="No classes yet"
|
title="No classes yet"
|
||||||
description="Create your first class to start managing students and schedules."
|
description="Create your first class to start managing students and schedules."
|
||||||
icon={Users}
|
icon={Users}
|
||||||
action={{ label: "Create class", onClick: () => setCreateOpen(true) }}
|
action={canCreateClass ? { label: "Create class", onClick: () => setCreateOpen(true) } : undefined}
|
||||||
className="h-[360px] bg-card sm:col-span-2 lg:col-span-3"
|
className="h-[360px] bg-card sm:col-span-2 lg:col-span-3"
|
||||||
/>
|
/>
|
||||||
) : filteredClasses.length === 0 ? (
|
) : filteredClasses.length === 0 ? (
|
||||||
|
|||||||
Reference in New Issue
Block a user