83 lines
2.8 KiB
TypeScript
83 lines
2.8 KiB
TypeScript
"use client";
|
|
|
|
import { useState } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
import { login, AuthError } from "@duoc-thu/api-client";
|
|
|
|
export default function AdminLoginPage() {
|
|
const router = useRouter();
|
|
const [username, setUsername] = useState("");
|
|
const [password, setPassword] = useState("");
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [pending, setPending] = useState(false);
|
|
|
|
async function onSubmit(event: React.FormEvent) {
|
|
event.preventDefault();
|
|
setError(null);
|
|
setPending(true);
|
|
try {
|
|
const user = await login({ username, password });
|
|
if (user.role !== "admin") {
|
|
setError("Tài khoản này không có quyền quản trị.");
|
|
return;
|
|
}
|
|
router.push("/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);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className="flex flex-1 items-center justify-center p-6">
|
|
<form
|
|
onSubmit={onSubmit}
|
|
className="w-full max-w-sm space-y-4 rounded-2xl border border-border-subtle bg-surface p-6 shadow-sm"
|
|
>
|
|
<h1 className="text-lg font-bold text-txt-primary">Đăng nhập quản trị</h1>
|
|
<div className="space-y-1">
|
|
<label className="text-xs font-semibold text-txt-secondary" htmlFor="username">
|
|
Tên đăng nhập
|
|
</label>
|
|
<input
|
|
id="username"
|
|
className="w-full rounded-lg border border-border-subtle bg-app px-3 py-2 text-sm text-txt-primary"
|
|
value={username}
|
|
onChange={(e) => setUsername(e.target.value)}
|
|
autoComplete="username"
|
|
required
|
|
/>
|
|
</div>
|
|
<div className="space-y-1">
|
|
<label className="text-xs font-semibold text-txt-secondary" htmlFor="password">
|
|
Mật khẩu
|
|
</label>
|
|
<input
|
|
id="password"
|
|
type="password"
|
|
className="w-full rounded-lg border border-border-subtle bg-app px-3 py-2 text-sm text-txt-primary"
|
|
value={password}
|
|
onChange={(e) => setPassword(e.target.value)}
|
|
autoComplete="current-password"
|
|
required
|
|
/>
|
|
</div>
|
|
{error && <p className="text-xs font-medium text-status-danger">{error}</p>}
|
|
<button
|
|
type="submit"
|
|
disabled={pending}
|
|
className="w-full rounded-lg bg-accent-primary py-2 text-sm font-semibold text-txt-inverse disabled:opacity-60"
|
|
>
|
|
{pending ? "Đang đăng nhập..." : "Đăng nhập"}
|
|
</button>
|
|
</form>
|
|
</div>
|
|
);
|
|
}
|