feat(api): ручки Фаз(ы) 1 — профиль, серверы, роли, админ инстанса
REST-слой Фазы 1 на huma (OpenAPI 3.1 генерируется из кода):
- профиль: GET/PATCH /users/@me, смена пароля со step-up, публичный профиль,
завершение онбординга (новая миграция 00003 с onboarding_completed_at);
- серверы: создание/изменение/удаление, join/leave, список серверов
пользователя, журнал действий;
- комнаты: список с учётом прав, создание/изменение/удаление;
- участники: список с профилями и ролями, никнейм, тайм-аут, исключение;
- роли: CRUD, выдача/снятие с проверкой иерархии и запретом выдачи прав выше
собственных;
- админ инстанса: публичная информация, настройки, серверы, пользователи,
аудит, выдача прав администратора со step-up; обход лимитов фиксируется в
аудите отдельной записью limits.bypass;
- движок прав: участие в сервере стало обязательным условием (IsMember),
не участник не получает прав роли @user; калькулятор прав общий для API и
Gateway, инвалидация кэша после изменений;
- Gateway: браузерный клиент аутентифицируется cookie на рукопожатии, IDENTIFY
без токена использует её; события GUILD/CHANNEL/MEMBER/ROLE рассылаются из
ручек, USER_UPDATE — адресно;
- ошибки huma отдаются в едином конверте {"error":{"code","message"}}.
Тесты: 8 сценариев API (профиль, жизненный цикл сервера и права, лимиты и
обход админом, иерархия ролей, тайм-аут, скрытие комнаты оверрайдом,
членство в движке прав, cookie-идентификация Gateway).
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
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 появляется при ответе `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: () =>
|
||||
login(needsTotp ? { email, password, totp_code: totpCode } : { email, password }),
|
||||
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();
|
||||
submit.mutate();
|
||||
};
|
||||
|
||||
const registrationEnabled = instance.data?.registration_enabled === true;
|
||||
|
||||
return (
|
||||
<main className="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
|
||||
/>
|
||||
{needsTotp ? (
|
||||
<Field
|
||||
label={t('auth.login.totp')}
|
||||
hint={t('auth.login.totpHint')}
|
||||
name="totp_code"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
pattern="[0-9]*"
|
||||
maxLength={8}
|
||||
value={totpCode}
|
||||
onChange={(event) => setTotpCode(event.target.value)}
|
||||
autoFocus
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{submit.isError ? <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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user