209 lines
6.5 KiB
JavaScript

// Authentication module for handling login/logout and session management
class AuthManager {
constructor() {
this.user = null;
this.isAuthenticated = false;
}
// Initialize authentication state
async init() {
await this.checkSession();
this.setupAuthListeners();
}
// Check current session status
async checkSession() {
try {
const response = await apiClient.get('/auth/session');
if (response.authenticated) {
this.isAuthenticated = true;
this.user = response.user;
this.updateUI();
return true;
} else {
this.isAuthenticated = false;
this.user = null;
this.updateUI();
return false;
}
} catch (error) {
console.error('Session check failed:', error);
this.isAuthenticated = false;
this.user = null;
this.updateUI();
return false;
}
}
// Login with email and password
async login(email, password) {
try {
const response = await apiClient.post('/auth/login', {
email,
password
});
if (response.success) {
this.isAuthenticated = true;
this.user = response.user;
this.updateUI();
return { success: true };
} else {
return { success: false, error: response.error };
}
} catch (error) {
console.error('Login error:', error);
return { success: false, error: error.message || 'Login failed' };
}
}
// Logout current user
async logout() {
try {
await apiClient.post('/auth/logout');
this.isAuthenticated = false;
this.user = null;
this.updateUI();
// Redirect to login page
window.location.href = '/login.html';
} catch (error) {
console.error('Logout error:', error);
// Force logout on client side even if server request fails
this.isAuthenticated = false;
this.user = null;
this.updateUI();
window.location.href = '/login.html';
}
}
// Update UI based on authentication state
updateUI() {
// Update user info display
const userInfo = document.getElementById('user-info');
if (userInfo) {
if (this.isAuthenticated && this.user) {
userInfo.innerHTML = `
<span>Welcome, ${this.user.name || this.user.email}</span>
<button id="logout-btn" class="btn btn-secondary">Logout</button>
`;
// Add logout button listener
const logoutBtn = document.getElementById('logout-btn');
if (logoutBtn) {
logoutBtn.addEventListener('click', () => this.logout());
}
} else {
userInfo.innerHTML = '';
}
}
// Show/hide admin elements
const adminElements = document.querySelectorAll('.admin-only');
adminElements.forEach(element => {
if (this.isAuthenticated && this.user?.isAdmin) {
element.style.display = 'block';
} else {
element.style.display = 'none';
}
});
// Show/hide authenticated elements
const authElements = document.querySelectorAll('.auth-only');
authElements.forEach(element => {
if (this.isAuthenticated) {
element.style.display = 'block';
} else {
element.style.display = 'none';
}
});
}
// Redirect to appropriate dashboard
redirectToDashboard() {
if (this.isAuthenticated && this.user) {
if (this.user.isAdmin) {
window.location.href = '/admin.html';
} else {
window.location.href = '/dashboard.html';
}
} else {
window.location.href = '/login.html';
}
}
// Set up event listeners for auth-related actions
setupAuthListeners() {
// Global logout button
document.addEventListener('click', (e) => {
if (e.target.matches('[data-action="logout"]')) {
e.preventDefault();
this.logout();
}
});
// Login form submission
const loginForm = document.getElementById('login-form');
if (loginForm) {
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
const email = document.getElementById('email').value.trim();
const password = document.getElementById('password').value;
const result = await this.login(email, password);
if (result.success) {
// Redirect to admin panel
window.location.href = '/admin.html';
} else {
// Show error message
const errorElement = document.getElementById('error-message');
if (errorElement) {
errorElement.textContent = result.error;
errorElement.style.display = 'block';
}
}
});
}
}
// Require authentication for current page
requireAuth() {
if (!this.isAuthenticated) {
window.location.href = '/login.html';
return false;
}
return true;
}
// Require admin access for current page
requireAdmin() {
if (!this.isAuthenticated) {
window.location.href = '/login.html';
return false;
}
if (!this.user?.isAdmin) {
alert('Admin access required');
window.location.href = '/';
return false;
}
return true;
}
}
// Create global auth manager instance
const authManager = new AuthManager();
// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
authManager.init();
});
// Export for use in other modules
if (typeof module !== 'undefined' && module.exports) {
module.exports = AuthManager;
}