Files
ember-market-frontend/middleware.ts
2025-03-23 22:20:43 +00:00

55 lines
1.8 KiB
TypeScript

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export async function middleware(req: NextRequest) {
const token = req.cookies.get("Authorization")?.value;
if (!token) {
console.log("Middleware: No token found, redirecting to login...");
return NextResponse.redirect(new URL("/auth/login", req.url));
}
console.log("Middleware: Token found, validating...");
try {
// Get the origin but handle localhost differently to avoid SSL issues
const origin = req.nextUrl.origin;
// Construct the auth check URL based on environment
// For localhost, explicitly use HTTP instead of HTTPS
const isLocalhost = origin.includes('localhost') || origin.includes('127.0.0.1');
const protocol = isLocalhost ? 'http' : 'https';
const host = req.nextUrl.host;
const authCheckUrl = `${protocol}://${host}/api/auth/check`;
console.log(`Using internal auth check URL: ${authCheckUrl}`);
const res = await fetch(authCheckUrl, {
method: "GET",
headers: {
"Content-Type": "application/json",
// Explicitly pass the token in headers as well
"Authorization": `Bearer ${token}`
},
credentials: 'include',
});
console.log(`Middleware: Auth check responded with status ${res.status}`);
if (!res.ok) {
console.log(`Middleware: Auth check failed with status ${res.status}, redirecting to login`);
return NextResponse.redirect(new URL("/auth/login", req.url));
}
console.log("Middleware: Auth check successful, proceeding to dashboard");
} catch (error) {
console.error("Authentication validation failed:", error);
return NextResponse.redirect(new URL("/auth/login", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*"],
};