2025-07-06 21:01:27 -06:00

82 lines
2.7 KiB
JavaScript

// Authentication related functions
import { showStatus } from './utils.js';
export let currentUser = null;
export async function checkAuth() {
try {
const response = await fetch('/api/auth/check');
const data = await response.json();
if (!data.authenticated) {
window.location.href = '/login.html';
throw new Error('Not authenticated');
}
currentUser = data.user;
updateUserInterface();
} catch (error) {
console.error('Auth check failed:', error);
window.location.href = '/login.html';
throw error;
}
}
export function updateUserInterface() {
if (!currentUser) return;
// Update user email in both desktop and mobile
const userEmailElement = document.getElementById('user-email');
const mobileUserEmailElement = document.getElementById('mobile-user-email');
if (userEmailElement) {
userEmailElement.textContent = currentUser.email;
}
if (mobileUserEmailElement) {
mobileUserEmailElement.textContent = currentUser.email;
}
// Add admin link if user is admin
if (currentUser.isAdmin) {
addAdminLinks();
}
}
function addAdminLinks() {
// Add admin link to desktop header
const headerActions = document.querySelector('.header-actions');
if (headerActions) {
const adminLink = document.createElement('a');
adminLink.href = '/admin.html';
adminLink.className = 'btn btn-secondary';
adminLink.textContent = '⚙️ Admin';
headerActions.insertBefore(adminLink, headerActions.firstChild);
}
// Add admin link to mobile dropdown
const mobileDropdownContent = document.getElementById('mobile-dropdown-content');
if (mobileDropdownContent) {
// Check if admin link already exists
if (!mobileDropdownContent.querySelector('.admin-link-mobile')) {
const adminItem = document.createElement('div');
adminItem.className = 'mobile-dropdown-item admin-link-mobile';
const adminLink = document.createElement('a');
adminLink.href = '/admin.html';
adminLink.style.color = 'inherit';
adminLink.style.textDecoration = 'none';
adminLink.textContent = '⚙️ Admin Panel';
adminItem.appendChild(adminLink);
// Insert admin link at the top of the dropdown
if (mobileDropdownContent.firstChild) {
mobileDropdownContent.insertBefore(adminItem, mobileDropdownContent.firstChild);
} else {
mobileDropdownContent.appendChild(adminItem);
}
}
}
}