66 lines
2.2 KiB
TypeScript
66 lines
2.2 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import type { NextRequest } from "next/server";
|
|
|
|
export async function middleware(req: NextRequest) {
|
|
// Check for auth token in cookies
|
|
const token = req.cookies.get("Authorization")?.value;
|
|
|
|
// Debug info about all cookies
|
|
const allCookies = req.cookies.getAll();
|
|
console.log("Middleware: All cookies:", allCookies.map(c => c.name).join(', '));
|
|
|
|
if (!token) {
|
|
// Try to get from Authorization header as fallback
|
|
const authHeader = req.headers.get('Authorization');
|
|
|
|
if (authHeader?.startsWith('Bearer ')) {
|
|
console.log("Middleware: Token found in Authorization header");
|
|
// Continue with validation using header auth
|
|
// The authCheckUrl will handle extracting the token from header
|
|
} else {
|
|
console.log("Middleware: No token found in cookies or headers, redirecting to login...");
|
|
return NextResponse.redirect(new URL("/auth/login", req.url));
|
|
}
|
|
} else {
|
|
console.log("Middleware: Token found in cookies, validating...");
|
|
}
|
|
|
|
try {
|
|
// Always use localhost for internal container communication
|
|
const authCheckUrl = "http://localhost:3000/api/auth/check";
|
|
|
|
console.log(`Using internal auth check URL: ${authCheckUrl}`);
|
|
|
|
// Clone headers to avoid modifying the original request
|
|
const headers = new Headers(req.headers);
|
|
|
|
// If token is in cookie, ensure it's also in Authorization header
|
|
if (token && !headers.has('Authorization')) {
|
|
headers.set('Authorization', `Bearer ${token}`);
|
|
}
|
|
|
|
const res = await fetch(authCheckUrl, {
|
|
method: "GET",
|
|
headers,
|
|
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*"],
|
|
}; |