Files
glchat/web/src/pages/LoginPage.tsx
T

137 lines
5.0 KiB
TypeScript
Raw Normal View History

import { useState, type FormEvent } from 'react';
import { useMutation } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { Link, useLocation, useNavigate } from 'react-router';
import { login } from '@/api/auth';
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';
interface LocationState {
from?: string;
}
/**
* Форма входа. Поле кода 2FA показывается всегда: сервер принимает и код из
* приложения (6 цифр), и резервный код вида `a8eh-pshp-t8st`, а при попытке
* входа без кода отвечает `auth.2fa_required` — тогда подсказываем про код.
*/
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);
const from = (location.state as LocationState | null)?.from ?? '/app';
const submit = useMutation({
mutationFn: () => {
// Пустое поле — вход без кода: сервер сам скажет, нужен ли он.
const code = totpCode.trim();
return login(code === '' ? { email, password } : { email, password, totp_code: code });
},
onSuccess: async () => {
// Профиль перечитываем заново: cookie уже выставлена сервером.
await getQueryClient().invalidateQueries();
void navigate(from === '/login' ? '/app' : from, { replace: true });
},
onError: (error: unknown) => {
if (errorCode(error) === 'auth.2fa_required') {
// Логин, пароль и уже введённый код остаются в форме.
setNeedsTotp(true);
}
},
});
const onSubmit = (event: FormEvent<HTMLFormElement>): void => {
event.preventDefault();
setNeedsTotp(false);
submit.mutate();
};
const registrationEnabled = instance.data?.registration_enabled === true;
return (
<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">
<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
/>
<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)}
/>
{needsTotp ? (
<p role="alert" className="text-sm text-danger">
{t('auth.login.totpRequired')}
</p>
) : null}
{/* При `auth.2fa_required` подсказка уже показана у поля — не дублируем. */}
{submit.isError && !needsTotp ? <ErrorNotice error={submit.error} /> : null}
<Button type="submit" disabled={submit.isPending}>
{t(submit.isPending ? 'auth.login.submitting' : 'auth.login.submit')}
</Button>
</form>
<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>
);
}