66 lines
1.8 KiB
JavaScript
66 lines
1.8 KiB
JavaScript
import { NextResponse } from "next/server";
|
|
import { cookies } from "next/headers";
|
|
|
|
import { getCookie, hasCookie } from "cookies-next";
|
|
|
|
export async function middleware(req, next) {
|
|
const token = getCookie("cmc-token", { req }); // Access the token from cookies
|
|
|
|
const headers = new Headers(req.headers);
|
|
headers.set("X-XSS-Protection", "1; mode=block");
|
|
headers.set("X-Frame-Options", "SAMEORIGIN");
|
|
headers.set("Content-Security-Policy", "frame-ancestors 'same';");
|
|
|
|
const { origin, pathname } = req.nextUrl;
|
|
|
|
try {
|
|
// console.log("Test path", pathname, origin);
|
|
if (token) {
|
|
// Redirect to the home page if already authenticated
|
|
NextResponse.redirect(new URL(pathname, origin), { status: 302 });
|
|
// Continue with the request if authenticated
|
|
return NextResponse.next();
|
|
}
|
|
|
|
if (
|
|
!authenticationPages.includes(pathname) ||
|
|
(authenticationPages.includes(pathname) && !token)
|
|
) {
|
|
// Redirect to the login page if not authenticated
|
|
return NextResponse.redirect(new URL("/auth/login", origin), {
|
|
status: 307,
|
|
});
|
|
}
|
|
|
|
// Add authentication logic here (verify the token, etc.)
|
|
// const isAuthenticated = verifyToken(token);
|
|
// const isAuthenticated = hasCookie("cmc-token", { req });
|
|
|
|
// if (!isAuthenticated) {
|
|
// // Handle unauthenticated users
|
|
// return NextResponse.error(new Error("Authentication failed"), {
|
|
// status: 401,
|
|
// });
|
|
// }
|
|
|
|
} catch (error) {
|
|
console.error("Error during authentication check:", error);
|
|
return NextResponse.error();
|
|
}
|
|
}
|
|
|
|
export const config = {
|
|
matcher: "/",
|
|
};
|
|
|
|
const authenticationPages = [
|
|
// "/",
|
|
"/auth",
|
|
"/auth/login",
|
|
"/auth/sign-up",
|
|
"/auth/forgot-password",
|
|
"/auth/lock-screen",
|
|
"/auth/confirm-mail",
|
|
"/auth/logout",
|
|
];
|