feat(auth): двухфакторная аутентификация (TOTP) для входа в панель
All checks were successful
Backend Tests / pytest (Python 3.12) (push) Successful in 58s
Deploy to Production / Trigger production update (push) Successful in 8s

Бэкенд:
- 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:
markmorado
2026-07-06 21:08:38 +05:00
parent fc42e8fc19
commit bec7b20e31
16 changed files with 671 additions and 64 deletions

View File

@@ -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>

View File

@@ -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();

View File

@@ -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')}

View File

@@ -181,6 +181,15 @@ export function useTerminateUserSessions() {
});
}
export function useDisableUser2FA() {
const qc = useQueryClient();
return useMutation({
mutationFn: (userId: number) =>
apiClient.post<{ message: string }>(`/admin/api/users/${userId}/disable-2fa`),
onSuccess: () => qc.invalidateQueries({ queryKey: userKeys.users }),
});
}
// ==================== User → Servers ====================
export function useUserServerAssignments(userId: number) {

View File

@@ -69,6 +69,11 @@
"forgot_password": "Forgot password",
"show_password": "Show password",
"hide_password": "Hide password",
"two_factor_code": "Authentication code",
"two_factor_placeholder": "6-digit code or backup code",
"two_factor_hint": "Enter the code from your authenticator app, or a backup code.",
"verify": "Verify",
"back": "Back",
"logout": "Logout"
},
"reset": {
@@ -1101,6 +1106,26 @@
"new_password": "New Password",
"confirm_password": "Confirm Password",
"password_mismatch": "Passwords do not match",
"tfa": {
"title": "Two-Factor Authentication",
"on": "Enabled",
"off": "Disabled",
"description": "Extra login protection: a one-time code from an authenticator app (Google Authenticator, Authy, 1Password, etc.).",
"enable": "Enable 2FA",
"disable": "Disable 2FA",
"confirm_disable": "Confirm disable",
"current_code": "Current code (or backup)",
"verify_enable": "Verify & enable",
"enter_code": "Enter the code from the app",
"scan_hint": "Scan the QR code in your authenticator app.",
"manual_key": "Or enter the key manually:",
"backup_codes_title": "Backup codes",
"backup_codes_hint": "Store these one-time codes somewhere safe. Each works once and replaces your app code if you lose access. Shown only now.",
"copy_codes": "Copy codes",
"backup_remaining": "Backup codes remaining: {{count}}",
"enabled_ok": "Two-factor authentication enabled",
"disabled_ok": "Two-factor authentication disabled"
},
"panel_settings": "Panel Settings",
"panel_name": "Panel Name",
"language": "Language",
@@ -1191,6 +1216,7 @@
"incompatible": "Incompatible",
"failed_attempts": "Failed Attempts",
"terminate_sessions": "Terminate Sessions",
"disable_2fa": "Disable user's 2FA",
"terminate_all_sessions": "Terminate All Sessions",
"permissions_count": "Permissions",
"permissions": "Permissions",

View File

@@ -69,6 +69,11 @@
"forgot_password": "Я не помню пароль",
"show_password": "Показать пароль",
"hide_password": "Скрыть пароль",
"two_factor_code": "Код подтверждения",
"two_factor_placeholder": "6-значный или резервный код",
"two_factor_hint": "Введите код из приложения-аутентификатора или резервный код.",
"verify": "Подтвердить",
"back": "Назад",
"logout": "Выход"
},
"reset": {
@@ -1101,6 +1106,26 @@
"new_password": "Новый пароль",
"confirm_password": "Подтвердите пароль",
"password_mismatch": "Пароли не совпадают",
"tfa": {
"title": "Двухфакторная аутентификация",
"on": "Включена",
"off": "Выключена",
"description": "Дополнительная защита входа: одноразовый код из приложения-аутентификатора (Google Authenticator, Authy, 1Password и т.п.).",
"enable": "Включить 2FA",
"disable": "Отключить 2FA",
"confirm_disable": "Подтвердить отключение",
"current_code": "Текущий код (или резервный)",
"verify_enable": "Проверить и включить",
"enter_code": "Введите код из приложения",
"scan_hint": "Отсканируйте QR-код в приложении-аутентификаторе.",
"manual_key": "Или введите ключ вручную:",
"backup_codes_title": "Резервные коды",
"backup_codes_hint": "Сохраните эти одноразовые коды в надёжном месте. Каждый работает один раз и заменяет код из приложения, если у вас нет доступа к нему. Показываются только сейчас.",
"copy_codes": "Скопировать коды",
"backup_remaining": "Осталось резервных кодов: {{count}}",
"enabled_ok": "Двухфакторная аутентификация включена",
"disabled_ok": "Двухфакторная аутентификация отключена"
},
"panel_settings": "Настройки панели",
"panel_name": "Название панели",
"language": "Язык",
@@ -1191,6 +1216,7 @@
"incompatible": "Несовместим",
"failed_attempts": "Неуд. попыток",
"terminate_sessions": "Завершить сессии",
"disable_2fa": "Отключить 2FA пользователя",
"terminate_all_sessions": "Завершить все сессии",
"permissions_count": "Разрешения",
"permissions": "Разрешения",

View File

@@ -9,7 +9,7 @@ interface AuthState {
isLoading: boolean;
error: string | null;
login: (credentials: LoginRequest) => Promise<void>;
login: (credentials: LoginRequest) => Promise<{ twoFactorRequired: boolean }>;
logout: () => Promise<void>;
loadUser: () => Promise<void>;
clearError: () => void;
@@ -26,12 +26,20 @@ export const useAuthStore = create<AuthState>((set) => ({
set({ isLoading: true, error: null });
try {
const data = await apiClient.post<AuthResponse>('/api/auth/login', credentials);
// Password accepted but a second factor is still required.
if (data.two_factor_required || !data.access_token) {
set({ isLoading: false });
return { twoFactorRequired: true };
}
apiClient.setToken(data.access_token);
set({ token: data.access_token, isAuthenticated: true, isLoading: false });
// Load user info
const user = await apiClient.get<User>('/api/auth/me');
set({ user });
return { twoFactorRequired: false };
} catch (err) {
const message = err instanceof Error ? err.message : 'Login failed';
set({ error: message, isLoading: false, isAuthenticated: false });

View File

@@ -15,6 +15,7 @@ export interface User {
failed_login_attempts?: number;
locked_until?: string | null;
require_password_change?: boolean;
two_factor_enabled?: boolean;
// Map of "resource:action" -> granted. Admins receive every permission.
permissions?: Record<string, boolean>;
}
@@ -22,41 +23,43 @@ export interface User {
export interface LoginRequest {
username: string;
password: string;
code?: string;
}
export interface AuthResponse {
access_token: string;
access_token?: string;
token_type: string;
session_id?: string;
two_factor_required?: boolean;
}
// ==================== Proxmox Server Types ====================
export interface ProxmoxServer {
id: number;
name: string;
export interface ServerWorkspaceBrief {
id: number;
name: string;
color?: string;
}
export interface ProxmoxServer {
id: number;
name: string;
hostname: string;
ip_address: string;
port: number;
api_user: string;
verify_ssl: boolean;
cluster_name?: string;
description?: string;
created_at: string;
updated_at: string;
cluster_name?: string;
last_check?: string;
is_online?: boolean;
last_error?: string;
workspaces?: ServerWorkspaceBrief[];
}
export interface ProxmoxServerCreate {
workspaces?: ServerWorkspaceBrief[];
name: string;
hostname: string;
ip_address: string;