From 80eb0a6c1bfd3362a0eb7545b618d53aec14cf36 Mon Sep 17 00:00:00 2001 From: g Date: Fri, 7 Feb 2025 22:21:26 +0000 Subject: [PATCH] Create middleswares --- lib/client-utils.ts | 3 --- middleware.ts | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) create mode 100644 middleware.ts diff --git a/lib/client-utils.ts b/lib/client-utils.ts index 8e993c7..e5a6313 100644 --- a/lib/client-utils.ts +++ b/lib/client-utils.ts @@ -8,9 +8,6 @@ export async function clientFetch(url: string, options: RequestInit = {}): Promi .find(row => row.startsWith('Authorization=')) ?.split('=')[1] || localStorage.getItem('Authorization'); - console.log('authToken', authToken); - - // Merge Authorization header if token is found const headers = { 'Content-Type': 'application/json', ...(authToken ? { Authorization: `Bearer ${authToken}` } : {}), diff --git a/middleware.ts b/middleware.ts new file mode 100644 index 0000000..f285bed --- /dev/null +++ b/middleware.ts @@ -0,0 +1,34 @@ +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 { + const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/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*"], +}; \ No newline at end of file