ปรับ frontend

This commit is contained in:
admin
2025-10-01 13:53:46 +07:00
parent 5cac3bdabf
commit 2215633fb9
7 changed files with 269 additions and 213 deletions

View File

@@ -1,54 +1,34 @@
// File: frontend/app/(auth)/login/page.jsx
"use client";
// ✅ ปรับให้ตรง backend: ใช้ Bearer token (ไม่ใช้ cookie)
// - เรียก POST /api/auth/login → รับ { token, refresh_token, user }
// - เก็บ token/refresh_token ใน localStorage (หรือ sessionStorage ถ้าไม่ติ๊กจำไว้)
// - ไม่ใช้ credentials: "include" อีกต่อไป
// - เอา RootLayout/metadata ออก เพราะไฟล์เพจเป็น client component
// - เพิ่มการอ่าน NEXT_PUBLIC_API_BASE และ error handling ให้ตรงกับ backend
// - เพิ่มโหมดดีบัก เปิดด้วย NEXT_PUBLIC_DEBUG_AUTH=1
import { useState, useMemo, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import {
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
CardFooter,
Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter,
} from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription } from "@/components/ui/alert";
const API_BASE = process.env.NEXT_PUBLIC_API_BASE?.replace(/\/$/, "") || "";
const API_BASE = (process.env.NEXT_PUBLIC_API_BASE || "").replace(/\/$/, "");
const DEBUG =
String(process.env.NEXT_PUBLIC_DEBUG_AUTH || "").trim() !== "" &&
process.env.NEXT_PUBLIC_DEBUG_AUTH !== "0" &&
process.env.NEXT_PUBLIC_DEBUG_AUTH !== "false";
function dlog(...args) {
if (DEBUG && typeof window !== "undefined") {
console.debug("[login]", ...args);
}
if (DEBUG && typeof window !== "undefined") console.debug("[login]", ...args);
}
function LoginForm() {
const router = useRouter();
const searchParams = useSearchParams();
const nextPath = useMemo(
() => searchParams.get("next") || "/dashboard",
[searchParams]
);
const nextPath = useMemo(() => searchParams.get("next") || "/dashboard", [searchParams]);
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [showPw, setShowPw] = useState(false);
const [remember, setRemember] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [err, setErr] = useState("");
@@ -63,69 +43,37 @@ function LoginForm() {
try {
setSubmitting(true);
// ── DEBUG: ค่าเบื้องต้น
dlog("API_BASE =", API_BASE || "(empty → จะเรียก path relative)");
dlog("nextPath =", nextPath);
dlog("remember =", remember);
dlog("payload =", { username: "[hidden]", password: "[hidden]" });
dlog("API_BASE =", API_BASE || "(empty → relative path)"); dlog("nextPath =", nextPath);
const res = await fetch(`${API_BASE}/api/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
credentials: "include", // << ใช้คุกกี้
cache: "no-store",
body: JSON.stringify({ username, password }),
});
dlog("response.status =", res.status);
dlog("response.headers.content-type =", res.headers.get("content-type"));
dlog("status =", res.status, "ctype =", res.headers.get("content-type"));
let data = {};
try {
data = await res.json();
} catch (e) {
dlog("response.json() error =", e);
}
dlog("response.body =", data);
try { data = await res.json(); } catch {}
if (!res.ok) {
const msg =
data?.error === "INVALID_CREDENTIALS"
? "ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง"
: data?.error || `เข้าสู่ระบบไม่สำเร็จ (HTTP ${res.status})`;
dlog("login FAILED →", msg);
setErr(msg);
return;
}
if (!data?.token) {
dlog("login FAILED → data.token not found");
setErr("รูปแบบข้อมูลตอบกลับไม่ถูกต้อง (ไม่มี token)");
return;
}
// ✅ เก็บ token ตามโหมดจำไว้/ไม่จำ
const storage = remember ? window.localStorage : window.sessionStorage;
storage.setItem("dms.token", data.token);
storage.setItem("dms.refresh_token", data.refresh_token);
storage.setItem("dms.user", JSON.stringify(data.user || {}));
dlog("token stored in", remember ? "localStorage" : "sessionStorage");
// (ออปชัน) เผยแพร่ event ให้แท็บอื่นทราบ
try {
window.dispatchEvent(
new StorageEvent("storage", { key: "dms.auth", newValue: "login" })
);
} catch {}
dlog("navigating →", nextPath);
// คุกกี้ (HttpOnly) ถูกตั้งด้วย Set-Cookie จาก backend แล้ว
dlog("login ok → redirect", nextPath);
router.replace(nextPath);
} catch (e) {
dlog("exception =", e);
setErr("เชื่อมต่อเซิร์ฟเวอร์ไม่ได้ กรุณาลองใหม่");
} finally {
setSubmitting(false);
dlog("done");
}
}
@@ -133,32 +81,22 @@ function LoginForm() {
<div className="grid min-h-[calc(100vh-4rem)] place-items-center p-4">
<Card className="w-full max-w-md border-0 shadow-xl ring-1 ring-black/5 bg-white/90 backdrop-blur">
<CardHeader className="space-y-1">
<CardTitle className="text-2xl font-bold text-sky-800">
เขาสระบบ
</CardTitle>
<CardDescription className="text-sky-700">
Document Management System LCBP3
</CardDescription>
<CardTitle className="text-2xl font-bold text-sky-800">เขาสระบบ</CardTitle>
<CardDescription className="text-sky-700">Document Management System LCBP3</CardDescription>
</CardHeader>
<CardContent>
{err ? (
<Alert className="mb-4">
<AlertDescription>{err}</AlertDescription>
</Alert>
<Alert className="mb-4"><AlertDescription>{err}</AlertDescription></Alert>
) : null}
<form onSubmit={onSubmit} className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="username">อผใช</Label>
<Input
id="username"
autoFocus
autoComplete="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="เช่น superadmin"
disabled={submitting}
id="username" autoFocus autoComplete="username"
value={username} onChange={(e) => setUsername(e.target.value)}
placeholder="เช่น superadmin" disabled={submitting}
/>
</div>
@@ -166,59 +104,22 @@ function LoginForm() {
<Label htmlFor="password">รหสผาน</Label>
<div className="relative">
<Input
id="password"
type={showPw ? "text" : "password"}
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="••••••••"
disabled={submitting}
className="pr-10"
id="password" type={showPw ? "text" : "password"} autoComplete="current-password"
value={password} onChange={(e) => setPassword(e.target.value)}
placeholder="••••••••" disabled={submitting} className="pr-10"
/>
<button
type="button"
onClick={() => setShowPw((v) => !v)}
type="button" onClick={() => setShowPw((v) => !v)}
className="absolute inset-y-0 px-2 my-auto text-xs bg-white border rounded-md right-2 hover:bg-slate-50"
aria-label={showPw ? "ซ่อนรหัสผ่าน" : "แสดงรหัสผ่าน"}
disabled={submitting}
aria-label={showPw ? "ซ่อนรหัสผ่าน" : "แสดงรหัสผ่าน"} disabled={submitting}
>
{showPw ? "Hide" : "Show"}
</button>
</div>
</div>
<div className="flex items-center justify-between pt-1">
<label className="inline-flex items-center gap-2 text-sm text-slate-600">
<input
type="checkbox"
className="size-4 accent-sky-700"
checked={remember}
onChange={(e) => setRemember(e.target.checked)}
disabled={submitting}
/>
จดจำฉนไวในเครองน
</label>
<a
href="/forgot-password"
className="text-sm text-sky-700 hover:text-sky-900 hover:underline"
>
มรหสผาน?
</a>
</div>
<Button
type="submit"
disabled={submitting}
className="mt-2 bg-sky-700 hover:bg-sky-800"
>
{submitting ? (
<span className="inline-flex items-center gap-2">
<Spinner /> กำลงเขาสระบบ
</span>
) : (
"เข้าสู่ระบบ"
)}
<Button type="submit" disabled={submitting} className="mt-2 bg-sky-700 hover:bg-sky-800">
{submitting ? <span className="inline-flex items-center gap-2"><Spinner /> กำลงเขาสระบบ</span> : "เข้าสู่ระบบ"}
</Button>
{DEBUG ? (
@@ -245,18 +146,13 @@ export default function LoginPage() {
);
}
/** Loading skeleton */
function LoginPageSkeleton() {
return (
<div className="grid min-h-[calc(100vh-4rem)] place-items-center p-4">
<Card className="w-full max-w-md border-0 shadow-xl ring-1 ring-black/5 bg-white/90 backdrop-blur">
<CardHeader className="space-y-1">
<CardTitle className="text-2xl font-bold text-sky-800">
เขาสระบบ
</CardTitle>
<CardDescription className="text-sky-700">
Document Management System LCBP3
</CardDescription>
<CardTitle className="text-2xl font-bold text-sky-800">เขาสระบบ</CardTitle>
<CardDescription className="text-sky-700">Document Management System LCBP3</CardDescription>
</CardHeader>
<CardContent>
<div className="grid gap-4 animate-pulse">
@@ -270,28 +166,11 @@ function LoginPageSkeleton() {
);
}
/** Spinner แบบไม่พึ่งไลบรารีเสริม */
function Spinner() {
return (
<svg
className="animate-spin size-4"
viewBox="0 0 24 24"
fill="none"
aria-hidden="true"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"
/>
<svg className="animate-spin size-4" viewBox="0 0 24 24" fill="none" aria-hidden="true">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" />
</svg>
);
}