chore: git cache cleanup
This commit is contained in:
184
frontend/src/context/AuthContext.tsx
Normal file
184
frontend/src/context/AuthContext.tsx
Normal file
@@ -0,0 +1,184 @@
|
||||
import { useState, useEffect, useCallback, useRef, type ReactNode, type FC } from 'react';
|
||||
import client, { setAuthToken, setAuthErrorHandler } from '../api/client';
|
||||
import { AuthContext, User } from './AuthContextValue';
|
||||
|
||||
export const AuthProvider: FC<{ children: ReactNode }> = ({ children }) => {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const authRequestVersionRef = useRef(0);
|
||||
|
||||
const fetchSessionUser = useCallback(async (): Promise<User> => {
|
||||
const response = await fetch('/api/v1/auth/me', {
|
||||
method: 'GET',
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Session validation failed');
|
||||
}
|
||||
|
||||
return response.json() as Promise<User>;
|
||||
}, []);
|
||||
|
||||
const invalidateAuthRequests = useCallback(() => {
|
||||
authRequestVersionRef.current += 1;
|
||||
}, []);
|
||||
|
||||
// Handle session expiry by clearing auth state and redirecting to login
|
||||
const handleAuthError = useCallback(() => {
|
||||
console.warn('Session expired, clearing auth state');
|
||||
invalidateAuthRequests();
|
||||
localStorage.removeItem('charon_auth_token');
|
||||
setAuthToken(null);
|
||||
setUser(null);
|
||||
setIsLoading(false);
|
||||
}, [invalidateAuthRequests]);
|
||||
|
||||
// Register auth error handler on mount
|
||||
useEffect(() => {
|
||||
setAuthErrorHandler(handleAuthError);
|
||||
}, [handleAuthError]);
|
||||
|
||||
useEffect(() => {
|
||||
const checkAuth = async () => {
|
||||
const requestVersion = authRequestVersionRef.current + 1;
|
||||
authRequestVersionRef.current = requestVersion;
|
||||
|
||||
try {
|
||||
const stored = localStorage.getItem('charon_auth_token');
|
||||
if (stored) {
|
||||
setAuthToken(stored);
|
||||
} else {
|
||||
// No token in localStorage - don't even try to authenticate
|
||||
// This prevents re-authentication via HttpOnly cookie after logout
|
||||
setAuthToken(null);
|
||||
if (authRequestVersionRef.current === requestVersion) {
|
||||
setUser(null);
|
||||
setIsLoading(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const response = await fetchSessionUser();
|
||||
if (authRequestVersionRef.current === requestVersion) {
|
||||
setUser(response);
|
||||
}
|
||||
} catch {
|
||||
if (authRequestVersionRef.current === requestVersion) {
|
||||
setAuthToken(null);
|
||||
setUser(null);
|
||||
}
|
||||
} finally {
|
||||
if (authRequestVersionRef.current === requestVersion) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
checkAuth();
|
||||
}, [fetchSessionUser]);
|
||||
|
||||
const login = useCallback(async (token?: string) => {
|
||||
const requestVersion = authRequestVersionRef.current + 1;
|
||||
authRequestVersionRef.current = requestVersion;
|
||||
setIsLoading(true);
|
||||
|
||||
if (token) {
|
||||
localStorage.setItem('charon_auth_token', token);
|
||||
setAuthToken(token);
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetchSessionUser();
|
||||
if (authRequestVersionRef.current === requestVersion) {
|
||||
setUser(response);
|
||||
}
|
||||
} catch (error) {
|
||||
if (authRequestVersionRef.current === requestVersion) {
|
||||
setUser(null);
|
||||
setAuthToken(null);
|
||||
localStorage.removeItem('charon_auth_token');
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
if (authRequestVersionRef.current === requestVersion) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
}, [fetchSessionUser]);
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
invalidateAuthRequests();
|
||||
localStorage.removeItem('charon_auth_token');
|
||||
setAuthToken(null);
|
||||
setUser(null);
|
||||
setIsLoading(false);
|
||||
|
||||
try {
|
||||
await client.post('/auth/logout');
|
||||
} catch (error) {
|
||||
console.error("Logout failed", error);
|
||||
}
|
||||
}, [invalidateAuthRequests]);
|
||||
|
||||
const changePassword = async (oldPassword: string, newPassword: string) => {
|
||||
try {
|
||||
await client.post('/auth/change-password', {
|
||||
old_password: oldPassword,
|
||||
new_password: newPassword,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
// Extract error message from API response
|
||||
const message = error instanceof Error
|
||||
? error.message
|
||||
: typeof error === 'object' && error !== null && 'response' in error
|
||||
? (error as { response?: { data?: { error?: string } } }).response?.data?.error || 'Password change failed'
|
||||
: 'Password change failed';
|
||||
throw new Error(message, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Auto-logout logic
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
|
||||
const TIMEOUT_MS = 15 * 60 * 1000; // 15 minutes
|
||||
let timeoutId: ReturnType<typeof setTimeout>;
|
||||
|
||||
const resetTimer = () => {
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
timeoutId = setTimeout(() => {
|
||||
console.log('Auto-logging out due to inactivity');
|
||||
logout();
|
||||
}, TIMEOUT_MS);
|
||||
};
|
||||
|
||||
// Initial timer start
|
||||
resetTimer();
|
||||
|
||||
// Event listeners for activity
|
||||
const events = ['mousedown', 'keydown', 'scroll', 'touchstart'];
|
||||
const handleActivity = () => resetTimer();
|
||||
|
||||
events.forEach(event => {
|
||||
window.addEventListener(event, handleActivity);
|
||||
});
|
||||
|
||||
return () => {
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
events.forEach(event => {
|
||||
window.removeEventListener(event, handleActivity);
|
||||
});
|
||||
};
|
||||
}, [user, logout]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, login, logout, changePassword, isAuthenticated: !!user, isLoading }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
19
frontend/src/context/AuthContextValue.ts
Normal file
19
frontend/src/context/AuthContextValue.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export interface User {
|
||||
user_id: number;
|
||||
role: 'admin' | 'user' | 'passthrough';
|
||||
name?: string;
|
||||
email?: string;
|
||||
}
|
||||
|
||||
export interface AuthContextType {
|
||||
user: User | null;
|
||||
login: (token?: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
changePassword: (oldPassword: string, newPassword: string) => Promise<void>;
|
||||
isAuthenticated: boolean;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
32
frontend/src/context/LanguageContext.tsx
Normal file
32
frontend/src/context/LanguageContext.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
import { ReactNode, useState, useEffect } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { LanguageContext, Language } from './LanguageContextValue'
|
||||
|
||||
export function LanguageProvider({ children }: { children: ReactNode }) {
|
||||
const { i18n } = useTranslation()
|
||||
const [language, setLanguageState] = useState<Language>(() => {
|
||||
const saved = localStorage.getItem('charon-language')
|
||||
return (saved as Language) || 'en'
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
i18n.changeLanguage(language)
|
||||
}, [language, i18n])
|
||||
|
||||
const setLanguage = (lang: Language) => {
|
||||
setLanguageState(lang)
|
||||
localStorage.setItem('charon-language', lang)
|
||||
i18n.changeLanguage(lang)
|
||||
// Set document direction for RTL languages
|
||||
// Currently only LTR languages are supported (en, es, fr, de, zh)
|
||||
// When adding RTL languages (ar, he), update the Language type and this check:
|
||||
// document.documentElement.dir = ['ar', 'he'].includes(lang) ? 'rtl' : 'ltr'
|
||||
document.documentElement.dir = 'ltr'
|
||||
}
|
||||
|
||||
return (
|
||||
<LanguageContext.Provider value={{ language, setLanguage }}>
|
||||
{children}
|
||||
</LanguageContext.Provider>
|
||||
)
|
||||
}
|
||||
10
frontend/src/context/LanguageContextValue.ts
Normal file
10
frontend/src/context/LanguageContextValue.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { createContext } from 'react'
|
||||
|
||||
export type Language = 'en' | 'es' | 'fr' | 'de' | 'zh'
|
||||
|
||||
export interface LanguageContextType {
|
||||
language: Language
|
||||
setLanguage: (lang: Language) => void
|
||||
}
|
||||
|
||||
export const LanguageContext = createContext<LanguageContextType | undefined>(undefined)
|
||||
26
frontend/src/context/ThemeContext.tsx
Normal file
26
frontend/src/context/ThemeContext.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import { useEffect, useState, ReactNode } from 'react'
|
||||
import { ThemeContext, Theme } from './ThemeContextValue'
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [theme, setTheme] = useState<Theme>(() => {
|
||||
const saved = localStorage.getItem('theme')
|
||||
return (saved as Theme) || 'dark'
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
const root = window.document.documentElement
|
||||
root.classList.remove('light', 'dark')
|
||||
root.classList.add(theme)
|
||||
localStorage.setItem('theme', theme)
|
||||
}, [theme])
|
||||
|
||||
const toggleTheme = () => {
|
||||
setTheme(prev => prev === 'dark' ? 'light' : 'dark')
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={{ theme, toggleTheme }}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
)
|
||||
}
|
||||
10
frontend/src/context/ThemeContextValue.ts
Normal file
10
frontend/src/context/ThemeContextValue.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { createContext } from 'react'
|
||||
|
||||
export type Theme = 'dark' | 'light'
|
||||
|
||||
export interface ThemeContextType {
|
||||
theme: Theme
|
||||
toggleTheme: () => void
|
||||
}
|
||||
|
||||
export const ThemeContext = createContext<ThemeContextType | undefined>(undefined)
|
||||
Reference in New Issue
Block a user