2026-09-19 21:50:06 +03:00
|
|
|
|
import { useState, type FormEvent } from 'react';
|
2026-09-26 15:12:43 +03:00
|
|
|
|
import { useMutation, useQuery } from '@tanstack/react-query';
|
2026-09-19 21:50:06 +03:00
|
|
|
|
import { useTranslation } from 'react-i18next';
|
2026-09-21 19:25:06 +03:00
|
|
|
|
import { Link, useLocation, useNavigate, useSearchParams } from 'react-router';
|
2026-09-19 21:50:06 +03:00
|
|
|
|
|
|
|
|
|
|
import { login } from '@/api/auth';
|
2026-09-26 15:12:43 +03:00
|
|
|
|
import { fetchMeta, metaQueryKey } from '@/api/meta';
|
|
|
|
|
|
import { loginWithPasskey } from '@/api/passkeys';
|
2026-09-19 21:50:06 +03:00
|
|
|
|
import { ErrorNotice } from '@/components/ui/ErrorNotice';
|
|
|
|
|
|
import { Field } from '@/components/ui/Field';
|
|
|
|
|
|
import { Button, Card } from '@/components/ui/primitives';
|
|
|
|
|
|
import { getQueryClient } from '@/lib/queryClient';
|
|
|
|
|
|
import { useInstance } from '@/lib/hooks';
|
|
|
|
|
|
import { errorCode } from '@/lib/format';
|
2026-09-26 15:12:43 +03:00
|
|
|
|
import { isPasskeySupported, WebAuthnClientError } from '@/lib/webauthn';
|
2026-09-22 21:52:16 +03:00
|
|
|
|
import { useGatewayStore } from '@/stores/gateway';
|
2026-09-19 21:50:06 +03:00
|
|
|
|
|
|
|
|
|
|
interface LocationState {
|
|
|
|
|
|
from?: string;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-20 01:11:04 +03:00
|
|
|
|
/**
|
|
|
|
|
|
* Форма входа. Поле кода 2FA показывается всегда: сервер принимает и код из
|
|
|
|
|
|
* приложения (6 цифр), и резервный код вида `a8eh-pshp-t8st`, а при попытке
|
|
|
|
|
|
* входа без кода отвечает `auth.2fa_required` — тогда подсказываем про код.
|
2026-09-26 15:12:43 +03:00
|
|
|
|
*
|
2026-09-26 15:13:24 +03:00
|
|
|
|
* Дополнительно (Фаза 7): вход по ключу доступа (passkeys) и кнопки внешних
|
|
|
|
|
|
* провайдеров, включённых на инстансе.
|
2026-09-20 01:11:04 +03:00
|
|
|
|
*/
|
2026-09-19 21:50:06 +03:00
|
|
|
|
export default function LoginPage() {
|
|
|
|
|
|
const { t } = useTranslation();
|
|
|
|
|
|
const navigate = useNavigate();
|
|
|
|
|
|
const location = useLocation();
|
|
|
|
|
|
const instance = useInstance();
|
|
|
|
|
|
|
|
|
|
|
|
const [email, setEmail] = useState('');
|
|
|
|
|
|
const [password, setPassword] = useState('');
|
|
|
|
|
|
const [totpCode, setTotpCode] = useState('');
|
|
|
|
|
|
const [needsTotp, setNeedsTotp] = useState(false);
|
2026-09-21 19:25:06 +03:00
|
|
|
|
const [searchParams] = useSearchParams();
|
2026-09-19 21:50:06 +03:00
|
|
|
|
|
2026-09-21 19:25:06 +03:00
|
|
|
|
// Возврат после входа: `?next=` (страница приглашения) важнее состояния
|
|
|
|
|
|
// перехода из AuthGuard, но только для внутренних путей.
|
|
|
|
|
|
const next = searchParams.get('next');
|
|
|
|
|
|
const stateFrom = (location.state as LocationState | null)?.from ?? null;
|
|
|
|
|
|
const from = next !== null && next.startsWith('/') ? next : (stateFrom ?? '/app');
|
2026-09-19 21:50:06 +03:00
|
|
|
|
|
2026-09-26 15:12:43 +03:00
|
|
|
|
// Признак доступности passkeys берём из меты инстанса: на IP-адресе (стенд
|
|
|
|
|
|
// без домена) WebAuthn невозможен, и кнопку показывать нельзя.
|
|
|
|
|
|
const meta = useQuery({
|
|
|
|
|
|
queryKey: metaQueryKey,
|
|
|
|
|
|
queryFn: ({ signal }) => fetchMeta(signal),
|
|
|
|
|
|
staleTime: 60_000,
|
|
|
|
|
|
});
|
|
|
|
|
|
const passkeySupported = isPasskeySupported() && meta.data?.features.passkeys_enabled === true;
|
|
|
|
|
|
|
|
|
|
|
|
const finishLogin = async (): Promise<void> => {
|
|
|
|
|
|
// Профиль перечитываем заново: cookie уже выставлена сервером. Признак
|
|
|
|
|
|
// отозванной сессии снимаем — иначе AuthGuard увёл бы обратно на /login.
|
|
|
|
|
|
useGatewayStore.getState().reset();
|
|
|
|
|
|
await getQueryClient().invalidateQueries();
|
|
|
|
|
|
void navigate(from === '/login' ? '/app' : from, { replace: true });
|
|
|
|
|
|
};
|
|
|
|
|
|
|
2026-09-19 21:50:06 +03:00
|
|
|
|
const submit = useMutation({
|
2026-09-20 01:11:04 +03:00
|
|
|
|
mutationFn: () => {
|
|
|
|
|
|
// Пустое поле — вход без кода: сервер сам скажет, нужен ли он.
|
|
|
|
|
|
const code = totpCode.trim();
|
|
|
|
|
|
return login(code === '' ? { email, password } : { email, password, totp_code: code });
|
|
|
|
|
|
},
|
2026-09-26 15:12:43 +03:00
|
|
|
|
onSuccess: finishLogin,
|
2026-09-19 21:50:06 +03:00
|
|
|
|
onError: (error: unknown) => {
|
|
|
|
|
|
if (errorCode(error) === 'auth.2fa_required') {
|
2026-09-20 01:11:04 +03:00
|
|
|
|
// Логин, пароль и уже введённый код остаются в форме.
|
2026-09-19 21:50:06 +03:00
|
|
|
|
setNeedsTotp(true);
|
|
|
|
|
|
}
|
|
|
|
|
|
},
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2026-09-26 15:12:43 +03:00
|
|
|
|
const passkey = useMutation({
|
|
|
|
|
|
mutationFn: () => loginWithPasskey(email.trim() === '' ? undefined : email.trim()),
|
|
|
|
|
|
onSuccess: finishLogin,
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2026-09-19 21:50:06 +03:00
|
|
|
|
const onSubmit = (event: FormEvent<HTMLFormElement>): void => {
|
|
|
|
|
|
event.preventDefault();
|
2026-09-20 01:11:04 +03:00
|
|
|
|
setNeedsTotp(false);
|
2026-09-19 21:50:06 +03:00
|
|
|
|
submit.mutate();
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
const registrationEnabled = instance.data?.registration_enabled === true;
|
2026-09-26 15:13:24 +03:00
|
|
|
|
|
|
|
|
|
|
// Ошибка возврата от провайдера: показываем человеческий текст.
|
2026-09-26 15:12:43 +03:00
|
|
|
|
// Ошибка клиента WebAuthn важнее серверной: она объясняет, что делать.
|
|
|
|
|
|
const passkeyErrorKey =
|
|
|
|
|
|
passkey.error instanceof WebAuthnClientError && passkey.error.code === 'cancelled'
|
|
|
|
|
|
? 'auth.login.passkeyCancelled'
|
|
|
|
|
|
: passkey.error instanceof WebAuthnClientError && passkey.error.code === 'unsupported'
|
|
|
|
|
|
? 'auth.login.passkeyUnsupported'
|
|
|
|
|
|
: null;
|
|
|
|
|
|
|
2026-09-19 21:50:06 +03:00
|
|
|
|
return (
|
2026-09-19 23:37:02 +03:00
|
|
|
|
<main className="gl-page mx-auto flex min-h-full w-full max-w-md flex-col justify-center gap-5 px-4 py-10">
|
2026-09-19 21:50:06 +03:00
|
|
|
|
<header>
|
|
|
|
|
|
<h1 className="text-2xl font-semibold tracking-tight">{t('auth.login.title')}</h1>
|
|
|
|
|
|
<p className="mt-1 text-fg-muted">{t('auth.login.subtitle')}</p>
|
|
|
|
|
|
</header>
|
|
|
|
|
|
|
|
|
|
|
|
<Card>
|
|
|
|
|
|
<form className="flex flex-col gap-4" onSubmit={onSubmit} noValidate>
|
|
|
|
|
|
<Field
|
|
|
|
|
|
label={t('auth.login.email')}
|
|
|
|
|
|
type="email"
|
|
|
|
|
|
name="email"
|
|
|
|
|
|
autoComplete="username"
|
|
|
|
|
|
placeholder={t('auth.login.emailPlaceholder')}
|
|
|
|
|
|
value={email}
|
|
|
|
|
|
onChange={(event) => setEmail(event.target.value)}
|
|
|
|
|
|
required
|
|
|
|
|
|
/>
|
|
|
|
|
|
<Field
|
|
|
|
|
|
label={t('auth.login.password')}
|
|
|
|
|
|
type="password"
|
|
|
|
|
|
name="password"
|
|
|
|
|
|
autoComplete="current-password"
|
|
|
|
|
|
value={password}
|
|
|
|
|
|
onChange={(event) => setPassword(event.target.value)}
|
|
|
|
|
|
required
|
|
|
|
|
|
/>
|
2026-09-20 01:11:04 +03:00
|
|
|
|
<Field
|
|
|
|
|
|
label={t('auth.login.totp')}
|
|
|
|
|
|
hint={t('auth.login.totpHint')}
|
|
|
|
|
|
name="totp_code"
|
|
|
|
|
|
inputMode="text"
|
|
|
|
|
|
autoComplete="one-time-code"
|
|
|
|
|
|
maxLength={32}
|
|
|
|
|
|
value={totpCode}
|
|
|
|
|
|
onChange={(event) => setTotpCode(event.target.value)}
|
|
|
|
|
|
/>
|
2026-09-19 21:50:06 +03:00
|
|
|
|
{needsTotp ? (
|
2026-09-20 01:11:04 +03:00
|
|
|
|
<p role="alert" className="text-sm text-danger">
|
|
|
|
|
|
{t('auth.login.totpRequired')}
|
|
|
|
|
|
</p>
|
2026-09-19 21:50:06 +03:00
|
|
|
|
) : null}
|
|
|
|
|
|
|
2026-09-20 01:11:04 +03:00
|
|
|
|
{/* При `auth.2fa_required` подсказка уже показана у поля — не дублируем. */}
|
|
|
|
|
|
{submit.isError && !needsTotp ? <ErrorNotice error={submit.error} /> : null}
|
2026-09-19 21:50:06 +03:00
|
|
|
|
|
|
|
|
|
|
<Button type="submit" disabled={submit.isPending}>
|
|
|
|
|
|
{t(submit.isPending ? 'auth.login.submitting' : 'auth.login.submit')}
|
|
|
|
|
|
</Button>
|
|
|
|
|
|
</form>
|
|
|
|
|
|
|
2026-09-26 15:12:43 +03:00
|
|
|
|
{passkeySupported ? (
|
|
|
|
|
|
<div className="mt-4 flex flex-col gap-2">
|
|
|
|
|
|
<Button
|
|
|
|
|
|
variant="ghost"
|
|
|
|
|
|
data-testid="passkey-login"
|
|
|
|
|
|
disabled={passkey.isPending}
|
|
|
|
|
|
onClick={() => {
|
|
|
|
|
|
setNeedsTotp(false);
|
|
|
|
|
|
passkey.mutate();
|
|
|
|
|
|
}}
|
|
|
|
|
|
>
|
|
|
|
|
|
{t(passkey.isPending ? 'auth.login.passkeyPending' : 'auth.login.passkeySubmit')}
|
|
|
|
|
|
</Button>
|
|
|
|
|
|
{passkeyErrorKey === null ? (
|
|
|
|
|
|
<ErrorNotice error={passkey.error} />
|
|
|
|
|
|
) : (
|
|
|
|
|
|
<p className="text-sm text-danger" role="alert" data-testid="passkey-error">
|
|
|
|
|
|
{t(passkeyErrorKey)}
|
|
|
|
|
|
</p>
|
|
|
|
|
|
)}
|
|
|
|
|
|
</div>
|
|
|
|
|
|
) : null}
|
|
|
|
|
|
|
2026-09-19 21:50:06 +03:00
|
|
|
|
<p className="mt-4 text-sm text-fg-muted">
|
|
|
|
|
|
{t('auth.login.noAccount')}{' '}
|
|
|
|
|
|
{registrationEnabled ? (
|
|
|
|
|
|
<Link className="text-accent underline" to="/register">
|
|
|
|
|
|
{t('auth.login.registerLink')}
|
|
|
|
|
|
</Link>
|
|
|
|
|
|
) : (
|
|
|
|
|
|
<span>{t('auth.login.registrationDisabled')}</span>
|
|
|
|
|
|
)}
|
|
|
|
|
|
</p>
|
|
|
|
|
|
<p className="mt-2 text-xs text-fg-muted">{t('auth.login.forgot')}</p>
|
|
|
|
|
|
</Card>
|
|
|
|
|
|
|
|
|
|
|
|
<footer className="flex items-center justify-between text-xs text-fg-muted">
|
|
|
|
|
|
<Link className="underline" to="/status">
|
|
|
|
|
|
{t('auth.login.instanceStatus')}
|
|
|
|
|
|
</Link>
|
|
|
|
|
|
<span>{instance.data?.version ?? ''}</span>
|
|
|
|
|
|
</footer>
|
|
|
|
|
|
</main>
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|