"use client"; import { useState } from "react"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { login, AuthError } from "@duoc-thu/api-client"; interface LoginFormProps { heading: string; /** `/admin/login` sets this. It changes only where a successful login * lands and what a non-admin is told afterwards -- never whether the * login itself is allowed to happen, which is auth-service's call. */ requireAdmin?: boolean; } /** * Shared by `/login` (any doctor) and `/admin/login` (administrators). * * The two pages used to be one page, and it only served admins: `AccountMenu` * pointed its "Đăng nhập" button at `/admin/login`, so a doctor signing in * from the chat UI with a `user` account got a red "Tài khoản này không có * quyền quản trị" while the header beside it switched to their name. Both were * accurate and together they were nonsense -- the login had succeeded and the * session cookie was already set; only the admin redirect had not happened. * * So a non-admin result is reported here as what it is: signed in, without * administrative rights. Not an error, and not silently swallowed either. */ export function LoginForm({ heading, requireAdmin = false }: LoginFormProps) { const router = useRouter(); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(null); const [signedInAs, setSignedInAs] = useState(null); const [pending, setPending] = useState(false); async function onSubmit(event: React.FormEvent) { event.preventDefault(); setError(null); setSignedInAs(null); setPending(true); try { const user = await login({ username, password }); if (requireAdmin && user.role !== "admin") { // Signed in, just not an administrator. Say so plainly and offer the // way onward rather than leaving them on a dead form. setSignedInAs(user.username); return; } router.push(user.role === "admin" && requireAdmin ? "/admin" : "/"); router.refresh(); } catch (err) { setError( err instanceof AuthError && err.status === 401 ? "Sai tên đăng nhập hoặc mật khẩu." : "Không thể đăng nhập lúc này. Vui lòng thử lại." ); } finally { setPending(false); } } if (signedInAs) { return (

Đã đăng nhập với tài khoản {signedInAs}

Tài khoản này không có quyền quản trị, nhưng bạn đã đăng nhập và có thể tra cứu bình thường.

Vào trang tra cứu
); } return (

{heading}

setUsername(e.target.value)} autoComplete="username" required />
setPassword(e.target.value)} autoComplete="current-password" required />
{error &&

{error}

} {!requireAdmin && (

Không bắt buộc — bạn vẫn tra cứu được mà không cần đăng nhập.

)}
); }