Этап 6: авторизация и роли
- вход по почте и паролю (argon2id), сессия в httpOnly-cookie, в БД только хеш токена - «Запомнить устройство» на 90 дней, rate-limit на вход, защита от CSRF заголовком - роли VIEWER / EDITOR / ADMIN: requireAuth и requireRole на сервере - без входа: только экран логина и статьи с visibility PUBLIC (и их файлы в /uploads) - приглашение по одноразовой ссылке с ролью - избранное и недавние синхронизируются с сервером, при выходе кеш закрытых статей стирается - экран входа по макету, блок пользователя с выходом Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
27cdca3967
commit
9f08158607
+50
-12
@@ -1,12 +1,16 @@
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { lazy, Suspense, useEffect } from 'react';
|
||||
import { Route, Routes } from 'react-router-dom';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Screen } from './components/Shell';
|
||||
import { BackLink, Notice } from './components/ui';
|
||||
import { pushFavorites, useAuth } from './lib/auth';
|
||||
import { useFavorites } from './lib/store';
|
||||
import { useTheme } from './lib/theme';
|
||||
import { ArticlePage } from './pages/Article';
|
||||
import { CheatSheetPage } from './pages/CheatSheet';
|
||||
import { FavoritesPage } from './pages/Favorites';
|
||||
import { HomePage } from './pages/Home';
|
||||
import { InvitePage, LoginPage } from './pages/Login';
|
||||
import { OfflinePage } from './pages/OfflinePage';
|
||||
import { SearchPage } from './pages/Search';
|
||||
import { SectionPage } from './pages/Section';
|
||||
@@ -28,20 +32,54 @@ function NotFound() {
|
||||
export function App() {
|
||||
// Тема применяется один раз здесь: вешает data-theme на <html>
|
||||
useTheme();
|
||||
const { user, loading } = useAuth();
|
||||
const qc = useQueryClient();
|
||||
const { favs } = useFavorites();
|
||||
|
||||
// Любой запрос ответил 401 (сессия кончилась): перепроверяем, кто вошёл
|
||||
useEffect(() => {
|
||||
const onUnauthorized = () => void qc.invalidateQueries({ queryKey: ['me'] });
|
||||
window.addEventListener('kb:unauthorized', onUnauthorized);
|
||||
return () => window.removeEventListener('kb:unauthorized', onUnauthorized);
|
||||
}, [qc]);
|
||||
|
||||
// Избранное живёт на устройстве; у вошедшего пользователя копия уходит на сервер
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
const id = setTimeout(() => void pushFavorites(favs), 800);
|
||||
return () => clearTimeout(id);
|
||||
}, [favs, user]);
|
||||
|
||||
if (loading) return <div className="splash" aria-busy="true" />;
|
||||
|
||||
// Без входа доступны только экран входа, приглашение и публичные статьи
|
||||
if (!user) {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<Routes>
|
||||
<Route path="/invite/:token" element={<InvitePage />} />
|
||||
<Route path="/a/:slug" element={<ArticlePage />} />
|
||||
<Route path="/print/:slug" element={<PrintPage />} />
|
||||
<Route path="*" element={<LoginPage />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/search" element={<SearchPage />} />
|
||||
<Route path="/cheatsheet" element={<CheatSheetPage />} />
|
||||
<Route path="/favorites" element={<FavoritesPage />} />
|
||||
<Route path="/s/:slug" element={<SectionPage />} />
|
||||
<Route path="/a/:slug" element={<ArticlePage />} />
|
||||
<Route path="/offline" element={<OfflinePage />} />
|
||||
<Route path="/print/:slug" element={<PrintPage />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/search" element={<SearchPage />} />
|
||||
<Route path="/cheatsheet" element={<CheatSheetPage />} />
|
||||
<Route path="/favorites" element={<FavoritesPage />} />
|
||||
<Route path="/offline" element={<OfflinePage />} />
|
||||
<Route path="/s/:slug" element={<SectionPage />} />
|
||||
<Route path="/a/:slug" element={<ArticlePage />} />
|
||||
<Route path="/print/:slug" element={<PrintPage />} />
|
||||
<Route path="/invite/:token" element={<InvitePage />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { articleHref, useNav } from '../lib/tree';
|
||||
import { IconDoc, IconHome, IconSearch, IconStar } from './Icons';
|
||||
import { OfflineBanner } from './Offline';
|
||||
import { CodeTag } from './ui';
|
||||
import { UserMenu } from './UserMenu';
|
||||
|
||||
export type Tab = 'home' | 'search' | 'cheat' | 'fav';
|
||||
|
||||
@@ -34,7 +35,7 @@ export function TabBar({ active }: { active: Tab }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function Sidebar({ footer }: { footer?: ReactNode }) {
|
||||
export function Sidebar() {
|
||||
const nav = useNav();
|
||||
const { theme, setTheme } = useTheme();
|
||||
const { pathname } = useLocation();
|
||||
@@ -92,7 +93,7 @@ export function Sidebar({ footer }: { footer?: ReactNode }) {
|
||||
</nav>
|
||||
|
||||
<div className="sidebar-foot">
|
||||
{footer}
|
||||
<UserMenu compact />
|
||||
<div className="sidebar-foot-label">Тема</div>
|
||||
<div className="segmented segmented--3" role="group" aria-label="Тема">
|
||||
{THEME_ORDER.map((t) => (
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
// Блок «кто вошёл»: имя, роль, ссылки на управление и выход.
|
||||
// В макете его нет: добавлен в стиле списков, иначе негде выйти и открыть админку.
|
||||
import { Link } from 'react-router-dom';
|
||||
import { ROLE_LABEL } from '@kb/shared';
|
||||
import { useAuth, useAuthActions } from '../lib/auth';
|
||||
|
||||
export function UserMenu({ compact }: { compact?: boolean }) {
|
||||
const { user, isEditor, isAdmin } = useAuth();
|
||||
const { logout } = useAuthActions();
|
||||
if (!user) return null;
|
||||
|
||||
return (
|
||||
<div className={compact ? 'usermenu usermenu--compact' : 'usermenu list'}>
|
||||
<div className="usermenu-who list-row">
|
||||
<span className="avatar" aria-hidden="true">
|
||||
{user.name
|
||||
.split(/\s+/)
|
||||
.slice(0, 2)
|
||||
.map((w) => w[0]?.toUpperCase())
|
||||
.join('')}
|
||||
</span>
|
||||
<span className="list-row-main">
|
||||
<span className="list-row-title">{user.name}</span>
|
||||
<span className="list-row-sub">{ROLE_LABEL[user.role]}</span>
|
||||
</span>
|
||||
</div>
|
||||
{isEditor ? (
|
||||
<Link to="/new" className="list-row usermenu-link">
|
||||
<span className="list-row-main list-row-title">Новая статья</span>
|
||||
</Link>
|
||||
) : null}
|
||||
{isAdmin ? (
|
||||
<Link to="/admin" className="list-row usermenu-link">
|
||||
<span className="list-row-main list-row-title">Управление</span>
|
||||
</Link>
|
||||
) : null}
|
||||
<button type="button" className="list-row usermenu-link usermenu-btn" onClick={() => void logout()}>
|
||||
<span className="list-row-main list-row-title">Выйти</span>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -32,7 +32,8 @@ export async function api<T>(path: string, init?: RequestInit & { json?: unknown
|
||||
if (res.status === 204) return undefined as T;
|
||||
const data = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) window.dispatchEvent(new Event('kb:unauthorized'));
|
||||
// 401 на обычном запросе = сессия кончилась. Сам запрос «кто я» не считаем, иначе получится замкнутый круг.
|
||||
if (res.status === 401 && !path.startsWith('/auth/')) window.dispatchEvent(new Event('kb:unauthorized'));
|
||||
throw new ApiError(res.status, (data as { error?: string } | null)?.error ?? `Ошибка ${res.status}`);
|
||||
}
|
||||
return data as T;
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// Кто вошёл. Сервер хранит сессию в httpOnly-cookie, здесь только узнаём пользователя.
|
||||
import { useEffect } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import type { Role, UserDto } from '@kb/shared';
|
||||
import { api, ApiError } from './api';
|
||||
import { clearPrivateCaches } from './offline';
|
||||
import { getStored, type RecentItem, setStored, useStored } from './store';
|
||||
|
||||
const USER_KEY = 'kb-user';
|
||||
|
||||
/**
|
||||
* Состояние входа:
|
||||
* loading: ещё спрашиваем сервер;
|
||||
* user: вошёл (или нет сети, но на этом устройстве уже входили: тогда читаем сохранённое);
|
||||
* null: не вошёл.
|
||||
*/
|
||||
export function useAuth() {
|
||||
const [cached, setCached] = useStored<UserDto | null>(USER_KEY, null);
|
||||
const q = useQuery({
|
||||
queryKey: ['me'],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
const { user } = await api<{ user: UserDto }>('/auth/me');
|
||||
return user;
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.status === 401) return null;
|
||||
throw e; // нет сети: оставляем сохранённого пользователя
|
||||
}
|
||||
},
|
||||
staleTime: 5 * 60_000,
|
||||
retry: false,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (q.data === undefined) return;
|
||||
if (q.data === null && cached) {
|
||||
// Сессия кончилась: убираем с устройства сохранённые закрытые статьи
|
||||
setCached(null);
|
||||
void clearPrivateCaches();
|
||||
} else if (q.data && JSON.stringify(q.data) !== JSON.stringify(cached)) {
|
||||
setCached(q.data);
|
||||
}
|
||||
}, [q.data, cached, setCached]);
|
||||
|
||||
// Если на устройстве уже входили, не ждём ответа сервера: сразу показываем приложение
|
||||
// (так оно открывается мгновенно и работает без сети). Сервер ответит 401: покажем экран входа.
|
||||
const user = q.data !== undefined ? q.data : (cached ?? (q.isError ? null : undefined));
|
||||
return {
|
||||
user: user ?? null,
|
||||
loading: user === undefined,
|
||||
isEditor: user?.role === 'EDITOR' || user?.role === 'ADMIN',
|
||||
isAdmin: user?.role === 'ADMIN',
|
||||
};
|
||||
}
|
||||
|
||||
export const roleAtLeast = (role: Role | undefined, min: Role) =>
|
||||
!!role && ['VIEWER', 'EDITOR', 'ADMIN'].indexOf(role) >= ['VIEWER', 'EDITOR', 'ADMIN'].indexOf(min);
|
||||
|
||||
export function useAuthActions() {
|
||||
const qc = useQueryClient();
|
||||
return {
|
||||
/** После входа: запоминаем пользователя и перезапрашиваем всё (теперь видны закрытые статьи). */
|
||||
async onLogin(user: UserDto) {
|
||||
setStored(USER_KEY, user);
|
||||
qc.setQueryData(['me'], user);
|
||||
await syncPersonal();
|
||||
await qc.invalidateQueries({ predicate: (query) => query.queryKey[0] !== 'me' });
|
||||
},
|
||||
async logout() {
|
||||
await api('/auth/logout', { method: 'POST' }).catch(() => undefined);
|
||||
setStored(USER_KEY, null);
|
||||
await clearPrivateCaches();
|
||||
qc.setQueryData(['me'], null);
|
||||
qc.removeQueries({ predicate: (query) => query.queryKey[0] !== 'me' });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- Синхронизация избранного и недавних между устройствами ----------
|
||||
interface PersonalState {
|
||||
favorites: string[];
|
||||
recent: RecentItem[];
|
||||
}
|
||||
|
||||
/** Объединяет локальные данные с серверными (ничего не теряя) и отправляет результат на сервер. */
|
||||
export async function syncPersonal() {
|
||||
try {
|
||||
const remote = await api<PersonalState>('/me/state');
|
||||
const favs = [...new Set([...getStored<string[]>('kb-fav', []), ...remote.favorites])];
|
||||
setStored('kb-fav', favs);
|
||||
const recent = new Map<string, number>();
|
||||
for (const r of [...remote.recent, ...getStored<RecentItem[]>('kb-recent', [])]) {
|
||||
recent.set(r.slug, Math.max(recent.get(r.slug) ?? 0, r.at));
|
||||
}
|
||||
setStored(
|
||||
'kb-recent',
|
||||
[...recent].map(([slug, at]) => ({ slug, at })).sort((a, b) => b.at - a.at).slice(0, 12),
|
||||
);
|
||||
await pushFavorites(favs);
|
||||
} catch {
|
||||
// нет сети: синхронизируемся в следующий раз
|
||||
}
|
||||
}
|
||||
|
||||
export const pushFavorites = (slugs: string[]) =>
|
||||
api('/me/favorites', { method: 'PUT', json: { slugs } }).catch(() => undefined);
|
||||
|
||||
export const pushRecentView = (slug: string) =>
|
||||
api('/me/recent', { method: 'POST', json: { slug } }).catch(() => undefined);
|
||||
@@ -10,7 +10,9 @@ import { Screen } from '../components/Shell';
|
||||
import { BackLink, Notice, Sheet, Skeleton } from '../components/ui';
|
||||
import { ApiError, useArticle } from '../lib/api';
|
||||
import { fileExt, formatBytes, formatDate, num2 } from '../lib/format';
|
||||
import { pushRecentView, useAuth } from '../lib/auth';
|
||||
import { pushRecent, useFavorites } from '../lib/store';
|
||||
import { LoginPage } from './Login';
|
||||
import { useTheme } from '../lib/theme';
|
||||
import { useNav } from '../lib/tree';
|
||||
|
||||
@@ -61,9 +63,13 @@ function ArticleView({ slug }: { slug: string }) {
|
||||
const listItem = nav.article(slug);
|
||||
const section = nav.sectionOf(art ?? listItem);
|
||||
|
||||
const { user } = useAuth();
|
||||
const artSlug = art?.slug;
|
||||
useEffect(() => {
|
||||
if (art) pushRecent(art.slug);
|
||||
}, [art]);
|
||||
if (!artSlug) return;
|
||||
pushRecent(artSlug);
|
||||
if (user) void pushRecentView(artSlug);
|
||||
}, [artSlug, user]);
|
||||
|
||||
// При переходе на другую статью начинаем чтение сверху
|
||||
useEffect(() => {
|
||||
@@ -105,6 +111,9 @@ function ArticleView({ slug }: { slug: string }) {
|
||||
</nav>
|
||||
);
|
||||
|
||||
// Закрытая статья, а пользователь не вошёл: показываем экран входа (после входа статья откроется)
|
||||
if (!art && error instanceof ApiError && error.status === 401) return <LoginPage />;
|
||||
|
||||
if (!art) {
|
||||
const notFound = error instanceof ApiError && error.status === 404;
|
||||
return (
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useRef } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { plural } from '@kb/shared';
|
||||
import { Screen } from '../components/Shell';
|
||||
import { UserMenu } from '../components/UserMenu';
|
||||
import { Caps, CodeTag, Notice, Plaque, Skeleton, ThemeButton } from '../components/ui';
|
||||
import { useArticle } from '../lib/api';
|
||||
import { formatRecent } from '../lib/format';
|
||||
@@ -193,6 +194,9 @@ export function HomePage() {
|
||||
</span>
|
||||
</Link>
|
||||
</nav>
|
||||
<div className="home-more">
|
||||
<UserMenu />
|
||||
</div>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
import { type FormEvent, useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { ROLE_LABEL, type Role, type UserDto } from '@kb/shared';
|
||||
import { api, ApiError } from '../lib/api';
|
||||
import { useAuthActions } from '../lib/auth';
|
||||
|
||||
function AuthFrame({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="login">
|
||||
<div className="hazard hazard--lg" aria-hidden="true" />
|
||||
<main className="login-main">
|
||||
<div>
|
||||
<div className="login-site">wiki.suchtech.ru</div>
|
||||
<h1 className="login-title">Памятки монтажника</h1>
|
||||
</div>
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PasswordField({ value, onChange, label, autoComplete }: { value: string; onChange: (v: string) => void; label: string; autoComplete: string }) {
|
||||
const [shown, setShown] = useState(false);
|
||||
return (
|
||||
<label className="field">
|
||||
<span className="field-label">{label}</span>
|
||||
<span className="field-box">
|
||||
<input
|
||||
className="field-input"
|
||||
type={shown ? 'text' : 'password'}
|
||||
autoComplete={autoComplete}
|
||||
required
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
<button type="button" className="field-toggle" onClick={() => setShown(!shown)} aria-pressed={shown}>
|
||||
{shown ? 'Скрыть' : 'Показать'}
|
||||
</button>
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function Remember({ on, toggle }: { on: boolean; toggle: () => void }) {
|
||||
return (
|
||||
<button type="button" role="switch" aria-checked={on} className="remember" onClick={toggle}>
|
||||
<span className={on ? 'bigbox bigbox--on' : 'bigbox'} aria-hidden="true" />
|
||||
<span>
|
||||
<span className="remember-title">Запомнить устройство</span>
|
||||
<span className="remember-text">Не спрашивать пароль 90 дней</span>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function LoginPage() {
|
||||
const { onLogin } = useAuthActions();
|
||||
const navigate = useNavigate();
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [remember, setRemember] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [inviteOpen, setInviteOpen] = useState(false);
|
||||
const [inviteLink, setInviteLink] = useState('');
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const { user } = await api<{ user: UserDto }>('/auth/login', { method: 'POST', json: { email, password, remember } });
|
||||
await onLogin(user);
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : 'Не удалось войти');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
// «Есть ссылка-приглашение»: принимаем и полную ссылку, и один код из неё
|
||||
const openInvite = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
const token = inviteLink.trim().split('/').filter(Boolean).pop();
|
||||
if (token) navigate(`/invite/${token}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthFrame>
|
||||
<form className="login-form" onSubmit={submit}>
|
||||
<label className="field">
|
||||
<span className="field-label">Почта</span>
|
||||
<input
|
||||
className="field-input field-input--box"
|
||||
type="email"
|
||||
inputMode="email"
|
||||
autoComplete="username"
|
||||
placeholder="ivanov@suchtech.ru"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<PasswordField label="Пароль" autoComplete="current-password" value={password} onChange={setPassword} />
|
||||
<Remember on={remember} toggle={() => setRemember(!remember)} />
|
||||
{error ? (
|
||||
<div className="form-error" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
<button type="submit" className="btn btn--solid btn--xl" disabled={busy}>
|
||||
{busy ? 'Входим…' : 'Войти'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{inviteOpen ? (
|
||||
<form className="login-form" onSubmit={openInvite}>
|
||||
<label className="field">
|
||||
<span className="field-label">Ссылка-приглашение</span>
|
||||
<input
|
||||
className="field-input field-input--box"
|
||||
autoFocus
|
||||
placeholder="Вставьте ссылку от администратора"
|
||||
value={inviteLink}
|
||||
onChange={(e) => setInviteLink(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" className="btn btn--outline btn--lg">
|
||||
Продолжить
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<button type="button" className="login-link" onClick={() => setInviteOpen(true)}>
|
||||
Есть ссылка-приглашение
|
||||
</button>
|
||||
)}
|
||||
</AuthFrame>
|
||||
);
|
||||
}
|
||||
|
||||
export function InvitePage() {
|
||||
const { token = '' } = useParams();
|
||||
const { onLogin } = useAuthActions();
|
||||
const navigate = useNavigate();
|
||||
const [role, setRole] = useState<Role | null>(null);
|
||||
const [invalid, setInvalid] = useState('');
|
||||
const [name, setName] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
api<{ role: Role }>(`/auth/invite/${encodeURIComponent(token)}`)
|
||||
.then((r) => setRole(r.role))
|
||||
.catch((e) => setInvalid(e instanceof ApiError ? e.message : 'Не удалось проверить ссылку'));
|
||||
}, [token]);
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const { user } = await api<{ user: UserDto }>(`/auth/invite/${encodeURIComponent(token)}`, {
|
||||
method: 'POST',
|
||||
json: { name, email, password },
|
||||
});
|
||||
await onLogin(user);
|
||||
navigate('/', { replace: true });
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : 'Не удалось зарегистрироваться');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthFrame>
|
||||
{invalid ? (
|
||||
<>
|
||||
<div className="form-error" role="alert">
|
||||
{invalid}
|
||||
</div>
|
||||
<button type="button" className="btn btn--outline btn--lg" onClick={() => navigate('/')}>
|
||||
На экран входа
|
||||
</button>
|
||||
</>
|
||||
) : !role ? (
|
||||
<div className="login-note">Проверяем приглашение…</div>
|
||||
) : (
|
||||
<form className="login-form" onSubmit={submit}>
|
||||
<div className="login-note">
|
||||
Вас пригласили с ролью «{ROLE_LABEL[role]}». Придумайте пароль, чтобы входить с любого устройства.
|
||||
</div>
|
||||
<label className="field">
|
||||
<span className="field-label">Имя и фамилия</span>
|
||||
<input className="field-input field-input--box" autoComplete="name" required minLength={2} value={name} onChange={(e) => setName(e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span className="field-label">Почта</span>
|
||||
<input className="field-input field-input--box" type="email" inputMode="email" autoComplete="username" required value={email} onChange={(e) => setEmail(e.target.value)} />
|
||||
</label>
|
||||
<PasswordField label="Пароль (не короче 8 символов)" autoComplete="new-password" value={password} onChange={setPassword} />
|
||||
{error ? (
|
||||
<div className="form-error" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
<button type="submit" className="btn btn--solid btn--xl" disabled={busy}>
|
||||
{busy ? 'Создаём…' : 'Зарегистрироваться'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</AuthFrame>
|
||||
);
|
||||
}
|
||||
@@ -2234,3 +2234,235 @@ mark {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Вход ---------- */
|
||||
.splash {
|
||||
min-height: 100dvh;
|
||||
background: var(--bg);
|
||||
}
|
||||
.hazard {
|
||||
height: 10px;
|
||||
background: repeating-linear-gradient(-45deg, var(--brand) 0 10px, var(--brand-ink) 10px 20px);
|
||||
}
|
||||
.hazard--lg {
|
||||
height: calc(14px + env(safe-area-inset-top));
|
||||
background: repeating-linear-gradient(-45deg, var(--brand) 0 12px, var(--brand-ink) 12px 24px);
|
||||
}
|
||||
.login {
|
||||
min-height: 100dvh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.login-main {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
max-width: 460px;
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: var(--sp-9);
|
||||
padding: var(--sp-12) var(--sp-10);
|
||||
}
|
||||
.login-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-9);
|
||||
}
|
||||
.login-site {
|
||||
font-size: var(--fs-13);
|
||||
font-weight: 700;
|
||||
color: var(--ink2);
|
||||
}
|
||||
.login-title {
|
||||
font-size: var(--fs-32);
|
||||
font-weight: 700;
|
||||
line-height: 1.05;
|
||||
letter-spacing: -0.02em;
|
||||
margin-top: var(--sp-3);
|
||||
}
|
||||
.login-note {
|
||||
font-size: var(--fs-16);
|
||||
color: var(--ink2);
|
||||
line-height: var(--lh-normal);
|
||||
}
|
||||
.login-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: var(--tap);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
font-size: var(--fs-16);
|
||||
font-weight: 600;
|
||||
color: var(--ink);
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
min-width: 0;
|
||||
}
|
||||
.field-label {
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 700;
|
||||
}
|
||||
.field-box,
|
||||
.field-input--box {
|
||||
height: var(--h-field);
|
||||
border: 2px solid var(--ink);
|
||||
border-radius: var(--r-btn);
|
||||
background: var(--sf);
|
||||
}
|
||||
.field-box {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 var(--sp-3) 0 var(--sp-8);
|
||||
}
|
||||
.field-box:focus-within,
|
||||
.field-input--box:focus {
|
||||
box-shadow: 0 0 0 var(--focus-ring) var(--hl);
|
||||
outline: 0;
|
||||
}
|
||||
.field-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-18);
|
||||
}
|
||||
.field-input--box {
|
||||
flex: none;
|
||||
padding: 0 var(--sp-8);
|
||||
border: 2px solid var(--ink);
|
||||
background: var(--sf);
|
||||
}
|
||||
.field-input::placeholder {
|
||||
color: var(--ink2);
|
||||
}
|
||||
.field-toggle {
|
||||
flex: none;
|
||||
height: var(--tap);
|
||||
padding: 0 var(--sp-6);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 600;
|
||||
color: var(--ink2);
|
||||
cursor: pointer;
|
||||
}
|
||||
.remember {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-7);
|
||||
min-height: var(--h-btn);
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
color: var(--ink);
|
||||
}
|
||||
.remember-title {
|
||||
display: block;
|
||||
font-weight: 700;
|
||||
}
|
||||
.remember-text {
|
||||
display: block;
|
||||
font-size: var(--fs-14);
|
||||
color: var(--ink2);
|
||||
}
|
||||
.bigbox {
|
||||
flex: none;
|
||||
position: relative;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border: 2px solid var(--ink);
|
||||
border-radius: var(--r-sm);
|
||||
background: var(--sf);
|
||||
}
|
||||
.bigbox--on {
|
||||
border-color: var(--grnS);
|
||||
background: var(--grnS);
|
||||
}
|
||||
.bigbox--on::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 9px;
|
||||
top: 3px;
|
||||
width: 8px;
|
||||
height: 15px;
|
||||
border: solid var(--on-strong);
|
||||
border-width: 0 3px 3px 0;
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
.form-error {
|
||||
padding: var(--sp-6) var(--sp-7);
|
||||
border: 2px solid var(--redS);
|
||||
border-radius: var(--r-btn);
|
||||
background: var(--redbg);
|
||||
color: var(--red);
|
||||
font-size: var(--fs-16);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ---------- Блок пользователя ---------- */
|
||||
.avatar {
|
||||
flex: none;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
background: var(--sf2);
|
||||
border: var(--bw) solid var(--ln);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: var(--fs-14);
|
||||
font-weight: 700;
|
||||
}
|
||||
.usermenu-btn {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
border-top: var(--bw) solid var(--ln);
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
font-size: inherit;
|
||||
}
|
||||
.usermenu-link {
|
||||
min-height: var(--h-row-sm);
|
||||
}
|
||||
.usermenu--compact {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin: calc(var(--sp-4) * -1) calc(var(--sp-4) * -1) var(--sp-2);
|
||||
}
|
||||
.usermenu--compact .list-row {
|
||||
min-height: var(--h-chip);
|
||||
padding: var(--sp-2) var(--sp-4);
|
||||
border: 0;
|
||||
border-radius: var(--r-sm);
|
||||
font-size: var(--fs-15);
|
||||
}
|
||||
.usermenu--compact .usermenu-who {
|
||||
min-height: var(--h-row-sm);
|
||||
}
|
||||
.usermenu--compact .avatar {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
}
|
||||
.badge-draft {
|
||||
flex: none;
|
||||
padding: var(--sp-1) var(--sp-4);
|
||||
border-radius: var(--r-tag);
|
||||
border: var(--bw) solid var(--ambln);
|
||||
background: var(--ambbg);
|
||||
color: var(--amb);
|
||||
font-size: var(--fs-12);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user