Selaa lähdekoodia

refactor(middleware): simplify authentication logic using withAuth

vidane 6 kuukautta sitten
vanhempi
sitoutus
f2141bb7b9
1 muutettua tiedostoa jossa 4 lisäystä ja 59 poistoa
  1. 4 59
      middleware.ts

+ 4 - 59
middleware.ts

@@ -1,64 +1,9 @@
-import { NextRequest, NextResponse } from "next/server";
-import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
+import { withAuth } from "@kinde-oss/kinde-auth-nextjs/server";
 
-export async function middleware(request: NextRequest) {
-  // Allow public routes
-  const publicPaths = [
-    "/",
-    "/api/auth/login",
-    "/api/auth/register",
-    "/api/auth/callback",
-    "/api/auth/logout",
-    "/favicon.ico",
-    "/_next",
-    "/public",
-  ];
-  
-  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();
-  }
-  
-  // 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();
+export default function middleware(request: Request) {
+  return withAuth(request);
 }
 
 export const config = {
-  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
+  matcher: ["/files/:path*", "/api-docs/:path*"],
 };