4e313392d0
- Removed restrictive x-show/x-cloak that blocked UI visibility - Forced tab container display and visibility in header - Improved auth state synchronization with synchronous Alpine loading - Fixed home section initialization and tab switching logic
120 lines
3.3 KiB
JavaScript
120 lines
3.3 KiB
JavaScript
/**
|
|
* Authentication management for web interface
|
|
*/
|
|
|
|
// Use relative path for API
|
|
const AUTH_API_BASE = '/api';
|
|
|
|
const COOKIE_NAME = 'auth_token';
|
|
const COOKIE_MAX_AGE = 60 * 60 * 24 * 7; // 7 days
|
|
|
|
function setToken(token) {
|
|
localStorage.setItem('auth_token', token);
|
|
const expires = new Date();
|
|
expires.setTime(expires.getTime() + COOKIE_MAX_AGE * 1000);
|
|
document.cookie = `${COOKIE_NAME}=${token};expires=${expires.toUTCString()};path=/;SameSite=Strict`;
|
|
}
|
|
|
|
function getToken() {
|
|
const cookieToken = getTokenFromCookie();
|
|
if (cookieToken) return cookieToken;
|
|
return localStorage.getItem('auth_token');
|
|
}
|
|
|
|
function getTokenFromCookie() {
|
|
const name = COOKIE_NAME + '=';
|
|
const decodedCookie = decodeURIComponent(document.cookie);
|
|
const cookieArray = decodedCookie.split(';');
|
|
for (let i = 0; i < cookieArray.length; i++) {
|
|
let cookie = cookieArray[i];
|
|
while (cookie.charAt(0) === ' ') cookie = cookie.substring(1);
|
|
if (cookie.indexOf(name) === 0) return cookie.substring(name.length, cookie.length);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function removeToken() {
|
|
localStorage.removeItem('auth_token');
|
|
localStorage.removeItem('user');
|
|
document.cookie = `${COOKIE_NAME}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;`;
|
|
}
|
|
|
|
// Check if user is authenticated
|
|
async function checkAuth() {
|
|
console.log('Checking authentication...');
|
|
const token = getToken();
|
|
|
|
if (!token) {
|
|
console.log('No token found');
|
|
return false;
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(`${AUTH_API_BASE}/auth/me`, {
|
|
headers: { 'Authorization': `Bearer ${token}` }
|
|
});
|
|
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
console.log('Auth success:', data.user.username);
|
|
|
|
// Dispatch for Alpine
|
|
window.dispatchEvent(new CustomEvent('auth-success', {
|
|
detail: { username: data.user.full_name || data.user.username }
|
|
}));
|
|
|
|
return true;
|
|
} else {
|
|
console.log('Token invalid');
|
|
return false;
|
|
}
|
|
} catch (error) {
|
|
console.error('Auth check error:', error);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function redirectToLogin() {
|
|
if (!window.location.pathname.includes('/login')) {
|
|
window.location.href = '/login';
|
|
}
|
|
}
|
|
|
|
async function handleLogout() {
|
|
if (!confirm('Êtes-vous sûr de vouloir vous déconnecter?')) return;
|
|
removeToken();
|
|
try {
|
|
await fetch(`${AUTH_API_BASE}/auth/logout`, { method: 'POST' });
|
|
} catch (error) {
|
|
console.error('Logout error:', error);
|
|
}
|
|
window.location.href = '/login';
|
|
}
|
|
|
|
function addAuthHeader(options = {}) {
|
|
const token = getToken();
|
|
if (token) {
|
|
options.headers = options.headers || {};
|
|
options.headers['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
return options;
|
|
}
|
|
|
|
async function authFetch(url, options = {}) {
|
|
options = addAuthHeader(options);
|
|
return fetch(url, options);
|
|
}
|
|
|
|
// Global exposure
|
|
window.checkAuth = checkAuth;
|
|
window.handleLogout = handleLogout;
|
|
window.authFetch = authFetch;
|
|
window.addAuthHeader = addAuthHeader;
|
|
window.getToken = getToken;
|
|
window.setToken = setToken;
|
|
window.removeToken = removeToken;
|
|
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
checkAuth();
|
|
});
|