/** * Authentication Manager Module * Handles user authentication, session management, and permissions */ export class AuthManager { constructor() { this.currentUser = null; this.authToken = null; } async checkAuthentication() { const token = localStorage.getItem('auth_token'); if (!token) { return false; } try { const response = await fetch('/api/auth/validate', { headers: { 'Authorization': `Bearer ${token}` } }); if (response.ok) { const data = await response.json(); this.currentUser = data.user; this.authToken = token; return true; } else { this.clearAuthData(); return false; } } catch (error) { console.error('Auth validation error:', error); return false; } } async logout() { try { await fetch('/api/auth/logout', { method: 'POST', headers: { 'Authorization': `Bearer ${this.authToken}` } }); } catch (error) { console.error('Logout error:', error); } finally { this.clearAuthData(); window.location.href = '/login'; } } clearAuthData() { localStorage.removeItem('auth_token'); localStorage.removeItem('user_info'); this.currentUser = null; this.authToken = null; } canEditTree(createdBy) { if (!this.currentUser) return false; const permissions = this.currentUser.permissions || []; // Admin and system can edit any tree if (permissions.includes('admin') || permissions.includes('system')) { return true; } // Users can edit trees they created if (permissions.includes('edit_own') && createdBy === this.currentUser.username) { return true; } // Users with delete permission can edit any tree if (permissions.includes('delete')) { return true; } return false; } canDeleteTree(createdBy) { if (!this.currentUser) return false; const permissions = this.currentUser.permissions || []; // Only admin and system can delete trees if (permissions.includes('admin') || permissions.includes('system')) { return true; } // Users with explicit delete permission if (permissions.includes('delete')) { return true; } return false; } getAuthHeaders() { return { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.authToken}` }; } }