Update login page.jsx
This commit is contained in:
341
frontend/app/(auth)/login/page copy.jsx
Normal file
341
frontend/app/(auth)/login/page copy.jsx
Normal file
@@ -0,0 +1,341 @@
|
||||
// frontend/app/(auth)/login/page.jsx
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import {
|
||||
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";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
|
||||
const IS_DEV = process.env.NODE_ENV !== "production";
|
||||
|
||||
// URL builder กันเคสซ้ำ /api
|
||||
function buildLoginUrl() {
|
||||
const base = (process.env.NEXT_PUBLIC_API_BASE || "").replace(/\/+$/, "");
|
||||
if (base.endsWith("/api")) return `${base}/auth/login`;
|
||||
return `${base}/api/auth/login`;
|
||||
}
|
||||
|
||||
// helper: parse response body เป็น json หรือ text
|
||||
async function parseBody(res) {
|
||||
const text = await res.text();
|
||||
try {
|
||||
return { raw: text, json: JSON.parse(text) };
|
||||
} catch {
|
||||
return { raw: text, json: null };
|
||||
}
|
||||
}
|
||||
|
||||
// สร้างข้อความ debug ที่พร้อม copy
|
||||
function stringifyDebug(debugInfo) {
|
||||
try {
|
||||
return JSON.stringify(debugInfo, null, 2);
|
||||
} catch {
|
||||
return String(debugInfo);
|
||||
}
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const search = useSearchParams();
|
||||
const redirectTo = search.get("from") || "/dashboard";
|
||||
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
// สำหรับ debug panel
|
||||
const [debugInfo, setDebugInfo] = useState(null);
|
||||
const [copyState, setCopyState] = useState({ copied: false, error: "" });
|
||||
|
||||
const loginUrl = useMemo(buildLoginUrl, [process.env.NEXT_PUBLIC_API_BASE]);
|
||||
|
||||
async function onSubmit(e) {
|
||||
e.preventDefault();
|
||||
setSubmitting(true);
|
||||
setError("");
|
||||
if (IS_DEV) {
|
||||
setDebugInfo(null);
|
||||
setCopyState({ copied: false, error: "" });
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(loginUrl, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const body = await parseBody(res);
|
||||
|
||||
const apiErr = {
|
||||
name: "ApiError",
|
||||
status: res.status,
|
||||
statusText: res.statusText,
|
||||
body: body.json ?? body.raw,
|
||||
message: (() => {
|
||||
const msgFromJson =
|
||||
(body.json && (body.json.error || body.json.message)) || null;
|
||||
|
||||
if (res.status === 400)
|
||||
return `Bad request: ${msgFromJson ?? res.statusText}`;
|
||||
if (res.status === 401)
|
||||
return `Unauthenticated: ${msgFromJson ?? "Invalid credentials"}`;
|
||||
if (res.status === 403)
|
||||
return `Forbidden: ${msgFromJson ?? res.statusText}`;
|
||||
if (res.status === 404)
|
||||
return `Not found: ${msgFromJson ?? res.statusText}`;
|
||||
if (res.status >= 500)
|
||||
return `Server error (${res.status}): ${
|
||||
msgFromJson ?? res.statusText
|
||||
}`;
|
||||
return `${res.status} ${res.statusText}: ${
|
||||
msgFromJson ?? "Request failed"
|
||||
}`;
|
||||
})(),
|
||||
};
|
||||
|
||||
if (IS_DEV) {
|
||||
setDebugInfo({
|
||||
kind: "api",
|
||||
request: {
|
||||
url: loginUrl,
|
||||
method: "POST",
|
||||
payload: { username: "(masked)", password: "(masked)" },
|
||||
},
|
||||
response: {
|
||||
status: res.status,
|
||||
statusText: res.statusText,
|
||||
body: apiErr.body,
|
||||
},
|
||||
env: {
|
||||
NEXT_PUBLIC_API_BASE:
|
||||
process.env.NEXT_PUBLIC_API_BASE || "(unset)",
|
||||
NODE_ENV: process.env.NODE_ENV,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
throw apiErr;
|
||||
}
|
||||
|
||||
// ✅ สำเร็จ
|
||||
if (IS_DEV) {
|
||||
setDebugInfo({
|
||||
kind: "success",
|
||||
request: { url: loginUrl, method: "POST" },
|
||||
note: "Login success. Redirecting…",
|
||||
});
|
||||
}
|
||||
router.push(redirectTo);
|
||||
} catch (err) {
|
||||
if (err?.name === "ApiError") {
|
||||
setError(err.message);
|
||||
} else if (err instanceof TypeError && /fetch/i.test(err.message)) {
|
||||
setError(
|
||||
"Network error: ไม่สามารถเชื่อมต่อเซิร์ฟเวอร์ได้ (ตรวจสอบ proxy/NPM/SSL)"
|
||||
);
|
||||
if (IS_DEV) {
|
||||
setDebugInfo({
|
||||
kind: "network",
|
||||
request: { url: loginUrl, method: "POST" },
|
||||
error: { message: err.message },
|
||||
hint: "เช็คว่า NPM ชี้ proxy /api ไปที่ backend ถูก network/port, และ TLS chain ถูกต้อง",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
setError(err?.message || "Unexpected error");
|
||||
if (IS_DEV) {
|
||||
setDebugInfo({
|
||||
kind: "unknown",
|
||||
request: { url: loginUrl, method: "POST" },
|
||||
error: { message: String(err) },
|
||||
});
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCopyDebug() {
|
||||
if (!debugInfo) return;
|
||||
const text = stringifyDebug(debugInfo);
|
||||
try {
|
||||
if (navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} else {
|
||||
// Fallback
|
||||
const ta = document.createElement("textarea");
|
||||
ta.value = text;
|
||||
ta.style.position = "fixed";
|
||||
ta.style.left = "-9999px";
|
||||
document.body.appendChild(ta);
|
||||
ta.focus();
|
||||
ta.select();
|
||||
document.execCommand("copy");
|
||||
document.body.removeChild(ta);
|
||||
}
|
||||
setCopyState({ copied: true, error: "" });
|
||||
setTimeout(() => setCopyState({ copied: false, error: "" }), 1500);
|
||||
} catch (e) {
|
||||
setCopyState({
|
||||
copied: false,
|
||||
error: "คัดลอกไม่สำเร็จ (permission ของ clipboard?)",
|
||||
});
|
||||
setTimeout(() => setCopyState({ copied: false, error: "" }), 2500);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="mx-auto w-full max-w-md shadow-lg">
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl text-sky-800">Sign in</CardTitle>
|
||||
<CardDescription>
|
||||
Enter your credentials to access the DMS
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-4">
|
||||
{error ? (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
|
||||
<form onSubmit={onSubmit} className="space-y-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="username">Username</Label>
|
||||
<Input
|
||||
id="username"
|
||||
autoComplete="username"
|
||||
placeholder="superadmin"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
placeholder="••••••••"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full" disabled={submitting}>
|
||||
{submitting ? "Signing in..." : "Sign in"}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{IS_DEV && (
|
||||
<div className="mt-4 rounded-xl border border-sky-200 bg-sky-50 p-3">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<div className="text-sm font-semibold text-sky-900">
|
||||
Debug (dev mode only)
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={handleCopyDebug}
|
||||
disabled={!debugInfo}
|
||||
aria-label="Copy debug info"
|
||||
>
|
||||
{copyState.copied ? "Copied!" : "Copy debug"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Separator className="my-2" />
|
||||
<div className="space-y-2 text-xs text-sky-900">
|
||||
<div>
|
||||
<span className="font-medium">Request URL:</span>{" "}
|
||||
<code className="break-all">{loginUrl}</code>
|
||||
</div>
|
||||
|
||||
{debugInfo?.request?.method && (
|
||||
<div>
|
||||
<span className="font-medium">Method:</span>{" "}
|
||||
<code>{debugInfo.request.method}</code>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{debugInfo?.response && (
|
||||
<>
|
||||
<div>
|
||||
<span className="font-medium">Status:</span>{" "}
|
||||
<code>
|
||||
{debugInfo.response.status}{" "}
|
||||
{debugInfo.response.statusText}
|
||||
</code>
|
||||
</div>
|
||||
<div className="font-medium">Response body:</div>
|
||||
<pre className="max-h-48 overflow-auto rounded bg-white p-2">
|
||||
{typeof debugInfo.response.body === "string"
|
||||
? debugInfo.response.body
|
||||
: JSON.stringify(debugInfo.response.body, null, 2)}
|
||||
</pre>
|
||||
</>
|
||||
)}
|
||||
|
||||
{debugInfo?.error && (
|
||||
<>
|
||||
<div className="font-medium">Error:</div>
|
||||
<pre className="max-h-48 overflow-auto rounded bg-white p-2">
|
||||
{JSON.stringify(debugInfo.error, null, 2)}
|
||||
</pre>
|
||||
</>
|
||||
)}
|
||||
|
||||
{debugInfo?.env && (
|
||||
<>
|
||||
<div className="font-medium">Env:</div>
|
||||
<pre className="max-h-40 overflow-auto rounded bg-white p-2">
|
||||
{JSON.stringify(debugInfo.env, null, 2)}
|
||||
</pre>
|
||||
</>
|
||||
)}
|
||||
|
||||
{debugInfo?.note && (
|
||||
<div className="italic text-sky-700">{debugInfo.note}</div>
|
||||
)}
|
||||
{debugInfo?.hint && (
|
||||
<div className="italic text-sky-700">
|
||||
Hint: {debugInfo.hint}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{copyState.error && (
|
||||
<div className="text-red-600">{copyState.error}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
<CardFooter className="justify-center text-xs text-gray-500">
|
||||
© {new Date().getFullYear()} np-dms.work
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -19,7 +19,188 @@ import { Separator } from "@/components/ui/separator";
|
||||
|
||||
const IS_DEV = process.env.NODE_ENV !== "production";
|
||||
|
||||
// URL builder กันเคสซ้ำ /api
|
||||
// URL builder กันเคสซ้ำ /api"use client";
|
||||
|
||||
import { useState, useMemo } from "react";
|
||||
import { useSearchParams, useRouter } from "next/navigation";
|
||||
import { 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";
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
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("");
|
||||
|
||||
async function onSubmit(e) {
|
||||
e.preventDefault();
|
||||
setErr("");
|
||||
|
||||
if (!username.trim() || !password) {
|
||||
setErr("กรอกชื่อผู้ใช้และรหัสผ่านให้ครบ");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setSubmitting(true);
|
||||
|
||||
// เรียก backend ให้ตั้ง HttpOnly cookie: access_token
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE}/api/auth/login`, {
|
||||
method: "POST",
|
||||
credentials: "include", // สำคัญ: รับ/ส่งคุกกี้
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password, remember }),
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
setErr(data?.message || "ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง");
|
||||
return;
|
||||
}
|
||||
|
||||
// สำเร็จ → backend ตั้งคุกกี้แล้ว → redirect
|
||||
router.replace(nextPath);
|
||||
} catch (e) {
|
||||
setErr("เชื่อมต่อเซิร์ฟเวอร์ไม่ได้ กรุณาลองใหม่");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<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>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent>
|
||||
{err ? (
|
||||
<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}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<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"
|
||||
/>
|
||||
<button
|
||||
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}
|
||||
>
|
||||
{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"
|
||||
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>
|
||||
</form>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter className="text-xs text-center text-slate-500">
|
||||
© {new Date().getFullYear()} np-dms.work
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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>
|
||||
);
|
||||
}
|
||||
|
||||
function buildLoginUrl() {
|
||||
const base = (process.env.NEXT_PUBLIC_API_BASE || "").replace(/\/+$/, "");
|
||||
if (base.endsWith("/api")) return `${base}/auth/login`;
|
||||
@@ -201,7 +382,7 @@ export default function LoginPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="mx-auto w-full max-w-md shadow-lg">
|
||||
<Card className="w-full max-w-md mx-auto shadow-lg">
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl text-sky-800">Sign in</CardTitle>
|
||||
<CardDescription>
|
||||
@@ -248,8 +429,8 @@ export default function LoginPage() {
|
||||
</form>
|
||||
|
||||
{IS_DEV && (
|
||||
<div className="mt-4 rounded-xl border border-sky-200 bg-sky-50 p-3">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<div className="p-3 mt-4 border rounded-xl border-sky-200 bg-sky-50">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<div className="text-sm font-semibold text-sky-900">
|
||||
Debug (dev mode only)
|
||||
</div>
|
||||
@@ -290,7 +471,7 @@ export default function LoginPage() {
|
||||
</code>
|
||||
</div>
|
||||
<div className="font-medium">Response body:</div>
|
||||
<pre className="max-h-48 overflow-auto rounded bg-white p-2">
|
||||
<pre className="p-2 overflow-auto bg-white rounded max-h-48">
|
||||
{typeof debugInfo.response.body === "string"
|
||||
? debugInfo.response.body
|
||||
: JSON.stringify(debugInfo.response.body, null, 2)}
|
||||
@@ -301,7 +482,7 @@ export default function LoginPage() {
|
||||
{debugInfo?.error && (
|
||||
<>
|
||||
<div className="font-medium">Error:</div>
|
||||
<pre className="max-h-48 overflow-auto rounded bg-white p-2">
|
||||
<pre className="p-2 overflow-auto bg-white rounded max-h-48">
|
||||
{JSON.stringify(debugInfo.error, null, 2)}
|
||||
</pre>
|
||||
</>
|
||||
@@ -310,7 +491,7 @@ export default function LoginPage() {
|
||||
{debugInfo?.env && (
|
||||
<>
|
||||
<div className="font-medium">Env:</div>
|
||||
<pre className="max-h-40 overflow-auto rounded bg-white p-2">
|
||||
<pre className="p-2 overflow-auto bg-white rounded max-h-40">
|
||||
{JSON.stringify(debugInfo.env, null, 2)}
|
||||
</pre>
|
||||
</>
|
||||
|
||||
Reference in New Issue
Block a user