Files
hermes/WebApp/wwwroot/js/auth.js
2025-05-31 13:34:18 +02:00

47 lines
1.7 KiB
JavaScript

"use strict";
// /js/auth.ts
function deleteCookie(name) {
document.cookie = `${name}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
}
function logoutUser() {
// Inform backend to remove cookie if necessary
fetch('/api/logout', {
method: 'POST',
credentials: 'include',
}).catch((err) => console.warn('Logout request failed:', err));
// Clear the auth cookie
deleteCookie('token');
// Redirect to login page
window.location.href = 'index.html';
}
function redirectToLogin() {
window.location.href = 'login.html';
}
function checkAuth() {
// Basic auth check via presence of token cookie
return document.cookie.includes('token=');
}
function setupAuthUI() {
const joinNowBtn = document.getElementById('joinnow-btn');
const signInBtn = document.getElementById('signin-btn');
const logoutBtn = document.getElementById('logout-btn');
const isAuthenticated = checkAuth();
if (joinNowBtn) {
joinNowBtn.classList.toggle('d-none', isAuthenticated);
joinNowBtn.addEventListener('click', redirectToLogin);
}
if (signInBtn) {
signInBtn.classList.toggle('d-none', isAuthenticated);
signInBtn.addEventListener('click', redirectToLogin);
}
if (logoutBtn) {
logoutBtn.classList.toggle('d-none', !isAuthenticated);
logoutBtn.addEventListener('click', logoutUser);
}
// Hide all auth buttons initially until DOM loads
const hiddenBeforeLoad = document.querySelectorAll('.hidden-before-load');
hiddenBeforeLoad.forEach(el => el.classList.remove('hidden-before-load'));
}
// Initialize on load
document.addEventListener('DOMContentLoaded', setupAuthUI);