Этап 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
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user