112 lines
3.3 KiB
JavaScript

// User profile JavaScript
// Function to set viewport dimensions for user page
function setUserViewportDimensions() {
const doc = document.documentElement;
doc.style.setProperty('--app-height', `${window.innerHeight}px`);
doc.style.setProperty('--app-width', `${window.innerWidth}px`);
}
// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
// Set initial viewport dimensions and listen for resize events
setUserViewportDimensions();
window.addEventListener('resize', setUserViewportDimensions);
window.addEventListener('orientationchange', () => {
setTimeout(setUserViewportDimensions, 100);
});
checkUserAuth();
loadUserProfile();
setupEventListeners();
});
// Check if user is authenticated
async function checkUserAuth() {
try {
const response = await fetch('/api/auth/check');
const data = await response.json();
if (!data.authenticated) {
window.location.href = '/login.html';
return;
}
// Update user info in header
const userInfo = document.getElementById('user-info');
if (userInfo && data.user) {
userInfo.textContent = `${data.user.name || data.user.email}`;
}
} catch (error) {
console.error('Auth check failed:', error);
window.location.href = '/login.html';
}
}
// Load user profile information
async function loadUserProfile() {
try {
const response = await fetch('/api/auth/check');
const data = await response.json();
if (data.authenticated && data.user) {
document.getElementById('profile-email').textContent = data.user.email || 'N/A';
document.getElementById('profile-name').textContent = data.user.name || 'N/A';
document.getElementById('profile-role').textContent = data.user.isAdmin ? 'Administrator' : 'User';
}
} catch (error) {
console.error('Failed to load profile:', error);
showStatus('Failed to load profile information', 'error');
}
}
// Setup event listeners
function setupEventListeners() {
// Logout button
const logoutBtn = document.getElementById('logout-btn');
if (logoutBtn) {
logoutBtn.addEventListener('click', handleLogout);
}
}
// Handle logout
async function handleLogout() {
try {
const response = await fetch('/api/auth/logout', {
method: 'POST',
credentials: 'include'
});
if (response.ok) {
window.location.href = '/login.html';
} else {
throw new Error('Logout failed');
}
} catch (error) {
console.error('Logout error:', error);
showStatus('Logout failed', 'error');
}
}
// Show status message
function showStatus(message, type = 'info') {
const container = document.getElementById('status-container');
if (!container) return;
const statusDiv = document.createElement('div');
statusDiv.className = `status-message status-${type}`;
statusDiv.textContent = message;
container.appendChild(statusDiv);
// Auto remove after 5 seconds
setTimeout(() => {
if (statusDiv.parentNode) {
statusDiv.parentNode.removeChild(statusDiv);
}
}, 5000);
}