314 lines
11 KiB
TypeScript
314 lines
11 KiB
TypeScript
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<void | OtpChallenge>
|
||
onVerifyOtp?: (code: string) => Promise<void>
|
||
onResendOtp?: () => Promise<void>
|
||
/** Кнопка «Войти по электронной подписи»; выбор сертификата — на стороне приложения. */
|
||
onSignature?: () => Promise<void | OtpChallenge>
|
||
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<OtpChallenge | null>(null)
|
||
const [code, setCode] = React.useState("")
|
||
const [resendLeft, setResendLeft] = React.useState(0)
|
||
const [pending, setPending] = React.useState<Pending>(null)
|
||
const [error, setError] = React.useState<string>()
|
||
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<T>(kind: Exclude<Pending, null>, action: () => Promise<T>) {
|
||
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 = <Loader2Icon className="animate-spin" />
|
||
|
||
if (challenge) {
|
||
return (
|
||
<div className={cn("w-full max-w-sm space-y-6", className)}>
|
||
<LoginHeader
|
||
logo={logo}
|
||
title="Код подтверждения"
|
||
description={
|
||
challenge.destination ? (
|
||
<>
|
||
Отправили код на <span className="font-medium text-foreground">{challenge.destination}</span>
|
||
</>
|
||
) : (
|
||
"Введите код из приложения-аутентификатора"
|
||
)
|
||
}
|
||
/>
|
||
<form
|
||
noValidate
|
||
className="space-y-4"
|
||
onSubmit={(e) => {
|
||
e.preventDefault()
|
||
void submitOtp()
|
||
}}
|
||
>
|
||
<InputOTP
|
||
maxLength={otpLength}
|
||
value={code}
|
||
onChange={(v) => {
|
||
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"
|
||
>
|
||
<InputOTPGroup>
|
||
{Array.from({ length: otpLength }, (_, i) => (
|
||
<InputOTPSlot key={i} index={i} aria-invalid={Boolean(error)} className="h-11 w-10 text-base" />
|
||
))}
|
||
</InputOTPGroup>
|
||
</InputOTP>
|
||
|
||
{error && <p className="text-center text-sm text-destructive">{error}</p>}
|
||
|
||
<Button type="submit" size="lg" className="w-full" disabled={busy || code.length < otpLength}>
|
||
{pending === "otp" && spinner} Подтвердить
|
||
</Button>
|
||
|
||
<div className="flex items-center justify-between gap-2 text-sm">
|
||
<Button type="button" variant="ghost" size="sm" className="-ml-2.5" onClick={back} disabled={busy}>
|
||
<ArrowLeftIcon /> Назад
|
||
</Button>
|
||
{challenge.destination && onResendOtp && (
|
||
resendLeft > 0 ? (
|
||
<span className="text-muted-foreground tabular">
|
||
Повторно — через {formatCountdown(resendLeft)}
|
||
</span>
|
||
) : (
|
||
<Button type="button" variant="link" size="sm" className="-mr-3" onClick={resend} disabled={busy}>
|
||
{pending === "resend" && spinner} Отправить код повторно
|
||
</Button>
|
||
)
|
||
)}
|
||
</div>
|
||
</form>
|
||
</div>
|
||
)
|
||
}
|
||
|
||
return (
|
||
<div className={cn("w-full max-w-sm space-y-6", className)}>
|
||
<LoginHeader logo={logo} title={title} description={description} />
|
||
<form
|
||
noValidate
|
||
className="space-y-4"
|
||
onSubmit={(e) => {
|
||
e.preventDefault()
|
||
void submitLogin()
|
||
}}
|
||
>
|
||
<FormField label="Логин" htmlFor="login-form-login">
|
||
<Input
|
||
id="login-form-login"
|
||
autoComplete="username"
|
||
autoFocus={autoFocus && !defaultLogin}
|
||
value={login}
|
||
onChange={(e) => {
|
||
setLogin(e.target.value)
|
||
setError(undefined)
|
||
}}
|
||
disabled={busy}
|
||
/>
|
||
</FormField>
|
||
|
||
<FormField
|
||
label="Пароль"
|
||
htmlFor="login-form-password"
|
||
hint={capsLock ? "Включён Caps Lock" : undefined}
|
||
>
|
||
<InputGroup data-disabled={busy || undefined}>
|
||
<InputGroupInput
|
||
id="login-form-password"
|
||
type={showPassword ? "text" : "password"}
|
||
autoComplete="current-password"
|
||
autoFocus={autoFocus && Boolean(defaultLogin)}
|
||
value={password}
|
||
onChange={(e) => {
|
||
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}
|
||
/>
|
||
<InputGroupAddon align="inline-end">
|
||
<InputGroupButton
|
||
size="icon-xs"
|
||
aria-label={showPassword ? "Скрыть пароль" : "Показать пароль"}
|
||
onClick={() => setShowPassword((v) => !v)}
|
||
disabled={busy}
|
||
>
|
||
{showPassword ? <EyeOffIcon /> : <EyeIcon />}
|
||
</InputGroupButton>
|
||
</InputGroupAddon>
|
||
</InputGroup>
|
||
</FormField>
|
||
|
||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||
|
||
<Button type="submit" size="lg" className="w-full" disabled={busy || !login.trim() || !password}>
|
||
{pending === "login" && spinner} Войти
|
||
</Button>
|
||
|
||
{onSignature && (
|
||
<>
|
||
<div className="flex items-center gap-3 text-xs text-muted-foreground">
|
||
<span className="h-px flex-1 bg-border" />
|
||
или
|
||
<span className="h-px flex-1 bg-border" />
|
||
</div>
|
||
<Button type="button" variant="outline" size="lg" className="w-full" onClick={submitSignature} disabled={busy}>
|
||
{pending === "signature" ? spinner : <FileKeyIcon />} Войти по электронной подписи
|
||
</Button>
|
||
</>
|
||
)}
|
||
</form>
|
||
</div>
|
||
)
|
||
}
|
||
|
||
function LoginHeader({
|
||
logo,
|
||
title,
|
||
description,
|
||
}: {
|
||
logo?: React.ReactNode
|
||
title: React.ReactNode
|
||
description?: React.ReactNode
|
||
}) {
|
||
return (
|
||
<div className="space-y-2 text-center">
|
||
{logo && <div className="mb-4 flex justify-center">{logo}</div>}
|
||
<h1 className="text-xl font-semibold tracking-tight">{title}</h1>
|
||
{description && <p className="text-sm text-muted-foreground">{description}</p>}
|
||
</div>
|
||
)
|
||
}
|