document.addEventListener('DOMContentLoaded', function() {
const loginForm = document.getElementById('login-form');
// We're on the login page, so we don't need to check if already logged in
// This prevents redirect loops
if (loginForm) {
// Clear any existing error messages
const existingErrors = document.querySelectorAll('.alert.alert-danger');
existingErrors.forEach(el => el.remove());
loginForm.addEventListener('submit', async function(e) {
e.preventDefault();
// Show loading indicator
const submitBtn = loginForm.querySelector('button[type="submit"]');
const originalBtnText = submitBtn.innerHTML;
submitBtn.disabled = true;
submitBtn.innerHTML = ' Logging in...';
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
// Clear any existing error messages
const existingErrors = document.querySelectorAll('.alert.alert-danger');
existingErrors.forEach(el => el.remove());
try {
console.log('Attempting login for user:', username);
const response = await fetch('/auth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
credentials: 'include', // Important: include cookies
body: new URLSearchParams({
'username': username,
'password': password
})
});
console.log('Login response status:', response.status);
if (!response.ok) {
const errorText = await response.text();
console.error('Login failed:', response.status, errorText);
throw new Error(`Login failed: ${response.status} ${errorText}`);
}
const result = await response.json();
console.log('Login successful, result:', result);
// Verify the token was set in cookies
const cookies = document.cookie;
console.log('Cookies after login:', cookies);
// Check if password change is required
if (result.password_change_required) {
console.log('Password change required, redirecting');
// Redirect to password change page
window.location.href = '/change-password';
} else {
console.log('Login successful, redirecting to dashboard');
// Normal login flow - redirect to dashboard
window.location.href = '/';
}
} catch (error) {
console.error('Login error:', error);
// Reset button
submitBtn.disabled = false;
submitBtn.innerHTML = originalBtnText;
// Show error message
const errorDiv = document.createElement('div');
errorDiv.className = 'alert alert-danger';
errorDiv.innerHTML = ` Login failed. Please check your username and password.`;
// Insert after the form
loginForm.parentNode.insertBefore(errorDiv, loginForm.nextSibling);
// Remove after 5 seconds
setTimeout(() => {
errorDiv.remove();
}, 5000);
}
});
}
});