feat: 首次登录引导与注册修复
This commit is contained in:
@@ -2,8 +2,6 @@ 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"
|
||||
|
||||
@@ -16,29 +14,100 @@ export default function RegisterPage() {
|
||||
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") ?? "")
|
||||
const databaseUrl = process.env.DATABASE_URL
|
||||
if (!databaseUrl) return { success: false, message: "DATABASE_URL 未配置" }
|
||||
|
||||
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" }
|
||||
try {
|
||||
const [{ db }, { users }] = await Promise.all([
|
||||
import("@/shared/db"),
|
||||
import("@/shared/db/schema"),
|
||||
])
|
||||
|
||||
const existing = await db.query.users.findFirst({
|
||||
where: eq(users.email, email),
|
||||
columns: { id: true },
|
||||
})
|
||||
if (existing) return { success: false, message: "Email already registered" }
|
||||
const name = String(formData.get("name") ?? "").trim()
|
||||
const email = String(formData.get("email") ?? "").trim().toLowerCase()
|
||||
const password = String(formData.get("password") ?? "")
|
||||
|
||||
await db.insert(users).values({
|
||||
id: createId(),
|
||||
name: name.length ? name : null,
|
||||
email,
|
||||
password,
|
||||
role: "student",
|
||||
})
|
||||
if (!email) return { success: false, message: "请输入邮箱" }
|
||||
if (!password) return { success: false, message: "请输入密码" }
|
||||
if (password.length < 6) return { success: false, message: "密码至少 6 位" }
|
||||
|
||||
return { success: true, message: "Account created" }
|
||||
const existing = await db.query.users.findFirst({
|
||||
where: eq(users.email, email),
|
||||
columns: { id: true },
|
||||
})
|
||||
if (existing) return { success: false, message: "该邮箱已注册" }
|
||||
|
||||
await db.insert(users).values({
|
||||
id: createId(),
|
||||
name: name.length ? name : null,
|
||||
email,
|
||||
password,
|
||||
role: "student",
|
||||
})
|
||||
|
||||
return { success: true, message: "账户创建成功" }
|
||||
} catch (error) {
|
||||
const isProd = process.env.NODE_ENV === "production"
|
||||
|
||||
const anyErr = error as unknown as {
|
||||
code?: string
|
||||
message?: string
|
||||
sqlMessage?: string
|
||||
cause?: unknown
|
||||
}
|
||||
|
||||
const cause1 = anyErr?.cause as
|
||||
| { code?: string; message?: string; sqlMessage?: string; cause?: unknown }
|
||||
| undefined
|
||||
const cause2 = (cause1?.cause ?? undefined) as
|
||||
| { code?: string; message?: string; sqlMessage?: string }
|
||||
| undefined
|
||||
|
||||
const code = String(cause2?.code ?? cause1?.code ?? anyErr?.code ?? "").trim()
|
||||
const msg = String(
|
||||
cause2?.sqlMessage ??
|
||||
cause1?.sqlMessage ??
|
||||
anyErr?.sqlMessage ??
|
||||
cause2?.message ??
|
||||
cause1?.message ??
|
||||
anyErr?.message ??
|
||||
""
|
||||
).trim()
|
||||
const msgLower = msg.toLowerCase()
|
||||
|
||||
if (
|
||||
code === "ER_DUP_ENTRY" ||
|
||||
msgLower.includes("duplicate") ||
|
||||
msgLower.includes("unique")
|
||||
) {
|
||||
return { success: false, message: "该邮箱已注册" }
|
||||
}
|
||||
|
||||
if (
|
||||
code === "ER_NO_SUCH_TABLE" ||
|
||||
msgLower.includes("doesn't exist") ||
|
||||
msgLower.includes("unknown column")
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
message: "数据库未初始化或未迁移,请先运行 npm run db:migrate",
|
||||
}
|
||||
}
|
||||
|
||||
if (code === "ER_ACCESS_DENIED_ERROR") {
|
||||
return { success: false, message: "数据库账号/权限错误,请检查 DATABASE_URL" }
|
||||
}
|
||||
|
||||
if (code === "ECONNREFUSED" || code === "ENOTFOUND") {
|
||||
return { success: false, message: "数据库连接失败,请检查 DATABASE_URL 与网络" }
|
||||
}
|
||||
|
||||
if (!isProd && msg) {
|
||||
return { success: false, message: `创建账户失败:${msg}` }
|
||||
}
|
||||
|
||||
return { success: false, message: "创建账户失败,请稍后重试" }
|
||||
}
|
||||
}
|
||||
|
||||
return <RegisterForm registerAction={registerAction} />
|
||||
|
||||
109
src/app/api/onboarding/complete/route.ts
Normal file
109
src/app/api/onboarding/complete/route.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { eq, inArray } from "drizzle-orm"
|
||||
|
||||
import { auth } from "@/auth"
|
||||
import { db } from "@/shared/db"
|
||||
import { classes, classSubjectTeachers, users } from "@/shared/db/schema"
|
||||
import { DEFAULT_CLASS_SUBJECTS, type ClassSubject } from "@/modules/classes/types"
|
||||
import { enrollStudentByInvitationCode } from "@/modules/classes/data-access"
|
||||
|
||||
export const dynamic = "force-dynamic"
|
||||
|
||||
function parseCodes(input: string) {
|
||||
const raw = input
|
||||
.split(/[\s,,;;]+/g)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
return Array.from(new Set(raw))
|
||||
}
|
||||
|
||||
function isRecord(v: unknown): v is Record<string, unknown> {
|
||||
return typeof v === "object" && v !== null
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const session = await auth()
|
||||
const userId = String(session?.user?.id ?? "").trim()
|
||||
if (!userId) return NextResponse.json({ success: false, message: "Unauthorized" }, { status: 401 })
|
||||
|
||||
const body = await req.json().catch(() => null)
|
||||
if (!isRecord(body)) return NextResponse.json({ success: false, message: "Invalid payload" }, { status: 400 })
|
||||
|
||||
const roleRaw = String(body.role ?? "").trim()
|
||||
const allowedRoles = ["student", "teacher", "parent", "admin"] as const
|
||||
const role = (allowedRoles as readonly string[]).includes(roleRaw) ? roleRaw : null
|
||||
if (!role) return NextResponse.json({ success: false, message: "Invalid role" }, { status: 400 })
|
||||
|
||||
const current = await db.query.users.findFirst({
|
||||
where: eq(users.id, userId),
|
||||
columns: { role: true },
|
||||
})
|
||||
const currentRole = String(current?.role ?? "student")
|
||||
|
||||
if (role === "admin" && currentRole !== "admin") {
|
||||
return NextResponse.json({ success: false, message: "Forbidden" }, { status: 403 })
|
||||
}
|
||||
|
||||
const name = String(body.name ?? "").trim()
|
||||
if (!name) return NextResponse.json({ success: false, message: "Name is required" }, { status: 400 })
|
||||
|
||||
const phone = String(body.phone ?? "").trim()
|
||||
const address = String(body.address ?? "").trim()
|
||||
|
||||
const classCodesText = String(body.classCodes ?? "").trim()
|
||||
const codes = classCodesText.length ? parseCodes(classCodesText) : []
|
||||
|
||||
const teacherSubjectsRaw = Array.isArray(body.teacherSubjects) ? body.teacherSubjects : []
|
||||
const teacherSubjects = teacherSubjectsRaw
|
||||
.map((s) => String(s).trim())
|
||||
.filter((s): s is ClassSubject => DEFAULT_CLASS_SUBJECTS.includes(s as ClassSubject))
|
||||
|
||||
await db
|
||||
.update(users)
|
||||
.set({
|
||||
role,
|
||||
name,
|
||||
phone: phone.length ? phone : null,
|
||||
address: address.length ? address : null,
|
||||
})
|
||||
.where(eq(users.id, userId))
|
||||
|
||||
if (role === "student" && codes.length) {
|
||||
for (const code of codes) {
|
||||
await enrollStudentByInvitationCode(userId, code)
|
||||
}
|
||||
}
|
||||
|
||||
if (role === "teacher" && codes.length && teacherSubjects.length) {
|
||||
const classRows = await db
|
||||
.select({ id: classes.id, invitationCode: classes.invitationCode })
|
||||
.from(classes)
|
||||
.where(inArray(classes.invitationCode, codes))
|
||||
|
||||
const byCode = new Map<string, string>()
|
||||
for (const r of classRows) {
|
||||
if (typeof r.invitationCode === "string") {
|
||||
byCode.set(r.invitationCode, r.id)
|
||||
}
|
||||
}
|
||||
|
||||
for (const code of codes) {
|
||||
const classId = byCode.get(code)
|
||||
if (!classId) continue
|
||||
for (const subject of teacherSubjects) {
|
||||
await db
|
||||
.insert(classSubjectTeachers)
|
||||
.values({ classId, subject, teacherId: userId })
|
||||
.onDuplicateKeyUpdate({ set: { teacherId: userId, updatedAt: new Date() } })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await db
|
||||
.update(users)
|
||||
.set({ onboardedAt: new Date() })
|
||||
.where(eq(users.id, userId))
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
}
|
||||
|
||||
25
src/app/api/onboarding/status/route.ts
Normal file
25
src/app/api/onboarding/status/route.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { eq } from "drizzle-orm"
|
||||
|
||||
import { auth } from "@/auth"
|
||||
import { db } from "@/shared/db"
|
||||
import { users } from "@/shared/db/schema"
|
||||
|
||||
export const dynamic = "force-dynamic"
|
||||
|
||||
export async function GET() {
|
||||
const session = await auth()
|
||||
const userId = String(session?.user?.id ?? "").trim()
|
||||
if (!userId) {
|
||||
return NextResponse.json({ required: false })
|
||||
}
|
||||
|
||||
const row = await db.query.users.findFirst({
|
||||
where: eq(users.id, userId),
|
||||
columns: { onboardedAt: true, role: true },
|
||||
})
|
||||
|
||||
const required = !row?.onboardedAt
|
||||
return NextResponse.json({ required, role: row?.role ?? "student" })
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { ThemeProvider } from "@/shared/components/theme-provider";
|
||||
import { Toaster } from "@/shared/components/ui/sonner";
|
||||
import { NuqsAdapter } from 'nuqs/adapters/next/app'
|
||||
import { AuthSessionProvider } from "@/shared/components/auth-session-provider"
|
||||
import { OnboardingGate } from "@/shared/components/onboarding-gate"
|
||||
import "./globals.css";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
@@ -29,6 +30,7 @@ export default function RootLayout({
|
||||
<AuthSessionProvider>
|
||||
<NuqsAdapter>
|
||||
{children}
|
||||
<OnboardingGate />
|
||||
</NuqsAdapter>
|
||||
</AuthSessionProvider>
|
||||
<Toaster />
|
||||
|
||||
Reference in New Issue
Block a user