feat: แกไข frontend/lib/auth.js
This commit is contained in:
@@ -1,18 +1,38 @@
|
||||
// lib/auth.js
|
||||
// frontend/lib/auth.js
|
||||
import { cookies } from "next/headers";
|
||||
import { API_BASE } from "./api";
|
||||
|
||||
// เรียกจาก Server Component/SSR เพื่อตรวจ session จริง
|
||||
const COOKIE_NAME = "access_token";
|
||||
|
||||
/**
|
||||
* Server-side session fetcher (ใช้ใน Server Components/Layouts)
|
||||
* - อ่านคุกกี้แบบ async: await cookies()
|
||||
* - ถ้าไม่มี token → return null
|
||||
* - ถ้ามี → เรียก /api/auth/me ที่ backend เพื่อตรวจสอบ
|
||||
*/
|
||||
export async function getSession() {
|
||||
const cookieStore = cookies();
|
||||
const cookie = cookieStore.toString();
|
||||
const res = await fetch(`${API_BASE}/auth/me`, {
|
||||
headers: { cookie },
|
||||
credentials: "include",
|
||||
// ✅ ต้อง await
|
||||
const cookieStore = await cookies();
|
||||
const token = cookieStore.get(COOKIE_NAME)?.value;
|
||||
|
||||
if (!token) return null;
|
||||
|
||||
// เรียก backend ตรวจ session (ปรับ endpoint ให้ตรงของคุณ)
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE}/api/auth/me`, {
|
||||
// ส่งต่อคุกกี้ไป backend (เลือกอย่างใดอย่างหนึ่ง)
|
||||
// วิธี A: ส่ง header Cookie โดยตรง
|
||||
headers: { Cookie: `${COOKIE_NAME}=${token}` },
|
||||
// วิธี B: ถ้า proxy ผ่าน nginx ในโดเมนเดียวกัน ใช้ credentials รวมคุกกี้อัตโนมัติได้
|
||||
// credentials: "include",
|
||||
cache: "no-store",
|
||||
next: { revalidate: 0 },
|
||||
});
|
||||
|
||||
if (!res.ok) return null;
|
||||
|
||||
const data = await res.json();
|
||||
return data?.user ? data : null;
|
||||
// คาดหวังโครงสร้าง { user, permissions } จาก backend
|
||||
return {
|
||||
user: data.user,
|
||||
permissions: data.permissions || [],
|
||||
token,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user