inital
This commit is contained in:
151
frontend/src/contexts/AuthContext.tsx
Normal file
151
frontend/src/contexts/AuthContext.tsx
Normal file
@@ -0,0 +1,151 @@
|
||||
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
||||
import { AuthContextType, AuthState, User } from '../types/auth.types';
|
||||
import { authService } from '../services/auth';
|
||||
import { getToken, setToken, removeToken, getUser, setUser, removeUser } from '../utils/storage';
|
||||
import { useNotification } from './NotificationContext';
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
interface AuthProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
|
||||
const notification = useNotification();
|
||||
const [state, setState] = useState<AuthState>({
|
||||
user: null,
|
||||
token: null,
|
||||
isAuthenticated: false,
|
||||
isLoading: true,
|
||||
});
|
||||
|
||||
// Check for existing token on mount
|
||||
useEffect(() => {
|
||||
const initializeAuth = async () => {
|
||||
const token = getToken();
|
||||
const user = getUser();
|
||||
|
||||
if (token && user) {
|
||||
setState({
|
||||
user,
|
||||
token,
|
||||
isAuthenticated: true,
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
// Optionally verify token is still valid
|
||||
try {
|
||||
await authService.getCurrentUser();
|
||||
} catch (error) {
|
||||
console.error('Token validation failed:', error);
|
||||
// Token is invalid, clear it
|
||||
removeToken();
|
||||
removeUser();
|
||||
setState({
|
||||
user: null,
|
||||
token: null,
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
setState({
|
||||
user: null,
|
||||
token: null,
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
initializeAuth();
|
||||
}, []);
|
||||
|
||||
const login = async (code: string): Promise<void> => {
|
||||
try {
|
||||
setState((prev) => ({ ...prev, isLoading: true }));
|
||||
|
||||
const { token, user } = await authService.handleCallback(code);
|
||||
|
||||
// Save to localStorage
|
||||
setToken(token);
|
||||
setUser(user);
|
||||
|
||||
// Update state
|
||||
setState({
|
||||
user,
|
||||
token,
|
||||
isAuthenticated: true,
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
// Show success notification
|
||||
notification.showSuccess('Anmeldung erfolgreich');
|
||||
} catch (error) {
|
||||
console.error('Login failed:', error);
|
||||
setState({
|
||||
user: null,
|
||||
token: null,
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
// Show error notification
|
||||
notification.showError('Anmeldung fehlgeschlagen. Bitte versuchen Sie es erneut.');
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const logout = (): void => {
|
||||
// Call backend logout (fire and forget)
|
||||
authService.logout().catch((error) => {
|
||||
console.error('Backend logout failed:', error);
|
||||
});
|
||||
|
||||
// Clear local state
|
||||
removeToken();
|
||||
removeUser();
|
||||
setState({
|
||||
user: null,
|
||||
token: null,
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
// Show logout notification
|
||||
notification.showSuccess('Abmeldung erfolgreich');
|
||||
|
||||
// Redirect to login after a short delay to show notification
|
||||
setTimeout(() => {
|
||||
window.location.href = '/login';
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
const refreshAuth = async (): Promise<void> => {
|
||||
try {
|
||||
const user = await authService.getCurrentUser();
|
||||
setUser(user);
|
||||
setState((prev) => ({ ...prev, user }));
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh user data:', error);
|
||||
logout();
|
||||
}
|
||||
};
|
||||
|
||||
const value: AuthContextType = {
|
||||
...state,
|
||||
login,
|
||||
logout,
|
||||
refreshAuth,
|
||||
};
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
};
|
||||
|
||||
export const useAuth = (): AuthContextType => {
|
||||
const context = useContext(AuthContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
Reference in New Issue
Block a user