36 lines
937 B
TypeScript
36 lines
937 B
TypeScript
import { withAuth } from "next-auth/middleware";
|
|
import { NextResponse } from "next/server";
|
|
|
|
export default withAuth(
|
|
function middleware(req) {
|
|
const { pathname } = req.nextUrl;
|
|
const role = req.nextauth.token?.role as string;
|
|
|
|
if (pathname.startsWith("/superadmin")) {
|
|
if (role !== "superadmin") {
|
|
return NextResponse.redirect(new URL("/dashboard", req.url));
|
|
}
|
|
}
|
|
|
|
if (pathname.startsWith("/dashboard")) {
|
|
if (!role || (role !== "admin" && role !== "teacher" && role !== "superadmin")) {
|
|
return NextResponse.redirect(new URL("/login", req.url));
|
|
}
|
|
}
|
|
|
|
return NextResponse.next();
|
|
},
|
|
{
|
|
callbacks: {
|
|
authorized({ req, token }) {
|
|
if (req.nextUrl.pathname.startsWith("/login")) return true;
|
|
return !!token;
|
|
},
|
|
},
|
|
}
|
|
);
|
|
|
|
export const config = {
|
|
matcher: ["/dashboard/:path*", "/superadmin/:path*", "/api/protected/:path*"],
|
|
};
|