refactor: replace custom authentication middleware with NextAuth, remove unused authentication pages, and update matcher configuration

This commit is contained in:
2025-03-23 18:06:27 +05:00
parent 020d74c5e2
commit 32bb01b656
8 changed files with 34 additions and 37 deletions

View File

@ -1,36 +1,20 @@
import type { Session } from "better-auth/types";
import { type NextRequest, NextResponse } from "next/server";
import { withAuth } from "next-auth/middleware";
export default async function authMiddleware(request: NextRequest) {
const protocol = request.headers.get("x-forwarded-proto") || "http";
const host = request.headers.get("host") || "localhost:3000";
try {
const response = await fetch(`${protocol}://${host}/api/auth/get-session`, {
method: "GET",
headers: {
cookie: request.headers.get("cookie") || "",
host: host,
},
next: { revalidate: 600 }, // Cache for 10 minutes (600 seconds)
});
if (!response.ok) {
throw new Error("Failed to fetch session");
}
const session: Session = await response.json();
if (!session) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
} catch (error) {
console.log("Middleware error", error);
return NextResponse.redirect(new URL("/login", request.url));
}
}
export default withAuth(
// `withAuth` augments your `Request` with the user's token.
function middleware(req) {},
);
export const config = {
matcher: ["/devices", "/", "/payments", "/payments/:paymentId"],
// https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
"/((?!api|_next/static|_next/image|favicon.ico|auth/|access-denied).*)",
],
};