|
|
@@ -1,25 +1,61 @@
|
|
|
import { NextRequest, NextResponse } from "next/server";
|
|
|
+import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
|
|
|
|
|
|
-export function middleware(request: NextRequest) {
|
|
|
+export async function middleware(request: NextRequest) {
|
|
|
// Allow public routes
|
|
|
const publicPaths = [
|
|
|
"/",
|
|
|
- "/api-docs",
|
|
|
"/api/auth/login",
|
|
|
"/api/auth/register",
|
|
|
"/api/auth/callback",
|
|
|
"/api/auth/logout",
|
|
|
+ "/favicon.ico",
|
|
|
+ "/_next",
|
|
|
+ "/public",
|
|
|
];
|
|
|
|
|
|
- const isPublicPath = publicPaths.some(path =>
|
|
|
- request.nextUrl.pathname.startsWith(path)
|
|
|
- );
|
|
|
+ const pathname = request.nextUrl.pathname;
|
|
|
+ const isPublicPath = publicPaths.some(path => pathname.startsWith(path));
|
|
|
|
|
|
+ // Allow public access to auth routes and static assets
|
|
|
if (isPublicPath) {
|
|
|
return NextResponse.next();
|
|
|
}
|
|
|
|
|
|
- // For now, allow all other routes - we'll add proper authentication checks later
|
|
|
+ // Check authentication for protected routes
|
|
|
+ const protectedPaths = [
|
|
|
+ "/files",
|
|
|
+ "/api-docs",
|
|
|
+ ];
|
|
|
+
|
|
|
+ const isProtectedPath = protectedPaths.some(path => pathname.startsWith(path));
|
|
|
+
|
|
|
+ if (isProtectedPath) {
|
|
|
+ try {
|
|
|
+ const { isAuthenticated } = getKindeServerSession();
|
|
|
+ const authenticated = await isAuthenticated();
|
|
|
+
|
|
|
+ // Add debugging headers
|
|
|
+ const response = NextResponse.next();
|
|
|
+ response.headers.set('X-Auth-Status', authenticated ? 'authenticated' : 'unauthenticated');
|
|
|
+
|
|
|
+ if (!authenticated) {
|
|
|
+ // Redirect to login page if not authenticated
|
|
|
+ const loginUrl = new URL("/api/auth/login", request.url);
|
|
|
+ loginUrl.searchParams.set("post_login_redirect_url", pathname);
|
|
|
+ return NextResponse.redirect(loginUrl);
|
|
|
+ }
|
|
|
+
|
|
|
+ return response;
|
|
|
+ } catch (error) {
|
|
|
+ console.error("Authentication check failed:", error);
|
|
|
+ // Redirect to login on authentication error
|
|
|
+ const loginUrl = new URL("/api/auth/login", request.url);
|
|
|
+ return NextResponse.redirect(loginUrl);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // Allow all other routes
|
|
|
return NextResponse.next();
|
|
|
}
|
|
|
|