auth frontend

This commit is contained in:
AleksDw
2025-05-31 13:34:18 +02:00
parent 740f8a955d
commit 42e468f28f
8 changed files with 213 additions and 11 deletions

58
WebApp/ts/auth.ts Normal file
View File

@@ -0,0 +1,58 @@
// /js/auth.ts
function deleteCookie(name: string): void {
document.cookie = `${name}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
}
function logoutUser(): void {
// 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(): void {
window.location.href = 'login.html';
}
function checkAuth(): boolean {
// Basic auth check via presence of token cookie
return document.cookie.includes('token=');
}
function setupAuthUI(): void {
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);