Spaces:
Running
Running
axeronis commited on
Commit Β·
e45174b
1
Parent(s): dba382f
fix: auto-reload page when account changes in another tab
Browse files
frontend/contexts/AuthContext.tsx
CHANGED
|
@@ -156,6 +156,56 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|
| 156 |
checkAuth()
|
| 157 |
}, [])
|
| 158 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
// Helper to clear all auth state
|
| 160 |
const clearAuthState = () => {
|
| 161 |
localStorage.removeItem('auth_token')
|
|
|
|
| 156 |
checkAuth()
|
| 157 |
}, [])
|
| 158 |
|
| 159 |
+
// MULTI-TAB SYNC: Detect when user logs in/out in another tab
|
| 160 |
+
useEffect(() => {
|
| 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
|
| 167 |
+
const currentToken = token
|
| 168 |
+
|
| 169 |
+
// Token removed (logout in another tab)
|
| 170 |
+
if (!newToken && currentToken) {
|
| 171 |
+
console.log('π [AuthContext] Logout detected in another tab - reloading...')
|
| 172 |
+
window.location.href = '/login'
|
| 173 |
+
return
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
// Token changed (different user logged in)
|
| 177 |
+
if (newToken && newToken !== currentToken) {
|
| 178 |
+
console.log('π [AuthContext] Account change detected in another tab - reloading...')
|
| 179 |
+
window.location.reload()
|
| 180 |
+
return
|
| 181 |
+
}
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
// If cached user data changed
|
| 185 |
+
if (event.key === CACHE_KEY_USER) {
|
| 186 |
+
const newUserData = event.newValue
|
| 187 |
+
if (newUserData) {
|
| 188 |
+
try {
|
| 189 |
+
const newUser = JSON.parse(newUserData)
|
| 190 |
+
// If user ID changed, force reload
|
| 191 |
+
if (user && newUser.id !== user.id) {
|
| 192 |
+
console.log('π [AuthContext] User changed in another tab - reloading...')
|
| 193 |
+
window.location.reload()
|
| 194 |
+
}
|
| 195 |
+
} catch (e) {
|
| 196 |
+
// Invalid JSON, ignore
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
}
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
window.addEventListener('storage', handleStorageChange)
|
| 203 |
+
|
| 204 |
+
return () => {
|
| 205 |
+
window.removeEventListener('storage', handleStorageChange)
|
| 206 |
+
}
|
| 207 |
+
}, [token, user])
|
| 208 |
+
|
| 209 |
// Helper to clear all auth state
|
| 210 |
const clearAuthState = () => {
|
| 211 |
localStorage.removeItem('auth_token')
|