feat(auth): имперсонация — вход админа под пользователем и возврат обратно
Backend:
- POST /api/auth/impersonate/{user_id} — только для админа, выдаёт JWT
с клеймом impersonator; запрещает вход под собой, отключённым,
другим админом и вложенную имперсонацию
- POST /api/auth/stop-impersonate — по клейму impersonator завершает
сессию имперсонации и перевыпускает токен исходного админа
- /api/auth/me отдаёт поле impersonator для баннера в SPA
- аудит-лог: impersonate_start / impersonate_stop
Frontend:
- auth-store: действия impersonate/stopImpersonate со сбросом кэша
React Query при смене токена
- UsersPage: кнопка "войти под пользователем" (только админу,
скрыта для себя/админов/неактивных и во время имперсонации)
- AppLayout: баннер имперсонации с кнопкой "вернуться к администратору"
- локали ru/en
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
Search, Plus, Shield, ShieldOff, Trash2, RotateCcw, Unlock, Pencil, Server, LogOut, Ban, KeyRound, Gauge,
|
||||
Search, Plus, Shield, ShieldOff, Trash2, RotateCcw, Unlock, Pencil, Server, LogOut, Ban, KeyRound, Gauge, UserCog,
|
||||
} from 'lucide-react';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
@@ -31,6 +32,7 @@ import {
|
||||
type Role, type SecuritySettings,
|
||||
} from '@/hooks/use-users';
|
||||
import { SSHKeysManager } from '@/features/settings/SSHKeysManager';
|
||||
import { useAuthStore } from '@/stores/auth-store';
|
||||
|
||||
// ==================== Helpers ====================
|
||||
|
||||
@@ -83,6 +85,9 @@ export default function UsersPage() {
|
||||
|
||||
function UsersTab() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const currentUser = useAuthStore(s => s.user);
|
||||
const impersonate = useAuthStore(s => s.impersonate);
|
||||
const [search, setSearch] = useState('');
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [editUser, setEditUser] = useState<User | null>(null);
|
||||
@@ -97,6 +102,18 @@ function UsersTab() {
|
||||
const disable2FA = useDisableUser2FA();
|
||||
const terminateSessions = useTerminateUserSessions();
|
||||
|
||||
const canImpersonate = !!currentUser?.is_admin && !currentUser?.impersonator;
|
||||
|
||||
const handleImpersonate = async (u: User) => {
|
||||
try {
|
||||
await impersonate(u.id);
|
||||
toast.success(t('users.impersonate_started', { name: u.username }));
|
||||
navigate('/dashboard');
|
||||
} catch (e) {
|
||||
toast.error(getErrMsg(e));
|
||||
}
|
||||
};
|
||||
|
||||
const filtered = users.filter(u => {
|
||||
if (!search) return true;
|
||||
const s = search.toLowerCase();
|
||||
@@ -193,6 +210,15 @@ function UsersTab() {
|
||||
>
|
||||
<KeyRound className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
{canImpersonate && !u.is_admin && u.id !== currentUser?.id && u.is_active && (
|
||||
<Button
|
||||
variant="ghost" size="icon" className="h-7 w-7"
|
||||
title={t('users.impersonate')}
|
||||
onClick={() => handleImpersonate(u)}
|
||||
>
|
||||
<UserCog className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost" size="icon" className="h-7 w-7"
|
||||
title={t('users.reset_password')}
|
||||
|
||||
@@ -11,7 +11,9 @@ import {
|
||||
Check,
|
||||
Search,
|
||||
FolderKanban,
|
||||
UserCog,
|
||||
} from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
|
||||
import {
|
||||
@@ -183,6 +185,41 @@ function WorkspaceSwitcher() {
|
||||
);
|
||||
}
|
||||
|
||||
function ImpersonationBanner() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const stopImpersonate = useAuthStore((s) => s.stopImpersonate);
|
||||
|
||||
if (!user?.impersonator) return null;
|
||||
|
||||
const handleReturn = async () => {
|
||||
try {
|
||||
await stopImpersonate();
|
||||
toast.success(t('users.impersonate_stopped'));
|
||||
navigate('/dashboard');
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-3 border-b border-amber-500/40 bg-amber-500/15 px-4 py-2 text-sm text-amber-700 dark:text-amber-300 lg:px-6">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<UserCog className="h-4 w-4 shrink-0" />
|
||||
<span className="truncate">
|
||||
{t('users.impersonating_as', { name: user.username })}
|
||||
<span className="text-muted-foreground"> · {t('users.impersonated_by', { name: user.impersonator })}</span>
|
||||
</span>
|
||||
</div>
|
||||
<Button size="sm" variant="outline" onClick={handleReturn} className="shrink-0">
|
||||
<LogOut className="mr-1.5 h-3.5 w-3.5" />
|
||||
{t('users.return_to_admin')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TopBar() {
|
||||
const { theme, toggleTheme } = useThemeStore();
|
||||
const { i18n, t } = useTranslation();
|
||||
@@ -263,6 +300,7 @@ export default function AppLayout() {
|
||||
|
||||
{/* Main area */}
|
||||
<div className="flex flex-1 flex-col overflow-hidden">
|
||||
<ImpersonationBanner />
|
||||
<TopBar />
|
||||
<main className="flex-1 overflow-y-auto p-4 lg:p-6">
|
||||
<Outlet />
|
||||
|
||||
@@ -1383,6 +1383,12 @@
|
||||
"reset_password": "Reset Password",
|
||||
"new_password": "New password",
|
||||
"unlock": "Unlock",
|
||||
"impersonate": "Log in as this user",
|
||||
"impersonate_started": "You are now logged in as {{name}}",
|
||||
"impersonate_stopped": "Returned to your admin account",
|
||||
"impersonating_as": "Viewing as {{name}}",
|
||||
"impersonated_by": "impersonated by {{name}}",
|
||||
"return_to_admin": "Return to admin",
|
||||
"manage_servers": "Assigned Servers",
|
||||
"manage_ssh_keys": "Manage SSH Keys",
|
||||
"assigned_servers": "Assigned Servers",
|
||||
|
||||
@@ -1382,6 +1382,12 @@
|
||||
"require_password_change": "Требовать смену пароля",
|
||||
"reset_password": "Сбросить пароль",
|
||||
"new_password": "Новый пароль",
|
||||
"impersonate": "Войти под этим пользователем",
|
||||
"impersonate_started": "Вы вошли как {{name}}",
|
||||
"impersonate_stopped": "Возврат в учётную запись администратора",
|
||||
"impersonating_as": "Просмотр от имени {{name}}",
|
||||
"impersonated_by": "администратор {{name}}",
|
||||
"return_to_admin": "Вернуться к администратору",
|
||||
"unlock": "Разблокировать",
|
||||
"manage_servers": "Назначенные серверы",
|
||||
"manage_ssh_keys": "Управление SSH ключами",
|
||||
|
||||
@@ -13,9 +13,25 @@ interface AuthState {
|
||||
login: (credentials: LoginRequest) => Promise<{ twoFactorRequired: boolean }>;
|
||||
logout: () => Promise<void>;
|
||||
loadUser: () => Promise<void>;
|
||||
impersonate: (userId: number) => Promise<void>;
|
||||
stopImpersonate: () => Promise<void>;
|
||||
clearError: () => void;
|
||||
}
|
||||
|
||||
// Swap the active token for a freshly-issued one (impersonation start/stop),
|
||||
// resetting the React Query cache so the previous identity's data cannot leak,
|
||||
// then reload the current-user info under the new token.
|
||||
async function switchToken(
|
||||
set: (partial: Partial<AuthState>) => void,
|
||||
token: string,
|
||||
): Promise<void> {
|
||||
apiClient.setToken(token);
|
||||
queryClient.clear();
|
||||
set({ token, isAuthenticated: true });
|
||||
const user = await apiClient.get<User>('/api/auth/me');
|
||||
set({ user });
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>((set) => ({
|
||||
user: null,
|
||||
token: localStorage.getItem('access_token'),
|
||||
@@ -81,5 +97,17 @@ export const useAuthStore = create<AuthState>((set) => ({
|
||||
}
|
||||
},
|
||||
|
||||
impersonate: async (userId: number) => {
|
||||
const data = await apiClient.post<AuthResponse>(`/api/auth/impersonate/${userId}`);
|
||||
if (!data.access_token) throw new Error('Impersonation failed');
|
||||
await switchToken(set, data.access_token);
|
||||
},
|
||||
|
||||
stopImpersonate: async () => {
|
||||
const data = await apiClient.post<AuthResponse>('/api/auth/stop-impersonate');
|
||||
if (!data.access_token) throw new Error('Failed to return to admin');
|
||||
await switchToken(set, data.access_token);
|
||||
},
|
||||
|
||||
clearError: () => set({ error: null }),
|
||||
}));
|
||||
|
||||
@@ -16,6 +16,9 @@ export interface User {
|
||||
locked_until?: string | null;
|
||||
require_password_change?: boolean;
|
||||
two_factor_enabled?: boolean;
|
||||
// Set to the original admin's username while that admin is impersonating this
|
||||
// user; null/undefined during a normal session.
|
||||
impersonator?: string | null;
|
||||
// Map of "resource:action" -> granted. Admins receive every permission.
|
||||
permissions?: Record<string, boolean>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user