OFTQUEST / static /js /auth.js
Nicolasmed26's picture
Deploy MedMembers OFT 2026
8d5289f verified
Raw History Blame Contribute Delete
4.75 kB
// ===== Authentication Module (v3 - cookie + storage fallback) =====
// Uses cookies as primary storage (works in HF Spaces iframe)
// Falls back to sessionStorage if available
const Auth = {
_memoryToken: null,
_memoryUser: null,
_sessionLockedUntil: 0,
_setCookie(name, value, days) {
let expires = '';
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toUTCString();
}
// SameSite=None + Secure required for iframe embedding (HF Spaces)
const isHttps = window.location.protocol === 'https:';
const sameSite = isHttps ? '; SameSite=None; Secure' : '; SameSite=Lax';
document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/' + sameSite;
},
_getCookie(name) {
const nameEQ = name + '=';
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i].trim();
if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length));
}
return null;
},
_deleteCookie(name) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
},
getToken() {
// Try memory first (fastest)
if (this._memoryToken) return this._memoryToken;
// Try cookie
const cookieToken = this._getCookie('mm_token');
if (cookieToken) {
this._memoryToken = cookieToken;
return cookieToken;
}
// Try sessionStorage as fallback
try {
const ssToken = sessionStorage.getItem('mm_token');
if (ssToken) {
this._memoryToken = ssToken;
return ssToken;
}
} catch(e) {}
return null;
},
getUser() {
// Try memory first
if (this._memoryUser) return this._memoryUser;
// Try cookie
const cookieUser = this._getCookie('mm_user');
if (cookieUser) {
try {
this._memoryUser = JSON.parse(cookieUser);
return this._memoryUser;
} catch(e) {}
}
// Try sessionStorage as fallback
try {
const data = sessionStorage.getItem('mm_user');
if (data) {
this._memoryUser = JSON.parse(data);
return this._memoryUser;
}
} catch(e) {}
return null;
},
isAdmin() {
const user = this.getUser();
return user && user.role === 'admin';
},
setSession(token, user) {
this._memoryToken = token;
this._memoryUser = user;
// Lock session for 15s to prevent any race-condition clearSession()
this._sessionLockedUntil = Date.now() + 15000;
// Save to cookie (1 day expiry)
this._setCookie('mm_token', token, 1);
this._setCookie('mm_user', JSON.stringify(user), 1);
// Also try sessionStorage
try {
sessionStorage.setItem('mm_token', token);
sessionStorage.setItem('mm_user', JSON.stringify(user));
} catch(e) {}
},
clearSession() {
if (Date.now() < this._sessionLockedUntil) {
console.warn('[Auth] clearSession blocked by lock', new Error().stack);
return;
}
this._memoryToken = null;
this._memoryUser = null;
this._deleteCookie('mm_token');
this._deleteCookie('mm_user');
try {
sessionStorage.removeItem('mm_token');
sessionStorage.removeItem('mm_user');
} catch(e) {}
},
async login(email, password) {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Erro no login');
this.setSession(data.token, data.user);
return data;
},
async logout() {
try {
await fetch('/api/auth/logout', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + this.getToken(),
'Content-Type': 'application/json'
}
});
} catch (e) { /* ignore */ }
this.clearSession();
window.location.hash = '#/login';
window.location.reload();
},
headers() {
return {
'Authorization': 'Bearer ' + this.getToken(),
'Content-Type': 'application/json'
};
}
};