This commit is contained in:
Ccjcarkbla
2026-06-13 20:42:08 -04:00
parent a2c300678b
commit f4f0a2c93a
13 changed files with 8267 additions and 22 deletions
+1 -1
View File
@@ -3,7 +3,7 @@
const { z } = require('zod');
const login = z.object({
username: z.string().min(1).max(64),
identifier: z.string().min(1).max(200), // email or username
password: z.string().min(1).max(128),
rememberDevice: z.boolean().optional().default(false),
deviceName: z.string().max(200).optional(),
+5 -4
View File
@@ -5,7 +5,7 @@ const path = require('path');
const checkDiskSpace = require('check-disk-space').default;
const { AppError } = require('./errors');
const UPLOADS_DIR = () => process.env.UPLOADS_DIR || path.join(__dirname, '..', 'uploads');
const UPLOADS_DIR = () => path.resolve(process.env.UPLOADS_DIR || path.join(__dirname, '..', 'uploads'));
const WARN_BYTES = () => parseInt(process.env.STORAGE_WARN_BYTES || String(5 * 1024 ** 3), 10);
let cache = null;
@@ -33,8 +33,10 @@ async function getStorageInfo() {
if (inflightPromise) return inflightPromise;
inflightPromise = (async () => {
const dir = UPLOADS_DIR();
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
const [disk, uploads] = await Promise.all([
checkDiskSpace(UPLOADS_DIR()),
checkDiskSpace(dir),
getUploadsSize(),
]);
@@ -52,9 +54,8 @@ async function getStorageInfo() {
cache = result;
cacheTime = Date.now();
inflightPromise = null;
return result;
})();
})().finally(() => { inflightPromise = null; });
return inflightPromise;
}
+12 -6
View File
@@ -1,5 +1,6 @@
'use strict';
const { Op } = require('sequelize');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
@@ -60,22 +61,27 @@ async function createDeviceToken(models, userId, orgId, deviceName, deviceType)
return { rawToken, record };
}
async function login(models, req, { username, password, rememberDevice, deviceName, deviceType }) {
checkLockout(username);
async function login(models, req, { identifier, password, rememberDevice, deviceName, deviceType }) {
checkLockout(identifier);
const user = await models.User.findOne({
where: { username },
where: {
[Op.or]: [
{ username: identifier },
{ email: identifier },
],
},
attributes: ['id', 'username', 'email', 'role', 'organizationId', 'isActive', 'password'],
});
const valid = user && user.isActive && await bcrypt.compare(password, user.password);
if (!valid) {
recordFailure(username);
recordFailure(identifier);
throw new AppError('LOGIN_FAILED', 'Invalid username or password.', 401);
}
clearFailures(username);
clearFailures(identifier);
await user.update({ lastLoginAt: new Date() });
@@ -89,7 +95,7 @@ async function login(models, req, { username, password, rememberDevice, deviceNa
const userPublic = { id: user.id, username: user.username, role: user.role, organizationId: user.organizationId };
await auditLog(req, 'auth.login.success', 'user', user.id, { username });
await auditLog(req, 'auth.login.success', 'user', user.id, { identifier });
return { jwt: token, user: userPublic, ...(deviceToken ? { deviceToken } : {}) };
}
+1
View File
@@ -49,6 +49,7 @@ router.patch('/', authenticateToken, authenticateRole(OWNERS), validate(updateOr
router.get('/branding', authenticateToken, async (req, res, next) => {
try {
if (!req.user.organizationId) return ok(res, {});
const branding = await svc.getBranding(models, req.user.organizationId);
ok(res, branding);
} catch (err) { next(err); }
+7
View File
@@ -39,6 +39,13 @@ router.post('/', authenticateToken, authenticateRole(COACH_PLUS), validate(creat
} catch (err) { next(err); }
});
router.get('/session/active', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => {
try {
const session = svc.getActiveSession(req.user.organizationId);
ok(res, session);
} catch (err) { next(err); }
});
router.get('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => {
try {
const timer = await svc.getTimerById(models, parseInt(req.params.id, 10), req.user.organizationId);
+2 -2
View File
@@ -50,7 +50,7 @@ async function launchTimer(models, req, timerId, orgId) {
const sessionId = `timer_${timerId}_${Date.now()}`;
const engine = new TimerEngine(timer.toJSON(), io, sessionId);
activeSessions.set(sessionId, { engine, orgId });
activeSessions.set(sessionId, { engine, orgId, timerName: timer.name });
engine.start();
await auditLog(req, 'timer.launch', 'timer', timerId, { sessionId });
@@ -70,7 +70,7 @@ async function stopTimer(req, sessionId, orgId) {
function getActiveSession(orgId) {
for (const [sessionId, session] of activeSessions) {
if (session.orgId === orgId) {
return { sessionId, state: session.engine.getState() };
return { sessionId, timerName: session.timerName, state: session.engine.getState() };
}
}
return null;
+8224
View File
File diff suppressed because it is too large Load Diff
+5 -5
View File
@@ -19,8 +19,8 @@
<form id="login-form" novalidate>
<div class="form-group">
<label class="form-label" for="email">Email</label>
<input class="form-input" type="email" id="email" name="email" autocomplete="email" required>
<label class="form-label" for="identifier">Email or Username</label>
<input class="form-input" type="text" id="identifier" name="identifier" autocomplete="username" required>
</div>
<div class="form-group">
<label class="form-label" for="password">Password</label>
@@ -72,14 +72,14 @@
loginBtn.disabled = true;
loginBtn.textContent = 'Signing in…';
const email = document.getElementById('email').value.trim();
const password = document.getElementById('password').value;
const identifier = document.getElementById('identifier').value.trim();
const password = document.getElementById('password').value;
try {
const res = await fetch('/api/v1/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
body: JSON.stringify({ identifier, password }),
});
const body = await res.json();
if (!res.ok) {
+8 -2
View File
@@ -76,6 +76,7 @@ const Api = (() => {
// 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');
}
@@ -200,7 +201,10 @@ const Page = (() => {
function currentUser() {
const token = Auth.getJwt();
if (!token) return null;
return Auth.decodeJwt(token);
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) {
@@ -217,7 +221,9 @@ const Page = (() => {
}
if (allowedRoles && !allowedRoles.includes(user.role)) {
window.location.href = '/dashboard.html';
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;
}
+1 -1
View File
@@ -1,6 +1,6 @@
/* ── Reset ────────────────────────────────────────────────────────────────── */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html { -webkit-text-size-adjust: 100%; }
html { -webkit-text-size-adjust: 100%; text-size-adjust: 100%; }
body { -webkit-font-smoothing: antialiased; }
img, video { max-width: 100%; display: block; }
button, input, select, textarea { font: inherit; }
+1 -1
View File
@@ -1,7 +1,7 @@
/* VitFit Service Worker — shell-only caching for PWA install */
'use strict';
const CACHE_NAME = 'vitfit-v2';
const CACHE_NAME = 'vitfit-v3';
const SHELL_ASSETS = [
'/',
'/index.html',
Binary file not shown.
Binary file not shown.