mirror of
https://github.com/i701/sarlink-portal.git
synced 2025-07-02 03:38:22 +00:00
refactor: replace custom authentication middleware with NextAuth, remove unused authentication pages, and update matcher configuration
This commit is contained in:
@ -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).*)",
|
||||
],
|
||||
};
|
||||
|
Reference in New Issue
Block a user