🔧 Enhance Middleware and Admin Features

 Updated Middleware Logic:
- Enhanced admin route protection with Basic Auth for legacy routes and session-based auth for `/manage` and `/editor`.

 Improved Admin Panel Styles:
- Added glassmorphism styles for admin components to enhance UI aesthetics.

 Refined Rate Limiting:
- Adjusted rate limits for admin dashboard requests to allow more generous access.

 Introduced Analytics Reset API:
- Added a new endpoint for resetting analytics data with rate limiting and admin authentication.

🎯 Overall Improvements:
- Strengthened security and user experience for admin functionalities.
- Enhanced visual design for better usability.
- Streamlined analytics management processes.
This commit is contained in:
2025-09-09 19:50:52 +02:00
parent 0ae1883cf4
commit be01ee2adb
26 changed files with 4518 additions and 1103 deletions

View File

@@ -2,13 +2,12 @@
import { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
Lock,
Eye,
EyeOff,
Shield,
AlertTriangle,
CheckCircle,
import {
Lock,
Eye,
EyeOff,
Shield,
AlertTriangle,
XCircle,
Loader2
} from 'lucide-react';
@@ -17,11 +16,8 @@ import ModernAdminDashboard from '@/components/ModernAdminDashboard';
// Security constants
const MAX_ATTEMPTS = 3;
const LOCKOUT_DURATION = 15 * 60 * 1000; // 15 minutes
const SESSION_DURATION = 2 * 60 * 60 * 1000; // 2 hours (reduced from 24h)
const RATE_LIMIT_DELAY = 1000; // 1 second base delay
// Password hashing removed - now handled server-side securely
// Rate limiting with exponential backoff
const getRateLimitDelay = (attempts: number): number => {
return RATE_LIMIT_DELAY * Math.pow(2, attempts);
@@ -63,8 +59,8 @@ const AdminPage = () => {
setAuthState(prev => ({ ...prev, csrfToken: data.csrfToken }));
return data.csrfToken;
}
} catch (error) {
console.error('Failed to fetch CSRF token:', error);
} catch {
console.error('Failed to fetch CSRF token');
}
return '';
}, []);
@@ -88,7 +84,7 @@ const AdminPage = () => {
} else {
localStorage.removeItem('admin_lockout');
}
} catch (error) {
} catch {
localStorage.removeItem('admin_lockout');
}
}
@@ -99,81 +95,79 @@ const AdminPage = () => {
const checkSession = useCallback(async () => {
const authStatus = sessionStorage.getItem('admin_authenticated');
const sessionToken = sessionStorage.getItem('admin_session_token');
if (!authStatus || !sessionToken) {
setAuthState(prev => ({ ...prev, showLogin: true, isLoading: false }));
return false;
}
const csrfToken = authState.csrfToken;
try {
// Validate session with server
const response = await fetch('/api/auth/validate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': authState.csrfToken
},
body: JSON.stringify({
sessionToken,
csrfToken: authState.csrfToken
})
});
if (authStatus === 'true' && sessionToken && csrfToken) {
try {
const response = await fetch('/api/auth/validate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken
},
body: JSON.stringify({
sessionToken,
csrfToken
})
});
const data = await response.json();
if (response.ok && data.valid) {
setAuthState(prev => ({
...prev,
isAuthenticated: true,
isLoading: false,
showLogin: false
}));
return true;
} else {
// Session invalid, clear storage
if (response.ok) {
setAuthState(prev => ({
...prev,
isAuthenticated: true,
isLoading: false,
showLogin: false
}));
return;
} else {
sessionStorage.clear();
}
} catch {
sessionStorage.clear();
setAuthState(prev => ({ ...prev, showLogin: true, isLoading: false }));
return false;
}
} catch (error) {
// Network error, clear session
sessionStorage.clear();
setAuthState(prev => ({ ...prev, showLogin: true, isLoading: false }));
return false;
}
}, []);
// Initialize authentication check
setAuthState(prev => ({
...prev,
isAuthenticated: false,
isLoading: false,
showLogin: true
}));
}, [authState.csrfToken]);
// Initialize
useEffect(() => {
const initAuth = async () => {
// Add random delay to prevent timing attacks
await new Promise(resolve => setTimeout(resolve, Math.random() * 500 + 200));
// Fetch CSRF token first
await fetchCSRFToken();
if (!checkLockout()) {
await checkSession();
const init = async () => {
if (checkLockout()) return;
const token = await fetchCSRFToken();
if (token) {
setAuthState(prev => ({ ...prev, csrfToken: token }));
}
};
init();
}, [checkLockout, fetchCSRFToken]);
initAuth();
}, [checkLockout, checkSession, fetchCSRFToken]);
useEffect(() => {
if (authState.csrfToken && !authState.isLocked) {
checkSession();
}
}, [authState.csrfToken, authState.isLocked, checkSession]);
// Handle login submission
// Handle login form submission
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
if (authState.isLocked || authState.isLoading) return;
if (!authState.password.trim() || authState.isLoading) return;
setAuthState(prev => ({ ...prev, isLoading: true, error: '' }));
try {
// Rate limiting delay
const delay = getRateLimitDelay(authState.attempts);
await new Promise(resolve => setTimeout(resolve, delay));
// Rate limiting delay
const delay = getRateLimitDelay(authState.attempts);
await new Promise(resolve => setTimeout(resolve, delay));
// Send login request to secure API
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: {
@@ -189,15 +183,14 @@ const AdminPage = () => {
const data = await response.json();
if (response.ok && data.success) {
// Successful login
const now = Date.now();
const sessionToken = data.sessionToken;
localStorage.removeItem('admin_lockout');
// Store session
sessionStorage.setItem('admin_authenticated', 'true');
sessionStorage.setItem('admin_login_time', now.toString());
sessionStorage.setItem('admin_session_token', sessionToken);
sessionStorage.setItem('admin_session_token', data.sessionToken);
// Clear lockout data
localStorage.removeItem('admin_lockout');
// Update state
setAuthState(prev => ({
...prev,
isAuthenticated: true,
@@ -225,7 +218,7 @@ const AdminPage = () => {
attempts: newAttempts,
lastAttempt: newLastAttempt,
isLoading: false,
error: `Zu viele fehlgeschlagene Versuche. Zugang für ${Math.ceil(LOCKOUT_DURATION / 60000)} Minuten gesperrt.`
error: `Too many failed attempts. Access locked for ${Math.ceil(LOCKOUT_DURATION / 60000)} minutes.`
}));
} else {
setAuthState(prev => ({
@@ -233,32 +226,20 @@ const AdminPage = () => {
attempts: newAttempts,
lastAttempt: newLastAttempt,
isLoading: false,
error: data.error || `Falsches Passwort. ${MAX_ATTEMPTS - newAttempts} Versuche übrig.`,
error: data.error || `Wrong password. ${MAX_ATTEMPTS - newAttempts} attempts remaining.`,
password: ''
}));
}
}
} catch (error) {
} catch {
setAuthState(prev => ({
...prev,
isLoading: false,
error: 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.'
error: 'An error occurred. Please try again.'
}));
}
};
// Handle logout
const handleLogout = () => {
sessionStorage.clear();
setAuthState(prev => ({
...prev,
isAuthenticated: false,
showLogin: true,
password: '',
error: ''
}));
};
// Get remaining lockout time
const getRemainingTime = () => {
const lockoutData = localStorage.getItem('admin_lockout');
@@ -277,17 +258,21 @@ const AdminPage = () => {
// Loading state
if (authState.isLoading && !authState.showLogin) {
return (
<div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center">
<motion.div
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
className="text-center"
>
<div className="w-16 h-16 bg-gradient-to-r from-blue-500 to-purple-500 rounded-full flex items-center justify-center mx-auto mb-4">
<Loader2 className="w-8 h-8 text-white animate-spin" />
</div>
<p className="text-white text-lg">Überprüfe Berechtigung...</p>
</motion.div>
<div className="min-h-screen">
<div className="fixed inset-0 animated-bg"></div>
<div className="relative z-10 min-h-screen flex items-center justify-center">
<motion.div
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
className="text-center admin-glass-card p-8 rounded-2xl"
>
<div className="w-16 h-16 bg-gradient-to-r from-blue-500 to-purple-500 rounded-2xl flex items-center justify-center mx-auto mb-6 shadow-lg">
<Loader2 className="w-8 h-8 text-white animate-spin" />
</div>
<p className="text-white text-xl font-semibold">Verifying Access...</p>
<p className="text-white/60 text-sm mt-2">Please wait while we authenticate your session</p>
</motion.div>
</div>
</div>
);
}
@@ -295,34 +280,45 @@ const AdminPage = () => {
// Lockout state
if (authState.isLocked) {
return (
<div className="min-h-screen bg-gradient-to-br from-red-900 via-gray-900 to-red-900 flex items-center justify-center p-4">
<motion.div
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
className="bg-white/10 backdrop-blur-md rounded-2xl border border-red-500/30 p-8 max-w-md w-full text-center"
>
<div className="mb-6">
<Shield className="w-16 h-16 text-red-400 mx-auto mb-4" />
<h1 className="text-2xl font-bold text-white mb-2">Zugang gesperrt</h1>
<p className="text-gray-300">
Zu viele fehlgeschlagene Anmeldeversuche
</p>
</div>
<div className="bg-red-500/20 border border-red-500/30 rounded-lg p-4 mb-6">
<AlertTriangle className="w-8 h-8 text-red-400 mx-auto mb-2" />
<p className="text-red-200 text-sm">
Versuche: {authState.attempts}/{MAX_ATTEMPTS}
</p>
<p className="text-red-200 text-sm">
Verbleibende Zeit: {getRemainingTime()} Minuten
</p>
</div>
<p className="text-gray-400 text-sm">
Der Zugang wird automatisch nach {Math.ceil(LOCKOUT_DURATION / 60000)} Minuten freigeschaltet.
</p>
</motion.div>
<div className="min-h-screen">
<div className="fixed inset-0 animated-bg"></div>
<div className="relative z-10 min-h-screen flex items-center justify-center p-4">
<motion.div
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
className="admin-glass-card border-red-500/40 p-8 lg:p-12 rounded-2xl max-w-md w-full text-center shadow-2xl"
>
<div className="mb-8">
<div className="w-16 h-16 bg-gradient-to-r from-red-500 to-orange-500 rounded-2xl flex items-center justify-center mx-auto mb-6 shadow-lg">
<Shield className="w-8 h-8 text-white" />
</div>
<h1 className="text-3xl font-bold text-white mb-3">Access Locked</h1>
<p className="text-white/80 text-lg">
Too many failed authentication attempts
</p>
</div>
<div className="admin-glass-light border border-red-500/40 rounded-xl p-6 mb-8">
<AlertTriangle className="w-8 h-8 text-red-400 mx-auto mb-4" />
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<p className="text-white/60 mb-1">Attempts</p>
<p className="text-red-300 font-bold text-lg">{authState.attempts}/{MAX_ATTEMPTS}</p>
</div>
<div>
<p className="text-white/60 mb-1">Time Left</p>
<p className="text-orange-300 font-bold text-lg">{getRemainingTime()}m</p>
</div>
</div>
</div>
<div className="admin-glass-light border border-blue-500/30 rounded-xl p-4">
<p className="text-white/70 text-sm">
Access will be automatically restored in {Math.ceil(LOCKOUT_DURATION / 60000)} minutes
</p>
</div>
</motion.div>
</div>
</div>
);
}
@@ -330,83 +326,122 @@ const AdminPage = () => {
// Login form
if (authState.showLogin || !authState.isAuthenticated) {
return (
<div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center p-4">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="bg-white/10 backdrop-blur-md rounded-2xl border border-white/20 p-8 max-w-md w-full"
>
<div className="text-center mb-8">
<div className="w-16 h-16 bg-gradient-to-r from-blue-500 to-purple-500 rounded-full flex items-center justify-center mx-auto mb-4">
<Lock className="w-8 h-8 text-white" />
</div>
<h1 className="text-2xl font-bold text-white mb-2">Admin-Zugang</h1>
<p className="text-gray-300">Bitte geben Sie das Admin-Passwort ein</p>
</div>
<div className="min-h-screen">
{/* Animated Background - same as admin dashboard */}
<div className="fixed inset-0 animated-bg"></div>
<form onSubmit={handleLogin} className="space-y-6">
<div>
<label htmlFor="password" className="block text-sm font-medium text-gray-300 mb-2">
Passwort
</label>
<div className="relative">
<input
type={authState.showPassword ? 'text' : 'password'}
id="password"
value={authState.password}
onChange={(e) => setAuthState(prev => ({ ...prev, password: e.target.value }))}
className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all pr-12"
placeholder="Admin-Passwort eingeben"
required
disabled={authState.isLoading}
autoComplete="current-password"
/>
<button
type="button"
onClick={() => setAuthState(prev => ({ ...prev, showPassword: !prev.showPassword }))}
className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-white transition-colors"
disabled={authState.isLoading}
>
{authState.showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
</button>
<div className="relative z-10 min-h-screen flex items-center justify-center p-4">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="admin-glass-card p-8 lg:p-12 rounded-2xl max-w-md w-full shadow-2xl"
>
<div className="text-center mb-8">
<div className="w-16 h-16 bg-gradient-to-r from-blue-500 to-purple-500 rounded-2xl flex items-center justify-center mx-auto mb-6 shadow-lg">
<Shield className="w-8 h-8 text-white" />
</div>
<h1 className="text-3xl font-bold text-white mb-3">Admin Panel</h1>
<p className="text-white/80 text-lg">Secure access to dashboard</p>
<div className="flex items-center justify-center space-x-2 mt-4">
<div className="w-2 h-2 bg-green-400 rounded-full animate-pulse"></div>
<span className="text-white/60 text-sm font-medium">System Online</span>
</div>
</div>
<AnimatePresence>
{authState.error && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
className="bg-red-500/20 border border-red-500/30 rounded-lg p-3"
>
<p className="text-red-200 text-sm">{authState.error}</p>
</motion.div>
)}
</AnimatePresence>
<button
type="submit"
disabled={authState.isLoading || !authState.password}
className="w-full bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600 disabled:from-gray-600 disabled:to-gray-700 text-white font-semibold py-3 px-4 rounded-lg transition-all duration-200 disabled:cursor-not-allowed"
>
{authState.isLoading ? (
<div className="flex items-center justify-center">
<Loader2 className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin mr-2"></Loader2>
Anmeldung...
<form onSubmit={handleLogin} className="space-y-6">
<div>
<label htmlFor="password" className="block text-sm font-medium text-white/80 mb-3">
Admin Password
</label>
<div className="relative">
<input
type={authState.showPassword ? 'text' : 'password'}
id="password"
value={authState.password}
onChange={(e) => setAuthState(prev => ({ ...prev, password: e.target.value }))}
className="w-full px-4 py-4 admin-glass-light border border-white/30 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500/50 transition-all text-lg pr-12"
placeholder="Enter admin password"
required
disabled={authState.isLoading}
autoComplete="current-password"
/>
<button
type="button"
onClick={() => setAuthState(prev => ({ ...prev, showPassword: !prev.showPassword }))}
className="absolute right-4 top-1/2 transform -translate-y-1/2 text-white/60 hover:text-white transition-colors p-1"
disabled={authState.isLoading}
>
{authState.showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
</button>
</div>
) : (
'Anmelden'
)}
</button>
</form>
</div>
<div className="mt-6 text-center">
<p className="text-gray-400 text-xs">
Versuche: {authState.attempts}/{MAX_ATTEMPTS}
</p>
</div>
</motion.div>
<AnimatePresence>
{authState.error && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
className="admin-glass-light border border-red-500/40 rounded-xl p-4 flex items-center space-x-3"
>
<XCircle className="w-5 h-5 text-red-400 flex-shrink-0" />
<p className="text-red-300 text-sm font-medium">{authState.error}</p>
</motion.div>
)}
</AnimatePresence>
{/* Security info */}
<div className="admin-glass-light border border-blue-500/30 rounded-xl p-6">
<div className="flex items-center space-x-3 mb-4">
<Shield className="w-5 h-5 text-blue-400" />
<h3 className="text-blue-300 font-semibold">Security Information</h3>
</div>
<div className="grid grid-cols-2 gap-4 text-xs">
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-white/60">Max Attempts:</span>
<span className="text-white font-medium">{MAX_ATTEMPTS}</span>
</div>
<div className="flex justify-between">
<span className="text-white/60">Lockout:</span>
<span className="text-white font-medium">{Math.ceil(LOCKOUT_DURATION / 60000)}m</span>
</div>
</div>
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-white/60">Session:</span>
<span className="text-white font-medium">2h</span>
</div>
<div className="flex justify-between">
<span className="text-white/60">Attempts:</span>
<span className={`font-medium ${authState.attempts > 0 ? 'text-orange-400' : 'text-green-400'}`}>
{authState.attempts}/{MAX_ATTEMPTS}
</span>
</div>
</div>
</div>
</div>
<button
type="submit"
disabled={authState.isLoading || !authState.password}
className="w-full bg-gradient-to-r from-blue-500 to-purple-500 text-white py-4 px-6 rounded-xl font-semibold text-lg hover:from-blue-600 hover:to-purple-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-transparent disabled:opacity-50 disabled:cursor-not-allowed transition-all transform hover:scale-[1.02] active:scale-[0.98] shadow-lg"
>
{authState.isLoading ? (
<div className="flex items-center justify-center space-x-3">
<Loader2 className="w-5 h-5 animate-spin" />
<span>Authenticating...</span>
</div>
) : (
<div className="flex items-center justify-center space-x-2">
<Lock size={18} />
<span>Secure Login</span>
</div>
)}
</button>
</form>
</motion.div>
</div>
</div>
);
}
@@ -414,17 +449,6 @@ const AdminPage = () => {
// Authenticated state - show admin dashboard
return (
<div className="relative">
{/* Logout button */}
<div className="fixed top-4 right-4 z-50">
<button
onClick={handleLogout}
className="bg-red-500/20 hover:bg-red-500/30 border border-red-500/30 text-red-200 px-4 py-2 rounded-lg transition-all duration-200 flex items-center space-x-2"
>
<XCircle className="w-4 h-4" />
<span>Logout</span>
</button>
</div>
<ModernAdminDashboard isAuthenticated={authState.isAuthenticated} />
</div>
);