cb7d7121c5
Add modern React frontend to replace Streamlit dashboard: - Vite build system with TypeScript - Tailwind CSS for styling - Component structure in src/ - Production Dockerfile with nginx - Development server on port 5173 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
82 lines
1.9 KiB
TypeScript
82 lines
1.9 KiB
TypeScript
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
|
import { authApi, getAccessToken } from '../api/client';
|
|
import type { User } from '../types';
|
|
|
|
interface AuthContextType {
|
|
user: User | null;
|
|
isLoading: boolean;
|
|
isAuthenticated: boolean;
|
|
isAdmin: boolean;
|
|
login: (email: string, password: string) => Promise<void>;
|
|
register: (email: string, password: string) => Promise<void>;
|
|
logout: () => void;
|
|
refreshUser: () => Promise<void>;
|
|
}
|
|
|
|
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
|
|
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
|
const [user, setUser] = useState<User | null>(null);
|
|
const [isLoading, setIsLoading] = useState(true);
|
|
|
|
const refreshUser = async () => {
|
|
try {
|
|
const userData = await authApi.getMe();
|
|
setUser(userData);
|
|
} catch {
|
|
setUser(null);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
const initAuth = async () => {
|
|
if (getAccessToken()) {
|
|
await refreshUser();
|
|
}
|
|
setIsLoading(false);
|
|
};
|
|
initAuth();
|
|
}, []);
|
|
|
|
const login = async (email: string, password: string) => {
|
|
await authApi.login(email, password);
|
|
await refreshUser();
|
|
};
|
|
|
|
const register = async (email: string, password: string) => {
|
|
await authApi.register(email, password);
|
|
await authApi.login(email, password);
|
|
await refreshUser();
|
|
};
|
|
|
|
const logout = () => {
|
|
authApi.logout();
|
|
setUser(null);
|
|
};
|
|
|
|
return (
|
|
<AuthContext.Provider
|
|
value={{
|
|
user,
|
|
isLoading,
|
|
isAuthenticated: !!user,
|
|
isAdmin: user?.role === 'admin',
|
|
login,
|
|
register,
|
|
logout,
|
|
refreshUser,
|
|
}}
|
|
>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useAuth() {
|
|
const context = useContext(AuthContext);
|
|
if (context === undefined) {
|
|
throw new Error('useAuth must be used within an AuthProvider');
|
|
}
|
|
return context;
|
|
}
|