51 lines
1.6 KiB
TypeScript
51 lines
1.6 KiB
TypeScript
import { NextResponse } from "next/server"
|
|
import type { NextAuthRequest } from "next-auth"
|
|
|
|
import { auth } from "./auth"
|
|
|
|
function normalizeRole(value: unknown) {
|
|
const role = String(value ?? "").trim().toLowerCase()
|
|
if (role === "admin" || role === "student" || role === "teacher" || role === "parent") return role
|
|
return "student"
|
|
}
|
|
|
|
function roleHome(role: string) {
|
|
if (role === "admin") return "/admin/dashboard"
|
|
if (role === "student") return "/student/dashboard"
|
|
if (role === "parent") return "/parent/dashboard"
|
|
return "/teacher/dashboard"
|
|
}
|
|
|
|
export default auth((req: NextAuthRequest) => {
|
|
const { pathname } = req.nextUrl
|
|
const session = req.auth
|
|
|
|
if (!session?.user) {
|
|
const url = req.nextUrl.clone()
|
|
url.pathname = "/login"
|
|
url.searchParams.set("callbackUrl", pathname)
|
|
return NextResponse.redirect(url)
|
|
}
|
|
|
|
const role = normalizeRole(session.user.role)
|
|
|
|
if (pathname.startsWith("/admin/") && role !== "admin") {
|
|
return NextResponse.redirect(new URL(roleHome(role), req.url))
|
|
}
|
|
if (pathname.startsWith("/teacher/") && role !== "teacher") {
|
|
return NextResponse.redirect(new URL(roleHome(role), req.url))
|
|
}
|
|
if (pathname.startsWith("/student/") && role !== "student") {
|
|
return NextResponse.redirect(new URL(roleHome(role), req.url))
|
|
}
|
|
if (pathname.startsWith("/parent/") && role !== "parent") {
|
|
return NextResponse.redirect(new URL(roleHome(role), req.url))
|
|
}
|
|
|
|
return NextResponse.next()
|
|
})
|
|
|
|
export const config = {
|
|
matcher: ["/dashboard", "/admin/:path*", "/teacher/:path*", "/student/:path*", "/parent/:path*", "/settings/:path*", "/profile"],
|
|
}
|