diff --git a/frontend/app/layout.jsx b/frontend/app/layout.jsx index d491c3e7..b748dd72 100755 --- a/frontend/app/layout.jsx +++ b/frontend/app/layout.jsx @@ -1,31 +1,33 @@ -// File: frontend/app/layout.jsx +// frontend/app/layout.jsx +import "./globals.css"; import Link from "next/link"; import { redirect } from "next/navigation"; import { cookies, headers } from "next/headers"; -// ถ้ามี lib rbac เดิมà¸à¸¢à¸¹à¹ˆà¹ƒà¸«à¹‰à¹ƒà¸Šà¹‰à¸•่à¸à¹„ด้ -import { can } from "@/lib/rbac"; -// à¹à¸à¹‰ title ให้ถูà¸à¸ªà¸°à¸à¸” -export const metadata = { title: "DMS | Protected" }; +export const metadata = { + title: "DMS", + description: "Document Management System — LCBP3 Phase 3", +}; const API_BASE = (process.env.NEXT_PUBLIC_API_BASE || "").replace(/\/$/, ""); -async function fetchSessionFromAPI() { - // ดึงคุà¸à¸à¸µà¹‰à¸ˆà¸£à¸´à¸‡à¸ˆà¸²à¸à¸à¸±à¹ˆà¸‡à¹€à¸‹à¸´à¸£à¹Œà¸Ÿà¹€à¸§à¸à¸£à¹Œ à¹à¸¥à¹‰à¸§à¸ªà¹ˆà¸‡à¸•่à¸à¹ƒà¸«à¹‰ backend - const cookieHeader = cookies().toString(); // serialize ทั้งชุด - const hostHdr = headers().get("host"); - const protoHdr = headers().get("x-forwarded-proto") || "https"; +/** ดึงสถานะผู้ใช้แบบ global (ไม่บังคับล็อกอิน) */ +async function fetchGlobalSession() { + const cookieStore = await cookies(); + const cookieHeader = cookieStore.toString(); + + const hdrs = await headers(); + const hostHdr = hdrs.get("host"); + const protoHdr = hdrs.get("x-forwarded-proto") || "https"; const res = await fetch(`${API_BASE}/api/auth/me`, { method: "GET", headers: { Cookie: cookieHeader, - // เผื่ภbackend ตรวจ origin/proto/host "X-Forwarded-Host": hostHdr || "", "X-Forwarded-Proto": protoHdr, Accept: "application/json", }, - // server component ไม่ต้à¸à¸‡à¹ƒà¸Šà¹‰ credentials cache: "no-store", }); @@ -38,75 +40,75 @@ async function fetchSessionFromAPI() { } } -export default async function ProtectedLayout({ children }) { - const session = await fetchSessionFromAPI(); - if (!session) { - // พยายามส่ง next path à¸à¸¥à¸±à¸šà¹„ปที่ /login - redirect("/login?next=/dashboard"); - } - const { user } = session; +/** ปุ่ม Logout แบบ Server Action (ไม่ต้องมี client component) */ +async function LogoutAction() { + "use server"; + const cookieStore = await cookies(); + const cookieHeader = cookieStore.toString(); + + const hdrs = await headers(); + const hostHdr = hdrs.get("host"); + const protoHdr = hdrs.get("x-forwarded-proto") || "https"; + + // เรียก backend ให้ลบคุกกี้ออก (HttpOnly cookies) + await fetch(`${API_BASE}/api/auth/logout`, { + method: "POST", + headers: { + Cookie: cookieHeader, + "X-Forwarded-Host": hostHdr || "", + "X-Forwarded-Proto": protoHdr, + Accept: "application/json", + }, + cache: "no-store", + }); + + // กลับไปหน้า login พร้อม next ไป dashboard + redirect("/login?next=/dashboard"); +} + +export default async function RootLayout({ children }) { + const session = await fetchGlobalSession(); + const loggedIn = !!session?.user; return ( - - + {children} + + ); -} \ No newline at end of file +}