Files
co-lite/solvway-admin-portal/app/login/page.tsx
T

147 lines
6.2 KiB
TypeScript

"use client";
import { useState, useSyncExternalStore } from "react";
import { Eye, EyeOff, Loader2 } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Button } from "@/app/components/ui/button";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { ErrorState } from "@/app/components/ui/states";
import { ApiError, apiPost } from "@/app/lib/clientApi";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import AuthFrame from "@/app/components/app/AuthFrame";
import { signedInElsewhere } from "@/app/lib/signedInElsewhere";
import { safeReturnTo } from "@/app/lib/returnTo";
/** The marker is read once per render; nothing in the page changes it. */
const noSubscription = () => () => {};
// Ported from src/legacy-pages/login/LoginPage.tsx. The hardcoded
// services/auth.ts credential check and localStorage session are gone (spec:
// "The hardcoded SPA auth is gone"); submit now calls the same-origin
// /api/auth/login route, which proxies solvway-mobile-api and sets the
// httpOnly colite_admin cookie server-side.
export default function LoginPage() {
const router = useRouter();
const { refresh } = useAdminAuth();
const t = useT();
const [company, setCompany] = useState("");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [error, setError] = useState<string | null>(null);
// one-session-per-account: a newer sign-in of this account ended the previous session in this browser.
// Read after hydration (the server renders without it), so server and client markup agree.
const elsewhere = useSyncExternalStore(noSubscription, () => signedInElsewhere(document.cookie), () => false);
const [submitting, setSubmitting] = useState(false);
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
setError(null);
setSubmitting(true);
try {
const res = await apiPost<{ name: string; resetPasswordRequired: boolean }>("/api/auth/login", {
company: company.trim() || undefined,
username,
password,
});
// Session hydration (roles/aclMenu) is not part of the login response
// (spec: "The ACL tree is not stored in the cookie") — refresh() re-runs
// GET /api/auth/session so the sidebar/header have it before we
// navigate, avoiding a stale flash on the redirect target.
await refresh();
// A new account (login flag N) must set its own password first.
// admin-login-return-to: otherwise back to the page the admin was sent away from.
router.replace(res.resetPasswordRequired ? "/reset-password"
: safeReturnTo(new URLSearchParams(window.location.search).get("returnTo")));
// replace keeps the root layout, whose locale list was loaded without a token; re-run it.
router.refresh();
} catch (err) {
const locked = err instanceof ApiError && (err.data as { code?: unknown } | undefined)?.code === "ACCOUNT_LOCKED";
setError(locked ? "LoginAccountLocked" : err instanceof Error ? err.message : "LoginInvalidCredentials");
} finally {
setSubmitting(false);
}
}
return (
<AuthFrame>
<div className="space-y-2">
<h1 className="font-heading text-3xl font-semibold tracking-tight">{t("BackOfficeTitle")}</h1>
<p className="text-muted-foreground">{t("BackOfficeSubtitle")}</p>
</div>
{error ? <ErrorState message={t(error)} /> : elsewhere && <ErrorState message={t("SignedInElsewhere")} />}
<form onSubmit={handleSubmit} className="space-y-5" noValidate>
<div className="space-y-1.5">
<Label htmlFor="company">{t("Company")}</Label>
<Input
id="company"
type="text"
autoComplete="organization"
placeholder={t("CompanyBlankForSuper")}
value={company}
onChange={(e) => setCompany(e.target.value)}
disabled={submitting}
className="h-11 bg-card"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="username">{t("Username")}</Label>
<Input
id="username"
type="text"
autoComplete="username"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
disabled={submitting}
className="h-11 bg-card"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="password">{t("Password")}</Label>
<div className="relative">
<Input
id="password"
type={showPassword ? "text" : "password"}
autoComplete="current-password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={submitting}
className="h-11 bg-card pr-11"
/>
<button
type="button"
onClick={() => setShowPassword((v) => !v)}
aria-label={showPassword ? t("LoginHidePassword") : t("LoginShowPassword")}
className="absolute top-1/2 right-1 flex size-9 -translate-y-1/2 cursor-pointer items-center justify-center rounded-full text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
>
{showPassword ? (
<EyeOff aria-hidden="true" className="size-4" />
) : (
<Eye aria-hidden="true" className="size-4" />
)}
</button>
</div>
</div>
<Link href="/forgot-password" className="block text-sm text-muted-foreground underline-offset-4 hover:underline">
{t("ForgotLink")}
</Link>
<Button type="submit" className="h-11 w-full text-base shadow-md" disabled={submitting}>
{submitting && <Loader2 aria-hidden="true" className="size-4 animate-spin" />}
{t("LogIn")}
</Button>
</form>
</AuthFrame>
);
}