feat: แกไขสวน pages.jsx, layout.jsx
This commit is contained in:
@@ -1,23 +1,50 @@
|
||||
// frontend/middleware.ts
|
||||
import { NextResponse } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
// ชื่อคุกกี้ให้ตรงกับ backend
|
||||
// ให้ตรงกับชื่อคุกกี้ที่ backend เซ็ต
|
||||
const COOKIE_NAME = "access_token";
|
||||
// หน้าที่เปิดได้โดยไม่ต้องล็อกอิน (ถ้าต้องการเพิ่มให้ใส่เพิ่มที่นี่)
|
||||
const PUBLIC_PREFIXES = ["/login", "/register", "/health", "/api/health"];
|
||||
// const PUBLIC_PATHS = new Set<string>(["/login", "/register", "/health"]);
|
||||
|
||||
export function middleware(req: NextRequest) {
|
||||
const { pathname } = req.nextUrl;
|
||||
const hasToken = req.cookies.get("access_token");
|
||||
// ตรวจคุกกี้
|
||||
const hastoken = req.cookies.get(COOKIE_NAME)?.value;
|
||||
if (!hasToken) {
|
||||
const loginUrl = new URL("/login", req.url);
|
||||
// จำเส้นทางเดิมไว้เพื่อเด้งกลับหลังล็อกอิน
|
||||
loginUrl.searchParams.set("from", pathname);
|
||||
return NextResponse.redirect(loginUrl);
|
||||
const { pathname, search } = req.nextUrl;
|
||||
|
||||
// อนุญาตไฟล์สาธารณะและ Static assets
|
||||
if (
|
||||
pathname.startsWith("/_next/") ||
|
||||
pathname.startsWith("/public/") ||
|
||||
pathname === "/favicon.ico"
|
||||
) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
// หน้าสาธารณะ: ปล่อยผ่าน
|
||||
// if (PUBLIC_PATHS.has(pathname)) {
|
||||
// return NextResponse.next();
|
||||
// }
|
||||
// อนุญาตหน้า public
|
||||
if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
// ตรวจ token จาก cookie
|
||||
const token = req.cookies.get(COOKIE_NAME)?.value;
|
||||
|
||||
// ไม่มี token → เด้งไป /login พร้อม next=path เดิม
|
||||
if (!token) {
|
||||
const url = req.nextUrl.clone();
|
||||
url.pathname = "/login";
|
||||
url.searchParams.set("next", pathname + (search || ""));
|
||||
return NextResponse.redirect(url);
|
||||
}
|
||||
|
||||
// มี token → ผ่าน
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
// จำกัดให้ตรวจเฉพาะเส้นทาง protected (ลดโอเวอร์เฮด)
|
||||
export const config = {
|
||||
matcher: [
|
||||
"/dashboard/:path*",
|
||||
|
||||
Reference in New Issue
Block a user