Add curator roles/permissions with Users admin, and fix lineage branch joins.
Staff accounts use admin/curator roles and fine-grained flags; transitions connect source-to-target with color gradients and stream cutout masks so overlaps stay seamless. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
co-authored by
Cursor
parent
bfa21989c9
commit
0466b77328
+19
-17
@@ -8,9 +8,10 @@ require('dotenv').config();
|
||||
|
||||
const pool = require('./db');
|
||||
const { createSessionMiddleware } = require('./middleware/session');
|
||||
const { requireCurator } = require('./middleware/auth');
|
||||
const { requirePermission } = require('./middleware/auth');
|
||||
const { logCuratorAction } = require('./audit-log');
|
||||
const authRoutes = require('./routes/auth');
|
||||
const usersRoutes = require('./routes/users');
|
||||
const { ensurePaintingImages, preloadArtistImagesLocal, replacePaintingImageFromUrl, replaceArtistPortraitFromUrl, clearPaintingImage, deletePainting, clearArtistPortrait, replacePaintingImageFromBuffer, replaceArtistPortraitFromBuffer, enrichPaintingRow, enrichArtistRow, IMAGE_DIR } = require('./image-service');
|
||||
const { getVersionInfo } = require('./version-info');
|
||||
const { searchCatalog } = require('./search-service');
|
||||
@@ -44,6 +45,7 @@ app.use(compression());
|
||||
app.use(express.json({ limit: '20mb' }));
|
||||
app.use(createSessionMiddleware());
|
||||
app.use('/api/auth', authRoutes);
|
||||
app.use('/api/users', usersRoutes);
|
||||
app.use('/api/translations', translationRoutes);
|
||||
app.use('/api/influences', influenceRoutes);
|
||||
app.use('/api/tours', tourRoutes);
|
||||
@@ -469,7 +471,7 @@ app.get('/api/artists/:id/navigation', async (req, res) => {
|
||||
});
|
||||
|
||||
// Update artist portrait checkup flags (checked / fixed)
|
||||
app.patch('/api/artists/:id/checkup-flags', requireCurator, async (req, res) => {
|
||||
app.patch('/api/artists/:id/checkup-flags', requirePermission('checkup'), async (req, res) => {
|
||||
try {
|
||||
const artistId = parseInt(req.params.id, 10);
|
||||
const { checked, fixed } = req.body ?? {};
|
||||
@@ -537,7 +539,7 @@ app.patch('/api/artists/:id/checkup-flags', requireCurator, async (req, res) =>
|
||||
});
|
||||
|
||||
// Developer debug: portrait image search for artist bio
|
||||
app.get('/api/artists/:id/debug-portrait-search/more', requireCurator, async (req, res) => {
|
||||
app.get('/api/artists/:id/debug-portrait-search/more', requirePermission('images'), async (req, res) => {
|
||||
try {
|
||||
const artistId = parseInt(req.params.id, 10);
|
||||
const limit = Math.min(20, Math.max(1, parseInt(req.query.limit, 10) || 20));
|
||||
@@ -555,7 +557,7 @@ app.get('/api/artists/:id/debug-portrait-search/more', requireCurator, async (re
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/artists/:id/debug-portrait-search', requireCurator, async (req, res) => {
|
||||
app.get('/api/artists/:id/debug-portrait-search', requirePermission('images'), async (req, res) => {
|
||||
try {
|
||||
const artistId = parseInt(req.params.id, 10);
|
||||
const result = await pool.query(`SELECT name FROM artists WHERE id = $1`, [artistId]);
|
||||
@@ -573,7 +575,7 @@ app.get('/api/artists/:id/debug-portrait-search', requireCurator, async (req, re
|
||||
});
|
||||
|
||||
// Developer debug: replace artist portrait with a search result URL
|
||||
app.post('/api/artists/:id/fix-portrait', requireCurator, async (req, res) => {
|
||||
app.post('/api/artists/:id/fix-portrait', requirePermission('images'), async (req, res) => {
|
||||
try {
|
||||
const artistId = parseInt(req.params.id, 10);
|
||||
const { imageUrl, searchUrl, source, pageUrl, thumbUrl } = req.body ?? {};
|
||||
@@ -607,7 +609,7 @@ app.post('/api/artists/:id/fix-portrait', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/artists/:id/clear-portrait', requireCurator, async (req, res) => {
|
||||
app.post('/api/artists/:id/clear-portrait', requirePermission('images'), async (req, res) => {
|
||||
try {
|
||||
const artistId = parseInt(req.params.id, 10);
|
||||
const updated = await clearArtistPortrait(artistId);
|
||||
@@ -630,7 +632,7 @@ app.post('/api/artists/:id/clear-portrait', requireCurator, async (req, res) =>
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/artists/:id/upload-portrait', requireCurator, async (req, res) => {
|
||||
app.post('/api/artists/:id/upload-portrait', requirePermission('images'), async (req, res) => {
|
||||
try {
|
||||
const artistId = parseInt(req.params.id, 10);
|
||||
const { imageData, mimeType } = req.body ?? {};
|
||||
@@ -720,7 +722,7 @@ app.get('/api/artists/:id', async (req, res) => {
|
||||
});
|
||||
|
||||
// Painting image checkup (developer audit table) — must be before /api/paintings/:id
|
||||
app.get('/api/paintings/checkup', requireCurator, async (_req, res) => {
|
||||
app.get('/api/paintings/checkup', requirePermission('checkup'), async (_req, res) => {
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT p.id, p.title, p.year, p.image_path, p.thumbnail_path,
|
||||
@@ -768,7 +770,7 @@ app.get('/api/paintings/checkup', requireCurator, async (_req, res) => {
|
||||
});
|
||||
|
||||
// Update checkup workflow flags (checked / fixed)
|
||||
app.patch('/api/paintings/:id/checkup-flags', requireCurator, async (req, res) => {
|
||||
app.patch('/api/paintings/:id/checkup-flags', requirePermission('checkup'), async (req, res) => {
|
||||
try {
|
||||
const paintingId = parseInt(req.params.id, 10);
|
||||
const { checked, fixed } = req.body ?? {};
|
||||
@@ -837,7 +839,7 @@ app.patch('/api/paintings/:id/checkup-flags', requireCurator, async (req, res) =
|
||||
});
|
||||
|
||||
// Update public curator notes on a painting
|
||||
app.patch('/api/paintings/:id/curator-notes', requireCurator, async (req, res) => {
|
||||
app.patch('/api/paintings/:id/curator-notes', requirePermission('curator_notes'), async (req, res) => {
|
||||
try {
|
||||
const paintingId = parseInt(req.params.id, 10);
|
||||
if (!Number.isFinite(paintingId)) {
|
||||
@@ -941,7 +943,7 @@ app.post('/api/artists/:id/preload-images', async (req, res) => {
|
||||
});
|
||||
|
||||
// Developer debug: Google Images first result for image audit
|
||||
app.get('/api/paintings/:id/debug-image-search/more', requireCurator, async (req, res) => {
|
||||
app.get('/api/paintings/:id/debug-image-search/more', requirePermission('images'), async (req, res) => {
|
||||
try {
|
||||
const paintingId = parseInt(req.params.id, 10);
|
||||
const limit = Math.min(20, Math.max(1, parseInt(req.query.limit, 10) || 20));
|
||||
@@ -965,7 +967,7 @@ app.get('/api/paintings/:id/debug-image-search/more', requireCurator, async (req
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/paintings/:id/debug-image-search', requireCurator, async (req, res) => {
|
||||
app.get('/api/paintings/:id/debug-image-search', requirePermission('images'), async (req, res) => {
|
||||
try {
|
||||
const paintingId = parseInt(req.params.id, 10);
|
||||
const result = await pool.query(
|
||||
@@ -989,7 +991,7 @@ app.get('/api/paintings/:id/debug-image-search', requireCurator, async (req, res
|
||||
});
|
||||
|
||||
// Developer debug: replace painting image with a search result URL
|
||||
app.post('/api/paintings/:id/fix-image', requireCurator, async (req, res) => {
|
||||
app.post('/api/paintings/:id/fix-image', requirePermission('images'), async (req, res) => {
|
||||
try {
|
||||
const paintingId = parseInt(req.params.id, 10);
|
||||
const { imageUrl, searchUrl, source, pageUrl, thumbUrl } = req.body ?? {};
|
||||
@@ -1023,7 +1025,7 @@ app.post('/api/paintings/:id/fix-image', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/paintings/:id', requireCurator, async (req, res) => {
|
||||
app.delete('/api/paintings/:id', requirePermission('images'), async (req, res) => {
|
||||
try {
|
||||
const paintingId = parseInt(req.params.id, 10);
|
||||
if (!Number.isFinite(paintingId)) {
|
||||
@@ -1047,7 +1049,7 @@ app.delete('/api/paintings/:id', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/paintings/:id/clear-image', requireCurator, async (req, res) => {
|
||||
app.post('/api/paintings/:id/clear-image', requirePermission('images'), async (req, res) => {
|
||||
try {
|
||||
const paintingId = parseInt(req.params.id, 10);
|
||||
const updated = await clearPaintingImage(paintingId);
|
||||
@@ -1070,7 +1072,7 @@ app.post('/api/paintings/:id/clear-image', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/paintings/:id/upload-image', requireCurator, async (req, res) => {
|
||||
app.post('/api/paintings/:id/upload-image', requirePermission('images'), async (req, res) => {
|
||||
try {
|
||||
const paintingId = parseInt(req.params.id, 10);
|
||||
const { imageData, mimeType } = req.body ?? {};
|
||||
@@ -1111,7 +1113,7 @@ app.post('/api/paintings/:id/upload-image', requireCurator, async (req, res) =>
|
||||
});
|
||||
|
||||
// Proxy remote image for debug preview (avoids hotlink / CORS blocks)
|
||||
app.get('/api/debug/image-proxy', requireCurator, async (req, res) => {
|
||||
app.get('/api/debug/image-proxy', requirePermission('images'), async (req, res) => {
|
||||
try {
|
||||
const imageUrl = req.query.url;
|
||||
const searchUrl = req.query.searchUrl;
|
||||
|
||||
@@ -1,5 +1,34 @@
|
||||
const pool = require('../db');
|
||||
const { hasPermission, effectivePermissions } = require('../permissions');
|
||||
|
||||
async function loadStaffUser(userId) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, username, role, permissions, is_active
|
||||
FROM users WHERE id = $1`,
|
||||
[userId]
|
||||
);
|
||||
if (rows.length === 0) return null;
|
||||
const row = rows[0];
|
||||
return {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
role: row.role,
|
||||
permissions: row.permissions || [],
|
||||
is_active: row.is_active !== false,
|
||||
};
|
||||
}
|
||||
|
||||
function attachStaff(req, user) {
|
||||
req.curatorUser = {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
role: user.role,
|
||||
permissions: user.permissions,
|
||||
is_active: user.is_active,
|
||||
};
|
||||
}
|
||||
|
||||
/** Any active staff account (admin or curator). */
|
||||
async function requireCurator(req, res, next) {
|
||||
const userId = req.session?.userId;
|
||||
if (!userId) {
|
||||
@@ -7,16 +36,13 @@ async function requireCurator(req, res, next) {
|
||||
}
|
||||
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, username FROM users WHERE id = $1`,
|
||||
[userId]
|
||||
);
|
||||
if (rows.length === 0) {
|
||||
const user = await loadStaffUser(userId);
|
||||
if (!user || !user.is_active) {
|
||||
req.session.destroy(() => {});
|
||||
return res.status(401).json({ error: 'Curator login required' });
|
||||
}
|
||||
|
||||
req.curatorUser = rows[0];
|
||||
attachStaff(req, user);
|
||||
next();
|
||||
} catch (err) {
|
||||
console.error('Auth middleware error:', err.message);
|
||||
@@ -24,4 +50,46 @@ async function requireCurator(req, res, next) {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { requireCurator };
|
||||
/** Active staff with a specific permission (admins always pass). */
|
||||
function requirePermission(permission) {
|
||||
return async (req, res, next) => {
|
||||
const userId = req.session?.userId;
|
||||
if (!userId) {
|
||||
return res.status(401).json({ error: 'Curator login required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const user = await loadStaffUser(userId);
|
||||
if (!user || !user.is_active) {
|
||||
req.session.destroy(() => {});
|
||||
return res.status(401).json({ error: 'Curator login required' });
|
||||
}
|
||||
|
||||
attachStaff(req, user);
|
||||
|
||||
if (!hasPermission(user, permission)) {
|
||||
return res.status(403).json({ error: 'Permission denied' });
|
||||
}
|
||||
|
||||
next();
|
||||
} catch (err) {
|
||||
console.error('Auth middleware error:', err.message);
|
||||
res.status(500).json({ error: 'Authentication failed' });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function staffAuthPayload(user) {
|
||||
return {
|
||||
role: user.role,
|
||||
username: user.username,
|
||||
permissions: effectivePermissions(user),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
requireCurator,
|
||||
requirePermission,
|
||||
loadStaffUser,
|
||||
staffAuthPayload,
|
||||
};
|
||||
|
||||
+15
-3
@@ -17,6 +17,17 @@ const INCREMENTAL_MIGRATIONS = [
|
||||
'migrate-i18n.sql',
|
||||
'migrate-tours.sql',
|
||||
'migrate-curator-notes.sql',
|
||||
'migrate-user-roles.sql',
|
||||
];
|
||||
|
||||
const BOOTSTRAP_ADMIN_PERMISSIONS = [
|
||||
'images',
|
||||
'checkup',
|
||||
'curator_notes',
|
||||
'translations',
|
||||
'influences',
|
||||
'tours',
|
||||
'users',
|
||||
];
|
||||
|
||||
async function bootstrapCurator() {
|
||||
@@ -36,10 +47,11 @@ async function bootstrapCurator() {
|
||||
const bcrypt = require('bcryptjs');
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
await pool.query(
|
||||
`INSERT INTO users (username, password_hash) VALUES ($1, $2)`,
|
||||
[username, passwordHash]
|
||||
`INSERT INTO users (username, password_hash, role, permissions, is_active)
|
||||
VALUES ($1, $2, 'admin', $3::text[], true)`,
|
||||
[username, passwordHash, BOOTSTRAP_ADMIN_PERMISSIONS]
|
||||
);
|
||||
console.log(` bootstrap curator account: ${username}`);
|
||||
console.log(` bootstrap admin account: ${username}`);
|
||||
}
|
||||
|
||||
async function applySqlFile(label, filePath) {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/** Fine-grained curator tool permissions. Admins are treated as having all. */
|
||||
const ALL_PERMISSIONS = [
|
||||
'images',
|
||||
'checkup',
|
||||
'curator_notes',
|
||||
'translations',
|
||||
'influences',
|
||||
'tours',
|
||||
'users',
|
||||
];
|
||||
|
||||
function normalizePermissions(raw) {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
const allowed = new Set(ALL_PERMISSIONS);
|
||||
const out = [];
|
||||
for (const key of raw) {
|
||||
if (typeof key === 'string' && allowed.has(key) && !out.includes(key)) {
|
||||
out.push(key);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function effectivePermissions(user) {
|
||||
if (!user) return [];
|
||||
if (user.role === 'admin') return [...ALL_PERMISSIONS];
|
||||
return normalizePermissions(user.permissions);
|
||||
}
|
||||
|
||||
function hasPermission(user, permission) {
|
||||
if (!user || !permission) return false;
|
||||
if (user.role === 'admin') return true;
|
||||
return normalizePermissions(user.permissions).includes(permission);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ALL_PERMISSIONS,
|
||||
normalizePermissions,
|
||||
effectivePermissions,
|
||||
hasPermission,
|
||||
};
|
||||
+24
-19
@@ -1,6 +1,7 @@
|
||||
const express = require('express');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const pool = require('../db');
|
||||
const { loadStaffUser, staffAuthPayload } = require('../middleware/auth');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -11,19 +12,13 @@ router.get('/me', async (req, res) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, username FROM users WHERE id = $1`,
|
||||
[userId]
|
||||
);
|
||||
if (rows.length === 0) {
|
||||
const user = await loadStaffUser(userId);
|
||||
if (!user || !user.is_active) {
|
||||
req.session.destroy(() => {});
|
||||
return res.json({ role: 'user' });
|
||||
}
|
||||
|
||||
res.json({
|
||||
role: 'curator',
|
||||
username: rows[0].username,
|
||||
});
|
||||
res.json(staffAuthPayload(user));
|
||||
} catch (err) {
|
||||
console.error('Auth me error:', err.message);
|
||||
res.status(500).json({ error: 'Failed to read session' });
|
||||
@@ -38,23 +33,36 @@ router.post('/login', async (req, res) => {
|
||||
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, username, password_hash FROM users WHERE LOWER(username) = LOWER($1)`,
|
||||
`SELECT id, username, password_hash, role, permissions, is_active
|
||||
FROM users WHERE LOWER(username) = LOWER($1)`,
|
||||
[username.trim()]
|
||||
);
|
||||
if (rows.length === 0) {
|
||||
return res.status(401).json({ error: 'Invalid username or password' });
|
||||
}
|
||||
|
||||
const user = rows[0];
|
||||
const valid = await bcrypt.compare(password, user.password_hash);
|
||||
const row = rows[0];
|
||||
if (row.is_active === false) {
|
||||
return res.status(401).json({ error: 'Account is disabled' });
|
||||
}
|
||||
|
||||
const valid = await bcrypt.compare(password, row.password_hash);
|
||||
if (!valid) {
|
||||
return res.status(401).json({ error: 'Invalid username or password' });
|
||||
}
|
||||
|
||||
await pool.query(`UPDATE users SET last_login_at = NOW() WHERE id = $1`, [user.id]);
|
||||
await pool.query(`UPDATE users SET last_login_at = NOW() WHERE id = $1`, [row.id]);
|
||||
|
||||
req.session.userId = user.id;
|
||||
req.session.username = user.username;
|
||||
req.session.userId = row.id;
|
||||
req.session.username = row.username;
|
||||
|
||||
const user = {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
role: row.role,
|
||||
permissions: row.permissions || [],
|
||||
is_active: true,
|
||||
};
|
||||
|
||||
// Ensure the store writes before the response finishes (proxy / HTTPS).
|
||||
req.session.save((err) => {
|
||||
@@ -62,10 +70,7 @@ router.post('/login', async (req, res) => {
|
||||
console.error('Auth session save error:', err.message);
|
||||
return res.status(500).json({ error: 'Login failed' });
|
||||
}
|
||||
res.json({
|
||||
role: 'curator',
|
||||
username: user.username,
|
||||
});
|
||||
res.json(staffAuthPayload(user));
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Auth login error:', err.message);
|
||||
|
||||
+10
-10
@@ -1,6 +1,6 @@
|
||||
const express = require('express');
|
||||
const pool = require('../db');
|
||||
const { requireCurator } = require('../middleware/auth');
|
||||
const { requirePermission } = require('../middleware/auth');
|
||||
const { logCuratorAction } = require('../audit-log');
|
||||
const {
|
||||
COLUMN_ROLES,
|
||||
@@ -24,7 +24,7 @@ function parseId(value) {
|
||||
return Number.isFinite(n) && n > 0 ? Math.floor(n) : null;
|
||||
}
|
||||
|
||||
router.get('/presets', requireCurator, (_req, res) => {
|
||||
router.get('/presets', requirePermission('influences'), (_req, res) => {
|
||||
res.json({
|
||||
roles: COLUMN_ROLES,
|
||||
presets: Object.values(PRESETS).map((p) => ({
|
||||
@@ -35,7 +35,7 @@ router.get('/presets', requireCurator, (_req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/', requireCurator, async (req, res) => {
|
||||
router.get('/', requirePermission('influences'), async (req, res) => {
|
||||
try {
|
||||
const artistId = parseId(req.query.artistId);
|
||||
const paintingId = parseId(req.query.paintingId);
|
||||
@@ -138,7 +138,7 @@ router.get('/', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/graph', requireCurator, async (req, res) => {
|
||||
router.get('/graph', requirePermission('influences'), async (req, res) => {
|
||||
try {
|
||||
const artistId = parseId(req.query.artistId);
|
||||
const paintingId = parseId(req.query.paintingId);
|
||||
@@ -261,7 +261,7 @@ router.get('/graph', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/', requireCurator, async (req, res) => {
|
||||
router.post('/', requirePermission('influences'), async (req, res) => {
|
||||
try {
|
||||
const {
|
||||
paintingId,
|
||||
@@ -361,7 +361,7 @@ router.post('/', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id', requireCurator, async (req, res) => {
|
||||
router.patch('/:id', requirePermission('influences'), async (req, res) => {
|
||||
try {
|
||||
const id = parseId(req.params.id);
|
||||
if (!id) return res.status(400).json({ error: 'Invalid id' });
|
||||
@@ -450,7 +450,7 @@ router.patch('/:id', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id', requireCurator, async (req, res) => {
|
||||
router.delete('/:id', requirePermission('influences'), async (req, res) => {
|
||||
try {
|
||||
const id = parseId(req.params.id);
|
||||
if (!id) return res.status(400).json({ error: 'Invalid id' });
|
||||
@@ -491,7 +491,7 @@ router.delete('/:id', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/import/parse', requireCurator, async (req, res) => {
|
||||
router.post('/import/parse', requirePermission('influences'), async (req, res) => {
|
||||
try {
|
||||
const { filename, sheet, contentBase64, content } = req.body || {};
|
||||
let buffer;
|
||||
@@ -552,7 +552,7 @@ router.post('/import/parse', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/import/preview', requireCurator, async (req, res) => {
|
||||
router.post('/import/preview', requirePermission('influences'), async (req, res) => {
|
||||
try {
|
||||
const { rows, mapping, sourceLabel, contentHash, payloadHash } = req.body || {};
|
||||
if (!Array.isArray(rows) || !rows.length) {
|
||||
@@ -585,7 +585,7 @@ router.post('/import/preview', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/import/commit', requireCurator, async (req, res) => {
|
||||
router.post('/import/commit', requirePermission('influences'), async (req, res) => {
|
||||
try {
|
||||
const { proposals, fileName, contentHash, payloadHash, force } = req.body || {};
|
||||
if (!Array.isArray(proposals)) {
|
||||
|
||||
+8
-11
@@ -1,6 +1,6 @@
|
||||
const express = require('express');
|
||||
const pool = require('../db');
|
||||
const { requireCurator } = require('../middleware/auth');
|
||||
const { requirePermission, loadStaffUser } = require('../middleware/auth');
|
||||
const { logCuratorAction } = require('../audit-log');
|
||||
const { enrichPaintingRow } = require('../image-service');
|
||||
const { localizePaintings, resolveLocale, translationStatuses } = require('../translation-service');
|
||||
@@ -87,7 +87,7 @@ router.get('/', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/admin', requireCurator, async (_req, res) => {
|
||||
router.get('/admin', requirePermission('tours'), async (_req, res) => {
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT t.*,
|
||||
@@ -125,11 +125,8 @@ router.get('/:id', async (req, res) => {
|
||||
const tour = rows[0];
|
||||
let isCurator = false;
|
||||
if (req.session?.userId) {
|
||||
const { rows: users } = await pool.query(
|
||||
'SELECT id FROM users WHERE id = $1',
|
||||
[req.session.userId],
|
||||
);
|
||||
isCurator = users.length > 0;
|
||||
const user = await loadStaffUser(req.session.userId);
|
||||
isCurator = Boolean(user && user.is_active);
|
||||
}
|
||||
if (tour.status !== 'published' && !isCurator) {
|
||||
return res.status(404).json({ error: 'Tour not found' });
|
||||
@@ -150,7 +147,7 @@ router.get('/:id', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/', requireCurator, async (req, res) => {
|
||||
router.post('/', requirePermission('tours'), async (req, res) => {
|
||||
try {
|
||||
const title = typeof req.body?.title === 'string' ? req.body.title.trim() : '';
|
||||
if (!title) return res.status(400).json({ error: 'title required' });
|
||||
@@ -180,7 +177,7 @@ router.post('/', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id', requireCurator, async (req, res) => {
|
||||
router.patch('/:id', requirePermission('tours'), async (req, res) => {
|
||||
try {
|
||||
const id = parseId(req.params.id);
|
||||
if (!id) return res.status(400).json({ error: 'Invalid id' });
|
||||
@@ -236,7 +233,7 @@ router.patch('/:id', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id', requireCurator, async (req, res) => {
|
||||
router.delete('/:id', requirePermission('tours'), async (req, res) => {
|
||||
try {
|
||||
const id = parseId(req.params.id);
|
||||
if (!id) return res.status(400).json({ error: 'Invalid id' });
|
||||
@@ -260,7 +257,7 @@ router.delete('/:id', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.put('/:id/stops', requireCurator, async (req, res) => {
|
||||
router.put('/:id/stops', requirePermission('tours'), async (req, res) => {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const id = parseId(req.params.id);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const express = require('express');
|
||||
const pool = require('../db');
|
||||
const { requireCurator } = require('../middleware/auth');
|
||||
const { requirePermission } = require('../middleware/auth');
|
||||
const { logCuratorAction } = require('../audit-log');
|
||||
const {
|
||||
TRANSLATABLE_FIELDS,
|
||||
@@ -14,7 +14,7 @@ const router = express.Router();
|
||||
|
||||
const VALID_ENTITY_TYPES = new Set(Object.keys(TRANSLATABLE_FIELDS));
|
||||
|
||||
router.get('/worklist/:entityType', requireCurator, async (req, res) => {
|
||||
router.get('/worklist/:entityType', requirePermission('translations'), async (req, res) => {
|
||||
try {
|
||||
const entityType = req.params.entityType;
|
||||
const locale = typeof req.query.locale === 'string' ? req.query.locale : 'ru';
|
||||
@@ -75,7 +75,7 @@ router.get('/worklist/:entityType', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/coverage', requireCurator, async (req, res) => {
|
||||
router.get('/coverage', requirePermission('translations'), async (req, res) => {
|
||||
try {
|
||||
const locale = typeof req.query.locale === 'string' ? req.query.locale : 'ru';
|
||||
const coverage = await getTranslationCoverage(locale);
|
||||
@@ -86,7 +86,7 @@ router.get('/coverage', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/', requireCurator, async (req, res) => {
|
||||
router.get('/', requirePermission('translations'), async (req, res) => {
|
||||
try {
|
||||
const entityType = typeof req.query.entityType === 'string' ? req.query.entityType : undefined;
|
||||
const locale = typeof req.query.locale === 'string' ? req.query.locale : 'ru';
|
||||
@@ -99,7 +99,7 @@ router.get('/', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/:entityType/:id', requireCurator, async (req, res) => {
|
||||
router.get('/:entityType/:id', requirePermission('translations'), async (req, res) => {
|
||||
try {
|
||||
const entityType = req.params.entityType;
|
||||
const entityId = parseInt(req.params.id, 10);
|
||||
@@ -133,7 +133,7 @@ router.get('/:entityType/:id', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.put('/:entityType/:id', requireCurator, async (req, res) => {
|
||||
router.put('/:entityType/:id', requirePermission('translations'), async (req, res) => {
|
||||
try {
|
||||
const entityType = req.params.entityType;
|
||||
const entityId = parseInt(req.params.id, 10);
|
||||
@@ -185,7 +185,7 @@ router.put('/:entityType/:id', requireCurator, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/:entityType/:id/publish', requireCurator, async (req, res) => {
|
||||
router.post('/:entityType/:id/publish', requirePermission('translations'), async (req, res) => {
|
||||
try {
|
||||
const entityType = req.params.entityType;
|
||||
const entityId = parseInt(req.params.id, 10);
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
const express = require('express');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const pool = require('../db');
|
||||
const { requirePermission } = require('../middleware/auth');
|
||||
const { logCuratorAction } = require('../audit-log');
|
||||
const { ALL_PERMISSIONS, normalizePermissions } = require('../permissions');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const USER_SELECT = `id, username, role, permissions, is_active, created_at, last_login_at`;
|
||||
|
||||
function mapUser(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
role: row.role,
|
||||
permissions: row.role === 'admin' ? [...ALL_PERMISSIONS] : normalizePermissions(row.permissions),
|
||||
is_active: row.is_active !== false,
|
||||
created_at: row.created_at,
|
||||
last_login_at: row.last_login_at,
|
||||
};
|
||||
}
|
||||
|
||||
function parseRole(raw) {
|
||||
if (raw === 'admin' || raw === 'curator') return raw;
|
||||
return null;
|
||||
}
|
||||
|
||||
async function countActiveAdmins(client = pool) {
|
||||
const { rows } = await client.query(
|
||||
`SELECT COUNT(*)::int AS n FROM users WHERE role = 'admin' AND is_active = true`
|
||||
);
|
||||
return rows[0].n;
|
||||
}
|
||||
|
||||
async function clearUserSessions(userId) {
|
||||
// connect-pg-simple stores session JSON with userId
|
||||
await pool.query(`DELETE FROM session WHERE (sess->>'userId')::int = $1`, [userId]);
|
||||
}
|
||||
|
||||
router.use(requirePermission('users'));
|
||||
|
||||
router.get('/', async (_req, res) => {
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT ${USER_SELECT} FROM users ORDER BY username ASC`
|
||||
);
|
||||
res.json({ users: rows.map(mapUser), permissions: ALL_PERMISSIONS });
|
||||
} catch (err) {
|
||||
console.error('Users list error:', err.message);
|
||||
res.status(500).json({ error: 'Failed to list users' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/', async (req, res) => {
|
||||
try {
|
||||
const username =
|
||||
typeof req.body?.username === 'string' ? req.body.username.trim() : '';
|
||||
const password = typeof req.body?.password === 'string' ? req.body.password : '';
|
||||
const role = parseRole(req.body?.role) || 'curator';
|
||||
const permissions = normalizePermissions(req.body?.permissions);
|
||||
|
||||
if (!username || username.length < 2 || username.length > 64) {
|
||||
return res.status(400).json({ error: 'Username must be 2–64 characters' });
|
||||
}
|
||||
if (!/^[a-zA-Z0-9._-]+$/.test(username)) {
|
||||
return res.status(400).json({ error: 'Username may only contain letters, numbers, . _ -' });
|
||||
}
|
||||
if (!password || password.length < 8) {
|
||||
return res.status(400).json({ error: 'Password must be at least 8 characters' });
|
||||
}
|
||||
if (role === 'admin' && req.curatorUser.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Only admins can create admin accounts' });
|
||||
}
|
||||
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
const storedPermissions = role === 'admin' ? ALL_PERMISSIONS : permissions;
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO users (username, password_hash, role, permissions, is_active)
|
||||
VALUES ($1, $2, $3, $4::text[], true)
|
||||
RETURNING ${USER_SELECT}`,
|
||||
[username, passwordHash, role, storedPermissions]
|
||||
);
|
||||
|
||||
await logCuratorAction({
|
||||
userId: req.curatorUser.id,
|
||||
action: 'user.create',
|
||||
resourceType: 'user',
|
||||
resourceId: rows[0].id,
|
||||
details: { username, role, permissions: storedPermissions },
|
||||
req,
|
||||
});
|
||||
|
||||
res.status(201).json({ user: mapUser(rows[0]) });
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
return res.status(409).json({ error: 'Username already exists' });
|
||||
}
|
||||
console.error('Users create error:', err.message);
|
||||
res.status(500).json({ error: 'Failed to create user' });
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id', async (req, res) => {
|
||||
try {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
if (!Number.isFinite(id)) return res.status(400).json({ error: 'Invalid id' });
|
||||
|
||||
const { rows: existingRows } = await pool.query(
|
||||
`SELECT ${USER_SELECT} FROM users WHERE id = $1`,
|
||||
[id]
|
||||
);
|
||||
if (!existingRows[0]) return res.status(404).json({ error: 'User not found' });
|
||||
const existing = existingRows[0];
|
||||
|
||||
let role = existing.role;
|
||||
if (req.body?.role !== undefined) {
|
||||
const parsed = parseRole(req.body.role);
|
||||
if (!parsed) return res.status(400).json({ error: 'Invalid role' });
|
||||
if (parsed === 'admin' && req.curatorUser.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Only admins can promote to admin' });
|
||||
}
|
||||
if (existing.role === 'admin' && parsed !== 'admin' && req.curatorUser.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Only admins can demote admins' });
|
||||
}
|
||||
role = parsed;
|
||||
}
|
||||
|
||||
let permissions = normalizePermissions(existing.permissions);
|
||||
if (req.body?.permissions !== undefined) {
|
||||
permissions = normalizePermissions(req.body.permissions);
|
||||
}
|
||||
if (role === 'admin') {
|
||||
permissions = [...ALL_PERMISSIONS];
|
||||
}
|
||||
|
||||
let isActive = existing.is_active !== false;
|
||||
if (req.body?.is_active !== undefined) {
|
||||
if (typeof req.body.is_active !== 'boolean') {
|
||||
return res.status(400).json({ error: 'is_active must be boolean' });
|
||||
}
|
||||
isActive = req.body.is_active;
|
||||
}
|
||||
|
||||
if (
|
||||
existing.role === 'admin' &&
|
||||
existing.is_active !== false &&
|
||||
(role !== 'admin' || !isActive)
|
||||
) {
|
||||
const admins = await countActiveAdmins();
|
||||
if (admins <= 1) {
|
||||
return res.status(400).json({ error: 'Cannot deactivate or demote the last active admin' });
|
||||
}
|
||||
}
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE users
|
||||
SET role = $2, permissions = $3::text[], is_active = $4
|
||||
WHERE id = $1
|
||||
RETURNING ${USER_SELECT}`,
|
||||
[id, role, permissions, isActive]
|
||||
);
|
||||
|
||||
if (!isActive) {
|
||||
await clearUserSessions(id);
|
||||
}
|
||||
|
||||
await logCuratorAction({
|
||||
userId: req.curatorUser.id,
|
||||
action: 'user.update',
|
||||
resourceType: 'user',
|
||||
resourceId: id,
|
||||
details: {
|
||||
username: rows[0].username,
|
||||
role,
|
||||
permissions,
|
||||
is_active: isActive,
|
||||
},
|
||||
req,
|
||||
});
|
||||
|
||||
res.json({ user: mapUser(rows[0]) });
|
||||
} catch (err) {
|
||||
console.error('Users update error:', err.message);
|
||||
res.status(500).json({ error: 'Failed to update user' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/:id/password', async (req, res) => {
|
||||
try {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
if (!Number.isFinite(id)) return res.status(400).json({ error: 'Invalid id' });
|
||||
|
||||
const password = typeof req.body?.password === 'string' ? req.body.password : '';
|
||||
if (!password || password.length < 8) {
|
||||
return res.status(400).json({ error: 'Password must be at least 8 characters' });
|
||||
}
|
||||
|
||||
const { rows: existingRows } = await pool.query(
|
||||
`SELECT id, username, role FROM users WHERE id = $1`,
|
||||
[id]
|
||||
);
|
||||
if (!existingRows[0]) return res.status(404).json({ error: 'User not found' });
|
||||
|
||||
if (existingRows[0].role === 'admin' && req.curatorUser.role !== 'admin' && req.curatorUser.id !== id) {
|
||||
return res.status(403).json({ error: 'Only admins can reset another admin password' });
|
||||
}
|
||||
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
await pool.query(`UPDATE users SET password_hash = $2 WHERE id = $1`, [id, passwordHash]);
|
||||
await clearUserSessions(id);
|
||||
|
||||
await logCuratorAction({
|
||||
userId: req.curatorUser.id,
|
||||
action: 'user.reset_password',
|
||||
resourceType: 'user',
|
||||
resourceId: id,
|
||||
details: { username: existingRows[0].username },
|
||||
req,
|
||||
});
|
||||
|
||||
res.json({ ok: true });
|
||||
} catch (err) {
|
||||
console.error('Users password error:', err.message);
|
||||
res.status(500).json({ error: 'Failed to reset password' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user