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;
|
||||
};
|
||||
109
frontend/src/contexts/NotificationContext.tsx
Normal file
109
frontend/src/contexts/NotificationContext.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
import React, { createContext, useContext, useState, ReactNode, useCallback } from 'react';
|
||||
import { Snackbar, Alert, AlertColor } from '@mui/material';
|
||||
|
||||
interface Notification {
|
||||
id: number;
|
||||
message: string;
|
||||
severity: AlertColor;
|
||||
}
|
||||
|
||||
interface NotificationContextType {
|
||||
showSuccess: (message: string) => void;
|
||||
showError: (message: string) => void;
|
||||
showWarning: (message: string) => void;
|
||||
showInfo: (message: string) => void;
|
||||
}
|
||||
|
||||
const NotificationContext = createContext<NotificationContextType | undefined>(undefined);
|
||||
|
||||
interface NotificationProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export const NotificationProvider: React.FC<NotificationProviderProps> = ({ children }) => {
|
||||
const [notifications, setNotifications] = useState<Notification[]>([]);
|
||||
const [currentNotification, setCurrentNotification] = useState<Notification | null>(null);
|
||||
|
||||
const addNotification = useCallback((message: string, severity: AlertColor) => {
|
||||
const id = Date.now();
|
||||
const notification: Notification = { id, message, severity };
|
||||
|
||||
setNotifications((prev) => [...prev, notification]);
|
||||
|
||||
// If no notification is currently displayed, show this one immediately
|
||||
if (!currentNotification) {
|
||||
setCurrentNotification(notification);
|
||||
}
|
||||
}, [currentNotification]);
|
||||
|
||||
const showSuccess = useCallback((message: string) => {
|
||||
addNotification(message, 'success');
|
||||
}, [addNotification]);
|
||||
|
||||
const showError = useCallback((message: string) => {
|
||||
addNotification(message, 'error');
|
||||
}, [addNotification]);
|
||||
|
||||
const showWarning = useCallback((message: string) => {
|
||||
addNotification(message, 'warning');
|
||||
}, [addNotification]);
|
||||
|
||||
const showInfo = useCallback((message: string) => {
|
||||
addNotification(message, 'info');
|
||||
}, [addNotification]);
|
||||
|
||||
const handleClose = (_event?: React.SyntheticEvent | Event, reason?: string) => {
|
||||
if (reason === 'clickaway') {
|
||||
return;
|
||||
}
|
||||
|
||||
setCurrentNotification(null);
|
||||
|
||||
// Show next notification after a short delay
|
||||
setTimeout(() => {
|
||||
setNotifications((prev) => {
|
||||
const remaining = prev.filter((n) => n.id !== currentNotification?.id);
|
||||
if (remaining.length > 0) {
|
||||
setCurrentNotification(remaining[0]);
|
||||
}
|
||||
return remaining;
|
||||
});
|
||||
}, 200);
|
||||
};
|
||||
|
||||
const value: NotificationContextType = {
|
||||
showSuccess,
|
||||
showError,
|
||||
showWarning,
|
||||
showInfo,
|
||||
};
|
||||
|
||||
return (
|
||||
<NotificationContext.Provider value={value}>
|
||||
{children}
|
||||
<Snackbar
|
||||
open={currentNotification !== null}
|
||||
autoHideDuration={6000}
|
||||
onClose={handleClose}
|
||||
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
|
||||
>
|
||||
<Alert
|
||||
onClose={handleClose}
|
||||
severity={currentNotification?.severity || 'info'}
|
||||
variant="filled"
|
||||
sx={{ width: '100%' }}
|
||||
>
|
||||
{currentNotification?.message}
|
||||
</Alert>
|
||||
</Snackbar>
|
||||
</NotificationContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useNotification = (): NotificationContextType => {
|
||||
const context = useContext(NotificationContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useNotification must be used within a NotificationProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
Reference in New Issue
Block a user