Live
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
node_modules
|
||||
.env
|
||||
*.sqlite
|
||||
*.sqlite-*
|
||||
uploads/
|
||||
tmp/
|
||||
pino-*.log
|
||||
|
||||
+3
-2
@@ -1,11 +1,12 @@
|
||||
# ── Stage 1: install production dependencies ──────────────────────────────────
|
||||
FROM node:20-alpine AS deps
|
||||
ARG NODE_VERSION=20
|
||||
FROM node:${NODE_VERSION}-alpine AS deps
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm ci --omit=dev && npm cache clean --force
|
||||
|
||||
# ── Stage 2: runtime image ────────────────────────────────────────────────────
|
||||
FROM node:20-alpine
|
||||
FROM node:${NODE_VERSION}-alpine
|
||||
|
||||
# tini: PID 1 signal forwarding + zombie reaping
|
||||
RUN apk add --no-cache tini
|
||||
|
||||
+1
-1
@@ -134,7 +134,7 @@ async function boot() {
|
||||
initSocket(server);
|
||||
|
||||
const port = parseInt(process.env.PORT || '3000', 10);
|
||||
server.listen(port, () => {
|
||||
server.listen(port, process.env.HOST || undefined, () => {
|
||||
logger.info(`VitFit v${require('./package.json').version} listening on port ${port}`);
|
||||
if (process.send) process.send('ready'); // PM2 ready signal
|
||||
});
|
||||
|
||||
@@ -2,9 +2,7 @@
|
||||
|
||||
const express = require('express');
|
||||
const multer = require('multer');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const fs = require('fs');
|
||||
const { models } = require('../../core/db');
|
||||
const { authenticateToken, authenticateRole } = require('../../core/auth');
|
||||
const { ok, noContent } = require('../../core/respond');
|
||||
@@ -80,18 +78,24 @@ router.post('/logo', authenticateToken, authenticateRole(OWNERS), upload.single(
|
||||
} catch (err) { next(err); }
|
||||
});
|
||||
|
||||
router.get('/logo', authenticateToken, async (req, res, next) => {
|
||||
// Public: logos are rendered by <img src> (login page, banner), which cannot send
|
||||
// an Authorization header. Org id comes from the path; legacy /logo falls back to
|
||||
// the first org, matching GET /branding/public.
|
||||
router.get('/logo/:orgId?', async (req, res, next) => {
|
||||
try {
|
||||
const branding = await svc.getBranding(models, req.user.organizationId);
|
||||
if (!branding.logoPath) return next(new AppError('NOT_FOUND', 'No custom logo set.', 404));
|
||||
let orgId = parseInt(req.params.orgId, 10);
|
||||
if (isNaN(orgId)) {
|
||||
const org = await models.Organization.findOne({ order: [['id', 'ASC']] });
|
||||
if (!org) return next(new AppError('NOT_FOUND', 'No custom logo set.', 404));
|
||||
orgId = org.id;
|
||||
}
|
||||
|
||||
// Find logo file in uploads dir
|
||||
const uploadsDir = process.env.UPLOADS_DIR || path.join(__dirname, '..', '..', 'uploads');
|
||||
const files = fs.readdirSync(uploadsDir).filter(f => f.startsWith(`logo_${req.user.organizationId}_`));
|
||||
if (!files.length) return next(new AppError('NOT_FOUND', 'Logo file not found.', 404));
|
||||
const filePath = svc.findLogoFile(orgId);
|
||||
if (!filePath) return next(new AppError('NOT_FOUND', 'No custom logo set.', 404));
|
||||
|
||||
const logoFile = files.sort().pop(); // latest
|
||||
res.sendFile(path.join(uploadsDir, logoFile));
|
||||
// Path is versioned (?v=), so the file at a given URL never changes
|
||||
res.set('Cache-Control', 'public, max-age=31536000, immutable');
|
||||
res.sendFile(filePath);
|
||||
} catch (err) { next(err); }
|
||||
});
|
||||
|
||||
|
||||
@@ -5,7 +5,12 @@ const path = require('path');
|
||||
const { AppError } = require('../../core/errors');
|
||||
const { log: auditLog } = require('../../core/audit');
|
||||
|
||||
const UPLOADS_DIR = () => process.env.UPLOADS_DIR || path.join(__dirname, '..', '..', 'uploads');
|
||||
// Resolved to an absolute path: res.sendFile() rejects relative paths, and
|
||||
// UPLOADS_DIR is commonly configured as './uploads'.
|
||||
// file-type's documented minimum sniff size
|
||||
const SNIFF_BYTES = 4100;
|
||||
|
||||
const UPLOADS_DIR = () => path.resolve(process.env.UPLOADS_DIR || path.join(__dirname, '..', '..', 'uploads'));
|
||||
|
||||
|
||||
async function getOrg(models, orgId) {
|
||||
@@ -42,6 +47,17 @@ async function updateBranding(models, req, orgId, data) {
|
||||
return branding;
|
||||
}
|
||||
|
||||
async function moveFile(src, dest) {
|
||||
try {
|
||||
await fs.promises.rename(src, dest);
|
||||
} catch (err) {
|
||||
// Cross-device rename (systemd PrivateTmp, docker tmpfs, separate volumes)
|
||||
if (err.code !== 'EXDEV') throw err;
|
||||
await fs.promises.copyFile(src, dest);
|
||||
await fs.promises.unlink(src).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadLogo(models, req, orgId, file) {
|
||||
const { fileTypeFromBuffer } = await import('file-type');
|
||||
const ALLOWED = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
|
||||
@@ -49,11 +65,13 @@ async function uploadLogo(models, req, orgId, file) {
|
||||
|
||||
let detectedMime;
|
||||
try {
|
||||
// file-type needs 4100 bytes: detectors read past the magic number (a PNG
|
||||
// header alone makes it run off the end and throw EndOfStreamError).
|
||||
const fd = fs.openSync(file.path, 'r');
|
||||
const buf = Buffer.alloc(12);
|
||||
fs.readSync(fd, buf, 0, 12, 0);
|
||||
const buf = Buffer.alloc(SNIFF_BYTES);
|
||||
const read = fs.readSync(fd, buf, 0, SNIFF_BYTES, 0);
|
||||
fs.closeSync(fd);
|
||||
const result = await fileTypeFromBuffer(buf);
|
||||
const result = await fileTypeFromBuffer(buf.subarray(0, read));
|
||||
detectedMime = result?.mime;
|
||||
} catch {
|
||||
await fs.promises.unlink(file.path).catch(() => {});
|
||||
@@ -65,23 +83,65 @@ async function uploadLogo(models, req, orgId, file) {
|
||||
throw new AppError('UPLOAD_TYPE_INVALID', 'Only PNG, JPG, GIF, and WebP images are supported.', 400);
|
||||
}
|
||||
|
||||
const uploadsDir = UPLOADS_DIR();
|
||||
const version = Date.now();
|
||||
const ext = EXT_MAP[detectedMime];
|
||||
const safeName = `logo_${orgId}_${Date.now()}${ext}`;
|
||||
const destPath = path.join(UPLOADS_DIR(), safeName);
|
||||
const safeName = `logo_${orgId}_${version}${ext}`;
|
||||
|
||||
try {
|
||||
await fs.promises.mkdir(uploadsDir, { recursive: true });
|
||||
} catch (err) {
|
||||
await fs.promises.unlink(file.path).catch(() => {});
|
||||
throw new AppError('UPLOAD_FAILED', `Uploads directory is not writable (${uploadsDir}): ${err.code}.`, 500);
|
||||
}
|
||||
|
||||
const branding = await getBranding(models, orgId);
|
||||
|
||||
// Delete old logo
|
||||
if (branding.logoPath) {
|
||||
const oldFile = path.join(UPLOADS_DIR(), path.basename(branding.logoPath));
|
||||
await fs.promises.unlink(oldFile).catch(() => {});
|
||||
try {
|
||||
await moveFile(file.path, path.join(uploadsDir, safeName));
|
||||
} catch (err) {
|
||||
await fs.promises.unlink(file.path).catch(() => {});
|
||||
throw new AppError('UPLOAD_FAILED', `Could not store the logo (${err.code}).`, 500);
|
||||
}
|
||||
|
||||
await fs.promises.rename(file.path, destPath);
|
||||
await branding.update({ logoPath: `/api/v1/org/logo` });
|
||||
// Remove previous logos for this org (filenames, not the API path, are the source of truth)
|
||||
await removeOldLogos(uploadsDir, orgId, safeName);
|
||||
|
||||
await branding.update({ logoPath: `/api/v1/org/logo/${orgId}?v=${version}` });
|
||||
await auditLog(req, 'logo.upload', 'branding', branding.id, { filename: safeName });
|
||||
|
||||
return branding;
|
||||
}
|
||||
|
||||
module.exports = { getOrg, updateOrg, getBranding, updateBranding, uploadLogo };
|
||||
async function removeOldLogos(uploadsDir, orgId, keepName) {
|
||||
try {
|
||||
const files = await fs.promises.readdir(uploadsDir);
|
||||
await Promise.all(
|
||||
files
|
||||
.filter(f => f.startsWith(`logo_${orgId}_`) && f !== keepName)
|
||||
.map(f => fs.promises.unlink(path.join(uploadsDir, f)).catch(() => {}))
|
||||
);
|
||||
} catch { /* non-fatal */ }
|
||||
}
|
||||
|
||||
function findLogoFile(orgId) {
|
||||
const uploadsDir = UPLOADS_DIR();
|
||||
let files;
|
||||
try {
|
||||
files = fs.readdirSync(uploadsDir);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const matches = files
|
||||
.filter(f => f.startsWith(`logo_${orgId}_`))
|
||||
.sort((a, b) => logoTimestamp(a) - logoTimestamp(b));
|
||||
if (!matches.length) return null;
|
||||
return path.join(uploadsDir, matches[matches.length - 1]);
|
||||
}
|
||||
|
||||
function logoTimestamp(filename) {
|
||||
const m = filename.match(/^logo_\d+_(\d+)\./);
|
||||
return m ? parseInt(m[1], 10) : 0;
|
||||
}
|
||||
|
||||
module.exports = { getOrg, updateOrg, getBranding, updateBranding, uploadLogo, findLogoFile };
|
||||
|
||||
@@ -108,7 +108,7 @@
|
||||
const btn = document.getElementById('password-btn');
|
||||
btn.disabled = true; btn.textContent = 'Changing…';
|
||||
try {
|
||||
const res = await Api.post('/api/v1/my/change-password', {
|
||||
const res = await Api.put('/api/v1/my/password', {
|
||||
currentPassword: document.getElementById('current-password').value,
|
||||
newPassword: newPw,
|
||||
});
|
||||
|
||||
@@ -58,7 +58,7 @@
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="logo-file">Logo (PNG/JPG, max 2MB)</label>
|
||||
<label class="form-label" for="logo-file">Logo (PNG/JPG/GIF/WebP, max 5MB)</label>
|
||||
<input class="form-input" type="file" id="logo-file" accept="image/*">
|
||||
<img id="logo-preview" style="display:none;max-height:60px;margin-top:var(--space-2);">
|
||||
</div>
|
||||
@@ -271,8 +271,8 @@
|
||||
const { data } = await res.json();
|
||||
el.innerHTML = `<table class="table"><thead><tr><th>Name</th><th>Email</th><th>Role</th><th>Status</th><th></th></tr></thead><tbody>
|
||||
${data.map(u => `<tr>
|
||||
<td>${u.name}</td>
|
||||
<td>${u.email}</td>
|
||||
<td>${[u.firstName, u.lastName].filter(Boolean).join(' ') || u.username}</td>
|
||||
<td>${u.email || '—'}</td>
|
||||
<td>${u.role}</td>
|
||||
<td><span class="badge badge-${u.isActive ? 'success' : 'danger'}">${u.isActive ? 'Active' : 'Inactive'}</span></td>
|
||||
<td class="table-actions">
|
||||
@@ -392,6 +392,12 @@
|
||||
}
|
||||
} catch {}
|
||||
|
||||
// Server errors are shaped { error: { code, message } }
|
||||
async function errMessage(res) {
|
||||
try { const b = await res.json(); return b.error?.message || b.message || 'Failed.'; }
|
||||
catch { return `Failed (HTTP ${res.status}).`; }
|
||||
}
|
||||
|
||||
function hexOrUndefined(id) { const v = document.getElementById(id).value.trim(); return /^#[0-9A-Fa-f]{6}$/.test(v) ? v : undefined; }
|
||||
|
||||
document.getElementById('branding-form').addEventListener('submit', async (e) => {
|
||||
@@ -426,10 +432,14 @@
|
||||
const fd = new FormData();
|
||||
fd.append('logo', logoFile);
|
||||
const logoRes = await Api.upload('/api/v1/org/logo', fd);
|
||||
if (!logoRes.ok) { const b = await logoRes.json(); errEl.textContent = b.message || 'Failed.'; errEl.style.display = 'block'; return; }
|
||||
if (!logoRes.ok) { errEl.textContent = await errMessage(logoRes); errEl.style.display = 'block'; return; }
|
||||
const { data } = await logoRes.json();
|
||||
const img = document.getElementById('logo-preview');
|
||||
img.src = data.logoPath; img.style.display = '';
|
||||
document.getElementById('logo-file').value = '';
|
||||
}
|
||||
const res = await Api.patch('/api/v1/org/branding', brandFields);
|
||||
if (!res.ok) { const b = await res.json(); errEl.textContent = b.message || 'Failed.'; errEl.style.display = 'block'; return; }
|
||||
if (!res.ok) { errEl.textContent = await errMessage(res); errEl.style.display = 'block'; return; }
|
||||
toast('Branding updated.', 'success');
|
||||
Branding.load();
|
||||
} catch { errEl.textContent = 'Network error.'; errEl.style.display = 'block'; }
|
||||
|
||||
@@ -32,15 +32,17 @@ async function main() {
|
||||
console.log('║ VitFit V1 → V2 Data Migration ║');
|
||||
console.log('╚══════════════════════════════════════════╝\n');
|
||||
|
||||
const { initDb, runMigrations, models } = require('../core/db');
|
||||
const { sequelize } = require('../core/db');
|
||||
const db = require('../core/db');
|
||||
|
||||
// ── Step 1: schema migrations ────────────────────────────────────────────
|
||||
console.log('Step 1/5 Running schema migrations...');
|
||||
await initDb();
|
||||
await runMigrations();
|
||||
await db.initDb();
|
||||
await db.runMigrations();
|
||||
console.log(' Schema migrations complete.\n');
|
||||
|
||||
const { models } = db;
|
||||
const sequelize = db.getSequelize();
|
||||
|
||||
// ── Idempotency guard ────────────────────────────────────────────────────
|
||||
const orgCount = await models.Organization.count();
|
||||
if (orgCount > 0) {
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user