Files
vitfit-r2/V2/app/public/js/core.js
T
2026-06-13 20:42:08 -04:00

263 lines
11 KiB
JavaScript

/* VitFit core.js — loaded on every page */
'use strict';
// ── Auth ──────────────────────────────────────────────────────────────────────
const Auth = (() => {
const JWT_KEY = 'vf_jwt';
const DEVICE_KEY = 'vf_device';
function getJwt() { return localStorage.getItem(JWT_KEY); }
function setJwt(t) { localStorage.setItem(JWT_KEY, t); }
function getDeviceToken() { return localStorage.getItem(DEVICE_KEY); }
function setDeviceToken(t) { localStorage.setItem(DEVICE_KEY, t); }
function clearSession() { localStorage.removeItem(JWT_KEY); localStorage.removeItem(DEVICE_KEY); }
function decodeJwt(token) {
try {
return JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')));
} catch { return null; }
}
function isTokenExpiringSoon(token) {
const payload = decodeJwt(token);
if (!payload?.exp) return false;
return (payload.exp * 1000 - Date.now()) < 60 * 60 * 1000; // < 1 hour
}
async function tryDeviceLogin() {
const deviceToken = getDeviceToken();
if (!deviceToken) return false;
try {
const res = await fetch('/api/v1/auth/device-login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ deviceToken }),
});
if (!res.ok) return false;
const { data } = await res.json();
setJwt(data.jwt);
if (data.deviceToken) setDeviceToken(data.deviceToken);
return true;
} catch { return false; }
}
async function autoRefreshIfNeeded() {
const token = getJwt();
if (!token || !isTokenExpiringSoon(token)) return;
try {
const res = await fetch('/api/v1/auth/refresh-token', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
});
if (res.ok) {
const { data } = await res.json();
setJwt(data.jwt);
}
} catch {}
}
return { getJwt, setJwt, getDeviceToken, setDeviceToken, clearSession, decodeJwt, isTokenExpiringSoon, tryDeviceLogin, autoRefreshIfNeeded };
})();
// ── Api ───────────────────────────────────────────────────────────────────────
const Api = (() => {
async function _fetch(url, options = {}, retry = true) {
await Auth.autoRefreshIfNeeded();
const jwt = Auth.getJwt();
const headers = { ...(options.headers || {}) };
if (jwt) headers['Authorization'] = `Bearer ${jwt}`;
if (!(options.body instanceof FormData) && options.body) {
headers['Content-Type'] = 'application/json';
}
const res = await fetch(url, { ...options, headers });
if (res.status === 401 && retry) {
// Try device login once
const refreshed = await Auth.tryDeviceLogin();
if (refreshed) return _fetch(url, options, false);
Auth.clearSession();
Page.showSessionExpiredOverlay();
throw new Error('Session expired');
}
return res;
}
const get = (url, params) => _fetch(url + (params ? '?' + new URLSearchParams(params) : ''));
const post = (url, body) => _fetch(url, { method: 'POST', body: JSON.stringify(body) });
const patch = (url, body) => _fetch(url, { method: 'PATCH', body: JSON.stringify(body) });
const put = (url, body) => _fetch(url, { method: 'PUT', body: JSON.stringify(body) });
const del = (url) => _fetch(url, { method: 'DELETE' });
const upload = (url, formData) => _fetch(url, { method: 'POST', body: formData });
return { fetch: _fetch, get, post, patch, put, del, upload };
})();
// ── Nav ───────────────────────────────────────────────────────────────────────
const Nav = (() => {
const NAV_LINKS = [
{ label: 'Dashboard', href: '/dashboard.html', roles: ['Owner', 'Coach'] },
{ label: 'Videos', href: '/videos.html', roles: ['Owner', 'Coach'] },
{ label: 'Workouts', href: '/workouts.html', roles: ['Owner', 'Coach'] },
{ label: 'Timers', href: '/timers.html', roles: ['Owner', 'Coach'] },
{ label: 'CrossFit', href: '/crossfit.html', roles: ['Owner', 'Coach'] },
{ label: 'Clients', href: '/clients.html', roles: ['Owner', 'Coach'], feature: 'client-management' },
{ label: 'Calendar', href: '/calendar.html', roles: ['Owner', 'Coach'], feature: 'calendar' },
{ label: 'My Workouts', href: '/my-workouts.html', roles: ['Client'] },
{ label: 'My Schedule', href: '/my-schedule.html', roles: ['Client'], feature: 'calendar' },
{ label: 'Settings', href: '/settings.html', roles: ['Owner'] },
{ label: 'Audit Log', href: '/audit-log.html', roles: ['Owner'] },
{ label: 'System Admin',href: '/sysadmin.html', roles: ['SystemAdmin'] },
{ label: 'Profile', href: '/profile.html', roles: ['Owner', 'Coach', 'Client', 'SystemAdmin'] },
{ label: 'Log Out', href: '#', action: 'logout', roles: ['Owner', 'Coach', 'Client', 'SystemAdmin'] },
];
function init(currentPage) {
const drawer = document.getElementById('nav-drawer');
const scrim = document.getElementById('drawer-scrim');
const hamb = document.getElementById('nav-hamburger');
const navList = document.getElementById('nav-list');
if (!drawer || !navList) return;
const user = Page.currentUser();
const orgFeatures = (window._orgFeatures || []);
navList.innerHTML = '';
NAV_LINKS.forEach(link => {
if (!link.roles.includes(user?.role)) return;
if (link.feature && !orgFeatures.includes(link.feature)) return;
const li = document.createElement('li');
const a = document.createElement('a');
a.textContent = link.label;
a.href = link.href;
if (link.href === currentPage || window.location.pathname.endsWith(link.href)) {
a.classList.add('active');
}
if (link.action === 'logout') {
a.addEventListener('click', async (e) => {
e.preventDefault();
await Api.post('/api/v1/auth/logout', {}).catch(() => {});
Auth.clearSession();
window.location.href = '/';
});
}
li.appendChild(a);
navList.appendChild(li);
});
hamb?.addEventListener('click', toggle);
scrim?.addEventListener('click', close);
}
function toggle() {
const drawer = document.getElementById('nav-drawer');
const scrim = document.getElementById('drawer-scrim');
drawer?.classList.toggle('open');
scrim?.classList.toggle('open');
}
function close() {
document.getElementById('nav-drawer')?.classList.remove('open');
document.getElementById('drawer-scrim')?.classList.remove('open');
}
return { init, toggle, close };
})();
// ── Branding ──────────────────────────────────────────────────────────────────
const Branding = (() => {
async function load() {
try {
const res = await Api.get('/api/v1/org/branding');
if (!res.ok) return;
const { data } = await res.json();
apply(data);
window._orgFeatures = data.features || [];
// Set app name in banner
const titleEl = document.getElementById('app-name');
if (titleEl && data.appName) titleEl.textContent = data.appName;
// Set logo if present
const logoEl = document.getElementById('banner-logo');
if (logoEl && data.logoPath) { logoEl.src = data.logoPath; logoEl.style.display = ''; }
} catch {}
}
function apply(branding) {
const root = document.documentElement.style;
if (branding.primaryColor) root.setProperty('--color-primary', branding.primaryColor);
if (branding.secondaryColor) root.setProperty('--color-secondary', branding.secondaryColor);
if (branding.workColor) root.setProperty('--color-work', branding.workColor);
if (branding.restColor) root.setProperty('--color-rest', branding.restColor);
if (branding.moveColor) root.setProperty('--color-move', branding.moveColor);
}
return { load, apply };
})();
// ── Page ──────────────────────────────────────────────────────────────────────
const Page = (() => {
function currentUser() {
const token = Auth.getJwt();
if (!token) return null;
const payload = Auth.decodeJwt(token);
if (!payload) return null;
if (payload.exp && payload.exp * 1000 < Date.now()) { Auth.clearSession(); return null; }
return payload;
}
async function init(allowedRoles) {
let user = currentUser();
if (!user) {
const refreshed = await Auth.tryDeviceLogin();
if (refreshed) { user = currentUser(); }
}
if (!user) {
window.location.href = '/';
return;
}
if (allowedRoles && !allowedRoles.includes(user.role)) {
if (user.role === 'Client') window.location.href = '/my-workouts.html';
else if (user.role === 'SystemAdmin') window.location.href = '/sysadmin.html';
else window.location.href = '/dashboard.html';
return;
}
await Branding.load();
Nav.init(window.location.pathname);
}
function showSessionExpiredOverlay() {
document.getElementById('session-expired-overlay')?.classList.add('visible');
}
return { init, currentUser, showSessionExpiredOverlay };
})();
// ── Toast ─────────────────────────────────────────────────────────────────────
function toast(message, type = 'info', duration = 3000) {
let container = document.getElementById('toast-container');
if (!container) {
container = document.createElement('div');
container.id = 'toast-container';
document.body.appendChild(container);
}
const el = document.createElement('div');
el.className = `toast toast-${type}`;
el.textContent = message;
container.appendChild(el);
setTimeout(() => el.remove(), duration);
}
// ── Back-forward cache (bfcache) re-init ──────────────────────────────────────
window.addEventListener('pageshow', (e) => {
if (e.persisted && window._socketClient) {
// Re-connect socket on bfcache restore
window._socketClient.connect?.();
}
});