"Refactor template files for better consistency (feat)"

This commit is contained in:
2025-05-29 16:40:46 +02:00
parent 6d3ccb5e26
commit e88a5b2780
2 changed files with 940 additions and 0 deletions

View File

@@ -440,4 +440,583 @@
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
let loginAttempts = parseInt(localStorage.getItem('loginAttempts') || '0');
let lastAttemptTime = parseInt(localStorage.getItem('lastAttemptTime') || '0');
let isFormLocked = false;
const MAX_ATTEMPTS = 5;
const LOCKOUT_DURATION = 15 * 60 * 1000; // 15 minutes
document.addEventListener('DOMContentLoaded', function() {
initializeLoginForm();
checkRateLimit();
setupFormValidation();
setupPasswordFeatures();
setupKeyboardShortcuts();
setupAccessibility();
});
function initializeLoginForm() {
const form = document.getElementById('loginForm');
const submitBtn = document.getElementById('submitBtn');
const submitText = document.getElementById('submitText');
const loadingSpinner = document.getElementById('loadingSpinner');
const emailInput = document.getElementById('email');
const passwordInput = document.getElementById('password');
// Enhanced form submission handling
if (form) {
form.addEventListener('submit', async function(e) {
e.preventDefault();
if (isFormLocked) {
showAdvancedMessage('Zu viele Anmeldeversuche. Bitte warten Sie.', 'error');
return;
}
// Validate form before submission
if (!validateLoginForm()) {
return;
}
await handleLoginSubmission();
});
}
// Auto-focus first empty field
if (emailInput && !emailInput.value) {
emailInput.focus();
} else if (passwordInput && !passwordInput.value) {
passwordInput.focus();
}
// Enhanced tab navigation
setupTabNavigation();
}
function checkRateLimit() {
const now = Date.now();
const timeSinceLastAttempt = now - lastAttemptTime;
if (loginAttempts >= MAX_ATTEMPTS && timeSinceLastAttempt < LOCKOUT_DURATION) {
const remainingTime = LOCKOUT_DURATION - timeSinceLastAttempt;
showRateLimitWarning(remainingTime);
lockForm(remainingTime);
} else if (timeSinceLastAttempt >= LOCKOUT_DURATION) {
// Reset attempts after lockout period
loginAttempts = 0;
localStorage.setItem('loginAttempts', '0');
}
// Show warning at 3 attempts
if (loginAttempts >= 3 && loginAttempts < MAX_ATTEMPTS) {
document.getElementById('rate-limit-warning').classList.remove('hidden');
}
}
function setupFormValidation() {
const emailInput = document.getElementById('email');
const passwordInput = document.getElementById('password');
if (emailInput) {
emailInput.addEventListener('blur', function() {
validateEmail();
});
emailInput.addEventListener('input', function() {
clearError(emailInput);
if (this.value.trim()) {
const isValid = isValidEmail(this.value.trim());
if (isValid) {
this.classList.add('input-success');
this.classList.remove('input-error');
} else {
this.classList.add('input-error');
this.classList.remove('input-success');
}
} else {
this.classList.remove('input-error', 'input-success');
}
});
}
if (passwordInput) {
passwordInput.addEventListener('input', function() {
clearError(passwordInput);
updatePasswordStrength(this.value);
});
passwordInput.addEventListener('focus', function() {
document.getElementById('password-strength').classList.remove('hidden');
});
}
}
function setupPasswordFeatures() {
const togglePassword = document.getElementById('togglePassword');
const passwordInput = document.getElementById('password');
const eyeOpen = document.getElementById('eyeOpen');
const eyeClosed = document.getElementById('eyeClosed');
if (togglePassword && passwordInput) {
togglePassword.addEventListener('click', function() {
const isPassword = passwordInput.type === 'password';
passwordInput.type = isPassword ? 'text' : 'password';
eyeOpen.classList.toggle('hidden', isPassword);
eyeClosed.classList.toggle('hidden', !isPassword);
// Accessibility
this.setAttribute('aria-label', isPassword ? 'Passwort verbergen' : 'Passwort anzeigen');
// Keep focus on password input
passwordInput.focus();
// Move cursor to end
setTimeout(() => {
const len = passwordInput.value.length;
passwordInput.setSelectionRange(len, len);
}, 10);
});
}
}
function setupKeyboardShortcuts() {
document.addEventListener('keypress', function(e) {
// Enter key submits form
if (e.key === 'Enter' && e.target.form === document.getElementById('loginForm')) {
e.preventDefault();
document.getElementById('loginForm').dispatchEvent(new Event('submit'));
}
});
// Escape key clears form
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
clearForm();
}
});
}
function setupAccessibility() {
// ARIA labels and descriptions
const form = document.getElementById('loginForm');
if (form) {
form.setAttribute('aria-describedby', 'login-description');
}
// Screen reader announcements
const srContainer = document.createElement('div');
srContainer.setAttribute('aria-live', 'polite');
srContainer.setAttribute('aria-atomic', 'true');
srContainer.className = 'sr-only';
srContainer.id = 'sr-announcements';
document.body.appendChild(srContainer);
}
function validateLoginForm() {
const emailValid = validateEmail();
const passwordValid = validatePassword();
return emailValid && passwordValid;
}
function validateEmail() {
const emailInput = document.getElementById('email');
const email = emailInput.value.trim();
if (!email) {
showError(emailInput, 'E-Mail-Adresse ist erforderlich');
return false;
}
if (!isValidEmail(email)) {
showError(emailInput, 'Bitte geben Sie eine gültige E-Mail-Adresse ein');
return false;
}
// Check for corporate domain (optional)
if (email && !email.includes('@mercedes-benz.com') && !email.includes('@daimler.com')) {
showWarning(emailInput, 'Hinweis: Externe E-Mail-Adresse erkannt');
}
clearError(emailInput);
emailInput.classList.add('input-success');
return true;
}
function validatePassword() {
const passwordInput = document.getElementById('password');
const password = passwordInput.value;
if (!password) {
showError(passwordInput, 'Passwort ist erforderlich');
return false;
}
if (password.length < 6) {
showError(passwordInput, 'Passwort muss mindestens 6 Zeichen lang sein');
return false;
}
clearError(passwordInput);
passwordInput.classList.add('input-success');
return true;
}
function updatePasswordStrength(password) {
const strengthBar = document.getElementById('strength-bar');
const strengthText = document.getElementById('strength-text');
if (!password) {
strengthBar.style.width = '0%';
strengthText.textContent = '';
return;
}
let score = 0;
let feedback = '';
// Length check
if (password.length >= 8) score += 20;
if (password.length >= 12) score += 10;
// Character variety
if (/[a-z]/.test(password)) score += 20;
if (/[A-Z]/.test(password)) score += 20;
if (/\d/.test(password)) score += 20;
if (/[^A-Za-z0-9]/.test(password)) score += 20;
// Determine strength level
if (score < 40) {
strengthBar.className = 'h-1 rounded-full transition-all duration-300 bg-red-500';
feedback = 'Schwach';
} else if (score < 70) {
strengthBar.className = 'h-1 rounded-full transition-all duration-300 bg-yellow-500';
feedback = 'Mittel';
} else if (score < 90) {
strengthBar.className = 'h-1 rounded-full transition-all duration-300 bg-blue-500';
feedback = 'Gut';
} else {
strengthBar.className = 'h-1 rounded-full transition-all duration-300 bg-green-500';
feedback = 'Sehr stark';
}
strengthBar.style.width = `${Math.min(score, 100)}%`;
strengthText.textContent = feedback;
}
async function handleLoginSubmission() {
const form = document.getElementById('loginForm');
const submitBtn = document.getElementById('submitBtn');
const submitText = document.getElementById('submitText');
const loadingSpinner = document.getElementById('loadingSpinner');
// Show loading state
submitBtn.disabled = true;
loadingSpinner.classList.remove('hidden');
submitText.textContent = 'Wird angemeldet...';
try {
// Add CSRF token if available
const formData = new FormData(form);
// Enhanced submission with proper headers
const response = await fetch(form.action, {
method: 'POST',
body: formData,
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
});
if (response.ok) {
const result = await response.json().catch(() => null);
if (result && result.success) {
// Clear login attempts on success
localStorage.setItem('loginAttempts', '0');
// Show success message
showSuccessMessage();
// Redirect after short delay
setTimeout(() => {
window.location.href = result.redirect_url || '/dashboard';
}, 1500);
} else {
throw new Error(result?.message || 'Anmeldung fehlgeschlagen');
}
} else {
// Handle HTTP errors
if (response.status === 401) {
handleFailedLogin('Ungültige E-Mail-Adresse oder Passwort');
} else if (response.status === 429) {
handleRateLimit();
} else {
throw new Error(`Server-Fehler: ${response.status}`);
}
}
} catch (error) {
console.error('Login error:', error);
handleFailedLogin(error.message || 'Ein unerwarteter Fehler ist aufgetreten');
} finally {
// Reset button state
submitBtn.disabled = false;
loadingSpinner.classList.add('hidden');
submitText.textContent = 'Anmelden';
}
}
function handleFailedLogin(message) {
loginAttempts++;
lastAttemptTime = Date.now();
localStorage.setItem('loginAttempts', loginAttempts.toString());
localStorage.setItem('lastAttemptTime', lastAttemptTime.toString());
showAdvancedMessage(message, 'error');
// Show warning after 3 attempts
if (loginAttempts >= 3 && loginAttempts < MAX_ATTEMPTS) {
document.getElementById('rate-limit-warning').classList.remove('hidden');
const remaining = MAX_ATTEMPTS - loginAttempts;
showAdvancedMessage(`Achtung: Noch ${remaining} Versuche übrig`, 'warning');
}
// Lock form after max attempts
if (loginAttempts >= MAX_ATTEMPTS) {
lockForm(LOCKOUT_DURATION);
showAdvancedMessage(`Konto gesperrt. Bitte warten Sie ${LOCKOUT_DURATION / 60000} Minuten.`, 'error');
}
// Shake form animation
const form = document.getElementById('loginForm');
form.style.animation = 'shake 0.5s ease-in-out';
setTimeout(() => {
form.style.animation = '';
}, 500);
}
function handleRateLimit() {
showRateLimitWarning(LOCKOUT_DURATION);
lockForm(LOCKOUT_DURATION);
}
function lockForm(duration) {
isFormLocked = true;
const form = document.getElementById('loginForm');
const inputs = form.querySelectorAll('input, button');
inputs.forEach(input => {
input.disabled = true;
});
// Start countdown
startLockoutCountdown(duration);
setTimeout(() => {
isFormLocked = false;
inputs.forEach(input => {
input.disabled = false;
});
document.getElementById('rate-limit-warning').classList.add('hidden');
}, duration);
}
function startLockoutCountdown(duration) {
const warningElement = document.getElementById('rate-limit-warning');
const startTime = Date.now();
const updateCountdown = () => {
const elapsed = Date.now() - startTime;
const remaining = Math.max(0, duration - elapsed);
if (remaining > 0) {
const minutes = Math.floor(remaining / 60000);
const seconds = Math.floor((remaining % 60000) / 1000);
warningElement.querySelector('p').innerHTML =
`<strong>Sicherheitssperre aktiv:</strong> Versuchen Sie es in ${minutes}:${seconds.toString().padStart(2, '0')} erneut.`;
setTimeout(updateCountdown, 1000);
}
};
updateCountdown();
}
function showRateLimitWarning(remainingTime) {
const warningElement = document.getElementById('rate-limit-warning');
warningElement.classList.remove('hidden');
const minutes = Math.floor(remainingTime / 60000);
const seconds = Math.floor((remainingTime % 60000) / 1000);
warningElement.querySelector('p').innerHTML =
`<strong>Sicherheitssperre:</strong> Zu viele fehlgeschlagene Anmeldeversuche. Warten Sie ${minutes}:${seconds.toString().padStart(2, '0')}.`;
}
function showSuccessMessage() {
const overlay = document.createElement('div');
overlay.className = 'loading-overlay active';
overlay.innerHTML = `
<div class="loading-content">
<div class="w-16 h-16 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center mx-auto mb-4">
<svg class="w-8 h-8 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
</svg>
</div>
<h3 class="text-lg font-semibold text-green-600 dark:text-green-400 mb-2">Anmeldung erfolgreich!</h3>
<p class="text-sm text-gray-600 dark:text-gray-400">Sie werden weitergeleitet...</p>
</div>
`;
document.body.appendChild(overlay);
}
// Utility functions
function isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
function showError(input, message) {
clearError(input);
input.classList.add('input-error');
input.classList.remove('input-success');
const errorDiv = document.createElement('div');
errorDiv.className = 'mt-1 text-sm text-mercedes-red error-message';
errorDiv.innerHTML = `
<div class="flex items-center">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
${message}
</div>
`;
input.parentNode.appendChild(errorDiv);
// Screen reader announcement
announceToScreenReader(`Fehler: ${message}`);
}
function showWarning(input, message) {
const warningDiv = document.createElement('div');
warningDiv.className = 'mt-1 text-sm text-yellow-600 dark:text-yellow-400 warning-message';
warningDiv.innerHTML = `
<div class="flex items-center">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"/>
</svg>
${message}
</div>
`;
input.parentNode.appendChild(warningDiv);
}
function clearError(input) {
input.classList.remove('input-error', 'input-success');
const errorMessage = input.parentNode.querySelector('.error-message');
if (errorMessage) {
errorMessage.remove();
}
const warningMessage = input.parentNode.querySelector('.warning-message');
if (warningMessage) {
warningMessage.remove();
}
}
function clearForm() {
const form = document.getElementById('loginForm');
form.reset();
const inputs = form.querySelectorAll('input');
inputs.forEach(input => {
clearError(input);
});
document.getElementById('password-strength').classList.add('hidden');
}
function showAdvancedMessage(message, type) {
// Create toast notification
const toast = document.createElement('div');
toast.className = `fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg transform transition-all duration-300 translate-x-full opacity-0`;
if (type === 'error') {
toast.className += ' bg-red-50 border border-red-200 text-red-800 dark:bg-red-900 dark:border-red-700 dark:text-red-200';
} else if (type === 'warning') {
toast.className += ' bg-yellow-50 border border-yellow-200 text-yellow-800 dark:bg-yellow-900 dark:border-yellow-700 dark:text-yellow-200';
} else {
toast.className += ' bg-blue-50 border border-blue-200 text-blue-800 dark:bg-blue-900 dark:border-blue-700 dark:text-blue-200';
}
toast.innerHTML = `
<div class="flex items-center">
<svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
${type === 'error' ?
'<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>' :
'<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>'
}
</svg>
<span>${message}</span>
<button onclick="this.parentElement.parentElement.remove()" class="ml-4 text-gray-400 hover:text-gray-600">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
</svg>
</button>
</div>
`;
document.body.appendChild(toast);
// Animate in
setTimeout(() => {
toast.classList.remove('translate-x-full', 'opacity-0');
}, 100);
// Auto-remove after 5 seconds
setTimeout(() => {
toast.classList.add('translate-x-full', 'opacity-0');
setTimeout(() => toast.remove(), 300);
}, 5000);
// Screen reader announcement
announceToScreenReader(message);
}
function announceToScreenReader(message) {
const srContainer = document.getElementById('sr-announcements');
if (srContainer) {
srContainer.textContent = message;
setTimeout(() => {
srContainer.textContent = '';
}, 1000);
}
}
function setupTabNavigation() {
const focusableElements = document.querySelectorAll(
'input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])'
);
focusableElements.forEach((element, index) => {
element.addEventListener('keydown', function(e) {
if (e.key === 'Tab') {
// Enhanced tab navigation logic can be added here
}
});
});
}
</script>
{% endblock %}