37 lines
1002 B
TypeScript
37 lines
1002 B
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("No token found, redirecting to login...");
|
|
return NextResponse.redirect(new URL("/auth/login", req.url));
|
|
}
|
|
|
|
try {
|
|
// Need to use a full URL for server-side fetch
|
|
const baseUrl = req.nextUrl.origin + '/api';
|
|
|
|
const res = await fetch(`${baseUrl}/auth/me`, {
|
|
method: "GET",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Authorization: `Bearer ${token}`,
|
|
},
|
|
});
|
|
|
|
if (!res.ok) {
|
|
return NextResponse.redirect(new URL("/auth/login", req.url));
|
|
}
|
|
} 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*"],
|
|
}; |