mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-07 19:50:20 +00:00
63 lines
1.8 KiB
JavaScript
63 lines
1.8 KiB
JavaScript
import { NextResponse } from "next/server";
|
|
import { getToken } from "next-auth/jwt";
|
|
|
|
// Configure which paths require authentication and which don't
|
|
export async function middleware(request) {
|
|
const { pathname } = request.nextUrl;
|
|
|
|
// Define paths that don't require authentication
|
|
// Include the full NextAuth path pattern to avoid conflicts
|
|
const publicPaths = [
|
|
"/login",
|
|
"/register",
|
|
"/api/register",
|
|
"/api/auth",
|
|
"/api/auth/signin",
|
|
"/api/auth/signout",
|
|
"/api/auth/session",
|
|
"/api/auth/csrf",
|
|
];
|
|
|
|
const isPathPublic = publicPaths.some((path) => {
|
|
return pathname === path || pathname.startsWith(`${path}/`);
|
|
});
|
|
|
|
// If it's a public path, allow the request
|
|
if (isPathPublic) {
|
|
return NextResponse.next();
|
|
}
|
|
|
|
try {
|
|
// For protected paths, check authentication
|
|
const token = await getToken({
|
|
req: request,
|
|
secret:
|
|
process.env.NEXTAUTH_SECRET ||
|
|
"your-fallback-secret-should-be-at-least-32-chars",
|
|
});
|
|
|
|
// If not authenticated, redirect to login
|
|
if (!token) {
|
|
const url = new URL("/login", request.url);
|
|
url.searchParams.set("callbackUrl", encodeURI(request.url));
|
|
return NextResponse.redirect(url);
|
|
}
|
|
|
|
return NextResponse.next();
|
|
} catch (error) {
|
|
console.error("Middleware authentication error:", error);
|
|
// If there's an error in authentication, redirect to login
|
|
const url = new URL("/login", request.url);
|
|
url.searchParams.set("error", "AuthError");
|
|
return NextResponse.redirect(url);
|
|
}
|
|
}
|
|
|
|
// Configure which paths this middleware runs on
|
|
export const config = {
|
|
matcher: [
|
|
// Match all paths except those starting with _next, public, or ending with specific file extensions
|
|
"/((?!_next/static|_next/image|favicon.ico|.*\\.png$|.*\\.jpg$|.*\\.svg$).*)",
|
|
],
|
|
};
|