import * as React from "react" import { ArrowLeftIcon, EyeIcon, EyeOffIcon, FileKeyIcon, Loader2Icon } from "lucide-react" import { Button } from "../ui/button" import { Input } from "../ui/input" import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "../ui/input-group" import { InputOTP, InputOTPGroup, InputOTPSlot } from "../ui/input-otp" import { cn } from "../lib/utils" import { FormField } from "./form-field" export interface LoginCredentials { login: string password: string } /** Второй шаг входа: у пользователя включён одноразовый код. */ export interface OtpChallenge { /** Число цифр в коде, по умолчанию 6. */ length?: number /** Куда отправлен код («+7 *** ***-45-67»). Без него — код из приложения-аутентификатора, без повторной отправки. */ destination?: string /** Через сколько секунд можно запросить код повторно, по умолчанию 60. */ resendIn?: number } export interface LoginFormProps { title?: React.ReactNode description?: React.ReactNode /** Слот над заголовком — знак продукта. */ logo?: React.ReactNode defaultLogin?: string /** Фокус в поле при показе (логин, а если он подставлен — пароль). По умолчанию включён. */ autoFocus?: boolean /** Вернуть OtpChallenge — форма перейдёт к вводу кода. Ошибка — `throw new Error("текст")`. */ onLogin: (credentials: LoginCredentials) => Promise onVerifyOtp?: (code: string) => Promise onResendOtp?: () => Promise /** Кнопка «Войти по электронной подписи»; выбор сертификата — на стороне приложения. */ onSignature?: () => Promise className?: string } type Pending = "login" | "signature" | "otp" | "resend" | null function errorText(e: unknown) { return e instanceof Error && e.message ? e.message : "Не удалось войти. Попробуйте ещё раз." } function formatCountdown(sec: number) { return `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, "0")}` } /** * Форма входа: логин и пароль, вход по электронной подписи, второй шаг с одноразовым кодом. * Без своей рамки — фон и раскладку задаёт страница. */ export function LoginForm({ title = "Вход в систему", description, logo, defaultLogin = "", autoFocus = true, onLogin, onVerifyOtp, onResendOtp, onSignature, className, }: LoginFormProps) { const [login, setLogin] = React.useState(defaultLogin) const [password, setPassword] = React.useState("") const [showPassword, setShowPassword] = React.useState(false) const [capsLock, setCapsLock] = React.useState(false) const [challenge, setChallenge] = React.useState(null) const [code, setCode] = React.useState("") const [resendLeft, setResendLeft] = React.useState(0) const [pending, setPending] = React.useState(null) const [error, setError] = React.useState() const busy = pending !== null const otpLength = challenge?.length ?? 6 React.useEffect(() => { if (resendLeft <= 0) return const timer = setTimeout(() => setResendLeft((s) => s - 1), 1000) return () => clearTimeout(timer) }, [resendLeft]) async function run(kind: Exclude, action: () => Promise) { setPending(kind) setError(undefined) try { return { ok: true as const, value: await action() } } catch (e) { setError(errorText(e)) return { ok: false as const } } finally { setPending(null) } } function startOtp(next: void | OtpChallenge) { if (!next) return setChallenge(next) setCode("") setResendLeft(next.resendIn ?? 60) } async function submitLogin() { if (busy || !login.trim() || !password) return const result = await run("login", () => onLogin({ login: login.trim(), password })) if (result.ok) startOtp(result.value) } async function submitSignature() { if (busy || !onSignature) return const result = await run("signature", onSignature) if (result.ok) startOtp(result.value) } async function submitOtp(value = code) { if (busy || !onVerifyOtp || value.length < otpLength) return const result = await run("otp", () => onVerifyOtp(value)) if (!result.ok) setCode("") } async function resend() { if (busy || !onResendOtp) return const result = await run("resend", onResendOtp) if (result.ok) setResendLeft(challenge?.resendIn ?? 60) } function back() { setChallenge(null) setPassword("") setCode("") setError(undefined) } const spinner = if (challenge) { return (
Отправили код на {challenge.destination} ) : ( "Введите код из приложения-аутентификатора" ) } />
{ e.preventDefault() void submitOtp() }} > { setCode(v) setError(undefined) }} onComplete={(v: string) => void submitOtp(v)} disabled={pending === "otp"} autoFocus autoComplete="one-time-code" inputMode="numeric" pattern="^[0-9]*$" aria-label="Одноразовый код" containerClassName="justify-center" > {Array.from({ length: otpLength }, (_, i) => ( ))} {error &&

{error}

}
{challenge.destination && onResendOtp && ( resendLeft > 0 ? ( Повторно — через {formatCountdown(resendLeft)} ) : ( ) )}
) } return (
{ e.preventDefault() void submitLogin() }} > { setLogin(e.target.value) setError(undefined) }} disabled={busy} /> { setPassword(e.target.value) setError(undefined) }} onKeyDown={(e) => setCapsLock(e.getModifierState("CapsLock"))} onKeyUp={(e) => setCapsLock(e.getModifierState("CapsLock"))} onBlur={() => setCapsLock(false)} aria-invalid={Boolean(error)} disabled={busy} /> setShowPassword((v) => !v)} disabled={busy} > {showPassword ? : } {error &&

{error}

} {onSignature && ( <>
или
)}
) } function LoginHeader({ logo, title, description, }: { logo?: React.ReactNode title: React.ReactNode description?: React.ReactNode }) { return (
{logo &&
{logo}
}

{title}

{description &&

{description}

}
) }