import { NextResponse } from "next/server"; import { cookies } from "next/headers"; const checkAuthentication = async () => { const token = req.cookies["cmc-token"]; // Access the token from cookies console.log("checking token", token); const isAuthenticated = token ? true : false; // Check if the user is authenticated. return isAuthenticated; }; const isTokenValid = () => { if (typeof window === "undefined") { return false; // Don't execute this code on the server-side } const cookies = document.cookie.split("; "); // Get all cookies and split them into an array for (const cookie of cookies) { const [name, value] = cookie.split("="); // Split the cookie into its name and value if (name.trim() === "cmc-token" && value) { return true; // The cmc-token cookie exists } } return false; }; export async function middleware(req) { const token = isTokenValid(); // req.cookies["cmc-token"]; // Access the token from cookies const cookieList = 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 { if (pathname === "/auth/login" && token) { // Redirect to the home page if already authenticated return NextResponse.redirect(new URL("/"), { status: 307 }); } if (!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 = cookieList.has("cmc-token"); console.log(token); if (!isAuthenticated) { // Handle unauthenticated users return NextResponse.error(new Error("Authentication failed"), { status: 401, }); } // Continue with the request if authenticated return NextResponse.next(); } 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", ];