feat(auth): двухфакторная аутентификация (TOTP) для входа в панель
Бэкенд:
- two_factor_service: генерация секрета, otpauth-URI, QR как inline-SVG,
одноразовые backup-коды (хранятся как SHA-256)
- эндпоинты /api/auth/2fa/{status,setup,enable,disable}; гейт 2FA в login
(неверный код -> 400, чтобы SPA не сбрасывала форму); two_factor_enabled в /me
- админский сброс: POST /api/users/{id}/disable-2fa
- модель/схемы/init.sql + идемпотентная миграция №30 (two_factor_backup_codes)
- зависимости: pyotp, qrcode
Фронтенд:
- двухшаговый вход с полем кода (TOTP/backup)
- карточка 2FA в профиле: QR, проверка, backup-коды, отключение
- бейдж/сброс 2FA в списке пользователей; локали ru/en
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -11,6 +11,8 @@ export default function LoginPage() {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [twoFactorRequired, setTwoFactorRequired] = useState(false);
|
||||
const [code, setCode] = useState('');
|
||||
const { login, isLoading, error, clearError } = useAuthStore();
|
||||
const navigate = useNavigate();
|
||||
const { t } = useTranslation();
|
||||
@@ -18,7 +20,11 @@ export default function LoginPage() {
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await login({ username, password });
|
||||
const result = await login({ username, password, code: twoFactorRequired ? code : undefined });
|
||||
if (result.twoFactorRequired) {
|
||||
setTwoFactorRequired(true);
|
||||
return;
|
||||
}
|
||||
navigate('/dashboard');
|
||||
} catch {
|
||||
// Error is already handled in store
|
||||
@@ -36,49 +42,74 @@ export default function LoginPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="username">{t('login.username', 'Username')}</Label>
|
||||
<Input
|
||||
id="username"
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => {
|
||||
setUsername(e.target.value);
|
||||
clearError();
|
||||
}}
|
||||
placeholder={t('login.username_placeholder', 'Enter username')}
|
||||
autoComplete="username"
|
||||
autoFocus
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{!twoFactorRequired ? (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="username">{t('login.username', 'Username')}</Label>
|
||||
<Input
|
||||
id="username"
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => {
|
||||
setUsername(e.target.value);
|
||||
clearError();
|
||||
}}
|
||||
placeholder={t('login.username_placeholder', 'Enter username')}
|
||||
autoComplete="username"
|
||||
autoFocus
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">{t('login.password', 'Password')}</Label>
|
||||
<div className="relative">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">{t('login.password', 'Password')}</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={password}
|
||||
onChange={(e) => {
|
||||
setPassword(e.target.value);
|
||||
clearError();
|
||||
}}
|
||||
placeholder={t('login.password_placeholder', 'Enter password')}
|
||||
autoComplete="current-password"
|
||||
className="pr-9"
|
||||
required
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword((v) => !v)}
|
||||
aria-label={showPassword ? t('login.hide_password', 'Hide password') : t('login.show_password', 'Show password')}
|
||||
className="absolute inset-y-0 right-0 flex items-center px-2.5 text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="code">{t('login.two_factor_code', 'Authentication code')}</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={password}
|
||||
id="code"
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
value={code}
|
||||
onChange={(e) => {
|
||||
setPassword(e.target.value);
|
||||
setCode(e.target.value);
|
||||
clearError();
|
||||
}}
|
||||
placeholder={t('login.password_placeholder', 'Enter password')}
|
||||
autoComplete="current-password"
|
||||
className="pr-9"
|
||||
placeholder={t('login.two_factor_placeholder', '6-digit code or backup code')}
|
||||
autoFocus
|
||||
required
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword((v) => !v)}
|
||||
aria-label={showPassword ? t('login.hide_password', 'Hide password') : t('login.show_password', 'Show password')}
|
||||
className="absolute inset-y-0 right-0 flex items-center px-2.5 text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('login.two_factor_hint', 'Enter the code from your authenticator app, or a backup code.')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-4 pt-1">
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
@@ -87,16 +118,28 @@ export default function LoginPage() {
|
||||
<span className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
|
||||
{t('login.signing_in', 'Signing in...')}
|
||||
</span>
|
||||
) : twoFactorRequired ? (
|
||||
t('login.verify', 'Verify')
|
||||
) : (
|
||||
t('login.sign_in', 'Sign in')
|
||||
)}
|
||||
</Button>
|
||||
<Link
|
||||
to="/forgot-password"
|
||||
className="text-sm font-medium text-primary transition-opacity hover:opacity-80"
|
||||
>
|
||||
{t('login.forgot_password', 'Forgot password')}
|
||||
</Link>
|
||||
{twoFactorRequired ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setTwoFactorRequired(false); setCode(''); clearError(); }}
|
||||
className="text-sm font-medium text-primary transition-opacity hover:opacity-80"
|
||||
>
|
||||
{t('login.back', 'Back')}
|
||||
</button>
|
||||
) : (
|
||||
<Link
|
||||
to="/forgot-password"
|
||||
className="text-sm font-medium text-primary transition-opacity hover:opacity-80"
|
||||
>
|
||||
{t('login.forgot_password', 'Forgot password')}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@@ -25,6 +25,8 @@ import {
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { SSHKeysManager } from './SSHKeysManager';
|
||||
import { useConfirm } from '@/components/shared/ConfirmDialog';
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import { useAuthStore } from '@/stores/auth-store';
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -112,11 +114,161 @@ function ProfileTab() {
|
||||
}}>{t('settings.change_password')}</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<TwoFactorCard />
|
||||
<QuotaCard />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface TwoFactorStatus { enabled: boolean; backup_codes_remaining: number }
|
||||
interface TwoFactorSetup { secret: string; otpauth_uri: string; qr_svg: string }
|
||||
|
||||
function TwoFactorCard() {
|
||||
const { t } = useTranslation();
|
||||
const loadUser = useAuthStore((s) => s.loadUser);
|
||||
const [status, setStatus] = useState<TwoFactorStatus | null>(null);
|
||||
const [setup, setSetup] = useState<TwoFactorSetup | null>(null);
|
||||
const [code, setCode] = useState('');
|
||||
const [backupCodes, setBackupCodes] = useState<string[] | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
// Disable flow
|
||||
const [showDisable, setShowDisable] = useState(false);
|
||||
const [disablePwd, setDisablePwd] = useState('');
|
||||
const [disableCode, setDisableCode] = useState('');
|
||||
|
||||
const refresh = () =>
|
||||
apiClient.get<TwoFactorStatus>('/api/auth/2fa/status').then(setStatus).catch(() => {});
|
||||
|
||||
useEffect(() => { refresh(); }, []);
|
||||
|
||||
const startSetup = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const data = await apiClient.post<TwoFactorSetup>('/api/auth/2fa/setup');
|
||||
setSetup(data);
|
||||
setBackupCodes(null);
|
||||
setCode('');
|
||||
} catch (e) { toast.error((e as Error).message); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
|
||||
const confirmEnable = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await apiClient.post<{ backup_codes: string[] }>('/api/auth/2fa/enable', { code });
|
||||
setBackupCodes(res.backup_codes);
|
||||
setSetup(null);
|
||||
setCode('');
|
||||
await refresh();
|
||||
loadUser();
|
||||
toast.success(t('settings.tfa.enabled_ok'));
|
||||
} catch (e) { toast.error((e as Error).message); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
|
||||
const confirmDisable = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await apiClient.post('/api/auth/2fa/disable', { password: disablePwd, code: disableCode });
|
||||
setShowDisable(false);
|
||||
setDisablePwd('');
|
||||
setDisableCode('');
|
||||
setBackupCodes(null);
|
||||
await refresh();
|
||||
loadUser();
|
||||
toast.success(t('settings.tfa.disabled_ok'));
|
||||
} catch (e) { toast.error((e as Error).message); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm flex items-center gap-2">
|
||||
{t('settings.tfa.title')}
|
||||
{status?.enabled
|
||||
? <Badge variant="default">{t('settings.tfa.on')}</Badge>
|
||||
: <Badge variant="secondary">{t('settings.tfa.off')}</Badge>}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-xs text-muted-foreground">{t('settings.tfa.description')}</p>
|
||||
|
||||
{/* Freshly generated backup codes (shown once, right after enabling) */}
|
||||
{backupCodes && (
|
||||
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 p-3 space-y-2">
|
||||
<p className="text-sm font-medium">{t('settings.tfa.backup_codes_title')}</p>
|
||||
<p className="text-xs text-muted-foreground">{t('settings.tfa.backup_codes_hint')}</p>
|
||||
<div className="grid grid-cols-2 gap-1.5 font-mono text-sm">
|
||||
{backupCodes.map((c) => <span key={c} className="select-all">{c}</span>)}
|
||||
</div>
|
||||
<Button size="sm" variant="outline" onClick={() => navigator.clipboard?.writeText(backupCodes.join('\n'))}>
|
||||
{t('settings.tfa.copy_codes')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Not enabled — offer setup */}
|
||||
{!status?.enabled && !setup && !backupCodes && (
|
||||
<Button size="sm" onClick={startSetup} disabled={busy}>{t('settings.tfa.enable')}</Button>
|
||||
)}
|
||||
|
||||
{/* Setup in progress — QR + verify */}
|
||||
{setup && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col items-start gap-2 sm:flex-row sm:items-center">
|
||||
<div
|
||||
className="h-40 w-40 rounded-md bg-white p-2 [&>svg]:h-full [&>svg]:w-full"
|
||||
dangerouslySetInnerHTML={{ __html: setup.qr_svg }}
|
||||
/>
|
||||
<div className="space-y-1 text-xs">
|
||||
<p className="text-muted-foreground">{t('settings.tfa.scan_hint')}</p>
|
||||
<p className="text-muted-foreground">{t('settings.tfa.manual_key')}</p>
|
||||
<code className="select-all break-all font-mono text-foreground">{setup.secret}</code>
|
||||
</div>
|
||||
</div>
|
||||
<div className="max-w-xs space-y-1">
|
||||
<Label>{t('settings.tfa.enter_code')}</Label>
|
||||
<Input value={code} inputMode="numeric" onChange={(e) => setCode(e.target.value)} placeholder="123456" />
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={confirmEnable} disabled={busy || code.length < 6}>{t('settings.tfa.verify_enable')}</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => { setSetup(null); setCode(''); }}>{t('common.cancel')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Enabled — show remaining backup codes + disable */}
|
||||
{status?.enabled && !backupCodes && (
|
||||
<div className="space-y-3">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('settings.tfa.backup_remaining', { count: status.backup_codes_remaining })}
|
||||
</p>
|
||||
{!showDisable ? (
|
||||
<Button size="sm" variant="destructive" onClick={() => setShowDisable(true)}>{t('settings.tfa.disable')}</Button>
|
||||
) : (
|
||||
<div className="space-y-2 rounded-md border p-3">
|
||||
<div className="max-w-xs space-y-1">
|
||||
<Label>{t('settings.current_password')}</Label>
|
||||
<Input type="password" value={disablePwd} onChange={(e) => setDisablePwd(e.target.value)} />
|
||||
</div>
|
||||
<div className="max-w-xs space-y-1">
|
||||
<Label>{t('settings.tfa.current_code')}</Label>
|
||||
<Input value={disableCode} inputMode="numeric" onChange={(e) => setDisableCode(e.target.value)} placeholder="123456" />
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" variant="destructive" onClick={confirmDisable} disabled={busy || !disablePwd}>{t('settings.tfa.confirm_disable')}</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => { setShowDisable(false); setDisablePwd(''); setDisableCode(''); }}>{t('common.cancel')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function QuotaCard() {
|
||||
const { t } = useTranslation();
|
||||
const { data: quota, isLoading } = useMyQuota();
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
Search, Plus, Shield, Trash2, RotateCcw, Unlock, Pencil, Server, LogOut, Ban, KeyRound, Gauge,
|
||||
Search, Plus, Shield, ShieldOff, Trash2, RotateCcw, Unlock, Pencil, Server, LogOut, Ban, KeyRound, Gauge,
|
||||
} from 'lucide-react';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
@@ -20,7 +20,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
||||
import type { User } from '@/types';
|
||||
import {
|
||||
useUsers, useCreateUser, useUpdateUser, useDeleteUser,
|
||||
useResetPassword, useUnlockUser, useTerminateUserSessions,
|
||||
useResetPassword, useUnlockUser, useTerminateUserSessions, useDisableUser2FA,
|
||||
useRoles, useCreateRole, useUpdateRole, useDeleteRole, usePermissions,
|
||||
useSessions, useTerminateSession, useTerminateAllSessions,
|
||||
useUserServerAssignments, useSetUserServers,
|
||||
@@ -93,6 +93,7 @@ function UsersTab() {
|
||||
const { data: users = [] } = useUsers();
|
||||
const deleteUser = useDeleteUser();
|
||||
const unlockUser = useUnlockUser();
|
||||
const disable2FA = useDisableUser2FA();
|
||||
const terminateSessions = useTerminateUserSessions();
|
||||
|
||||
const filtered = users.filter(u => {
|
||||
@@ -210,6 +211,18 @@ function UsersTab() {
|
||||
<Unlock className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
{u.two_factor_enabled && (
|
||||
<Button
|
||||
variant="ghost" size="icon" className="h-7 w-7"
|
||||
title={t('users.disable_2fa')}
|
||||
onClick={() => disable2FA.mutate(u.id, {
|
||||
onSuccess: r => toast.success(r.message),
|
||||
onError: e => toast.error(getErrMsg(e)),
|
||||
})}
|
||||
>
|
||||
<ShieldOff className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost" size="icon" className="h-7 w-7"
|
||||
title={t('users.terminate_sessions')}
|
||||
|
||||
Reference in New Issue
Block a user