Spaces:
Running

axeronis commited on
Commit
6bfac6b
·
1 Parent(s): e45174b

fix: admin impersonation opens new tab, preserves admin session

Browse files
frontend/app/auth/impersonate/page.tsx ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use client'
2
+
3
+ import { useEffect, useState } from 'react'
4
+ import { useSearchParams } from 'next/navigation'
5
+
6
+ /**
7
+ * Impersonation Page
8
+ *
9
+ * This page is opened in a new tab by admin when they click "Login as user".
10
+ * It receives the token via URL parameter and stores it in localStorage,
11
+ * then redirects to dashboard.
12
+ *
13
+ * This allows admin to stay logged in in the original tab while
14
+ * the new tab has the impersonated user's session.
15
+ */
16
+ export default function ImpersonatePage() {
17
+ const searchParams = useSearchParams()
18
+ const [error, setError] = useState<string | null>(null)
19
+
20
+ useEffect(() => {
21
+ const token = searchParams.get('token')
22
+
23
+ if (!token) {
24
+ setError('Токен не найден в URL')
25
+ return
26
+ }
27
+
28
+ try {
29
+ // Clear any existing auth data in THIS tab's storage
30
+ localStorage.clear()
31
+ sessionStorage.clear()
32
+
33
+ // Set the impersonated user's token
34
+ localStorage.setItem('auth_token', token)
35
+
36
+ // Set cookie for middleware
37
+ document.cookie = `auth_token=${token}; path=/; max-age=${7 * 24 * 60 * 60}; SameSite=Lax`
38
+
39
+ // Redirect to dashboard
40
+ console.log('🎭 [Impersonate] Token set, redirecting to dashboard...')
41
+ window.location.href = '/dashboard'
42
+ } catch (e) {
43
+ setError('Ошибка при сохранении токена')
44
+ console.error('Impersonate error:', e)
45
+ }
46
+ }, [searchParams])
47
+
48
+ if (error) {
49
+ return (
50
+ <div className="min-h-screen bg-background flex items-center justify-center">
51
+ <div className="text-center">
52
+ <h1 className="text-xl font-bold text-red-400 mb-2">Ошибка</h1>
53
+ <p className="text-slate-400">{error}</p>
54
+ <a href="/login" className="text-indigo-400 hover:underline mt-4 inline-block">
55
+ Перейти на страницу входа
56
+ </a>
57
+ </div>
58
+ </div>
59
+ )
60
+ }
61
+
62
+ return (
63
+ <div className="min-h-screen bg-background flex items-center justify-center">
64
+ <div className="text-center">
65
+ <div className="w-8 h-8 rounded-full border-2 border-indigo-500 border-t-transparent animate-spin mx-auto mb-4"></div>
66
+ <p className="text-slate-400">Вход под пользователем...</p>
67
+ </div>
68
+ </div>
69
+ )
70
+ }
frontend/components/admin/UsersTab.tsx CHANGED
@@ -59,7 +59,7 @@ export default function UsersTab() {
59
  }
60
 
61
  const handleImpersonate = async (userId: string) => {
62
- if (!confirm('Вы уверены, что хотите войти под этим пользователем?')) return
63
  try {
64
  const res = await fetch(`/api/v1/admin/users/${userId}/impersonate`, {
65
  method: 'POST',
@@ -67,9 +67,15 @@ export default function UsersTab() {
67
  })
68
  if (res.ok) {
69
  const data = await res.json()
70
- localStorage.setItem('auth_token', data.access_token)
71
- toast.success('Успех', 'Вход выполнен! Перенаправление...')
72
- setTimeout(() => window.location.href = '/dashboard', 1000)
 
 
 
 
 
 
73
  }
74
  } catch (error) { toast.error('Ошибка', 'Ошибка сети') }
75
  }
 
59
  }
60
 
61
  const handleImpersonate = async (userId: string) => {
62
+ if (!confirm('Вы уверены, что хотите войти под этим пользователем? Откроется новая вкладка.')) return
63
  try {
64
  const res = await fetch(`/api/v1/admin/users/${userId}/impersonate`, {
65
  method: 'POST',
 
67
  })
68
  if (res.ok) {
69
  const data = await res.json()
70
+ // Open in NEW TAB with token in URL - admin stays logged in!
71
+ const newWindow = window.open(`/auth/impersonate?token=${data.access_token}`, '_blank')
72
+ if (newWindow) {
73
+ toast.success('Успех', 'Новая вкладка открыта с аккаунтом пользователя')
74
+ } else {
75
+ // Popup blocked - fallback to copying token
76
+ navigator.clipboard.writeText(data.access_token)
77
+ toast.info('Popup заблокирован', 'Токен скопирован в буфер. Откройте /auth/impersonate вручную.')
78
+ }
79
  }
80
  } catch (error) { toast.error('Ошибка', 'Ошибка сети') }
81
  }
frontend/contexts/AuthContext.tsx CHANGED
@@ -161,6 +161,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
161
  if (typeof window === 'undefined') return
162
 
163
  const handleStorageChange = (event: StorageEvent) => {
 
 
 
 
 
 
164
  // If auth_token changed in another tab
165
  if (event.key === 'auth_token') {
166
  const newToken = event.newValue
 
161
  if (typeof window === 'undefined') return
162
 
163
  const handleStorageChange = (event: StorageEvent) => {
164
+ // SKIP sync on admin pages - admin may be impersonating in another tab
165
+ if (window.location.pathname.startsWith('/admin')) {
166
+ console.log('🔄 [AuthContext] On admin page, skipping storage sync')
167
+ return
168
+ }
169
+
170
  // If auth_token changed in another tab
171
  if (event.key === 'auth_token') {
172
  const newToken = event.newValue