feat: admin dashboard for user management

Adds an /admin route, visible only to users with role=admin, that lets an
operator manage the user base from the UI:
- list / search users (active + inactive)
- create new accounts (with role and optional display name)
- reset a user's password
- promote/demote between admin and member
- deactivate / reactivate (soft-delete via is_active flag)

Backend changes:
- New adminOrApiKeyMiddleware accepts EITHER a Bearer JWT belonging to a
  role=admin user (UI path) OR the existing X-API-Key (bot/server-to-server).
- Existing /api/admin/* routes switched to the hybrid middleware, so the same
  endpoints serve both the dashboard and any external scripts.
- Added PUT /api/admin/users/:id/role and PUT /api/admin/users/:id/reactivate.
- Self-deactivation and self-demotion are explicitly blocked so an admin can't
  lock themselves out.

Frontend changes:
- New Admin.tsx page (table view, modals for create + reset, toast feedback).
- Admin button in CollectionList header, only rendered for admin role.
- Wired into App.tsx routing.

Also: friendly error when poppler-utils is missing on the host (PDF uploads
return 501 POPPLER_MISSING with a one-line install hint instead of crashing
the request); README clarifies poppler is required for the manual install.
This commit is contained in:
Hiren Kangad
2026-04-28 20:34:49 +05:30
parent f2260a9e35
commit 782d6df9e0
8 changed files with 606 additions and 9 deletions
+33
View File
@@ -81,6 +81,38 @@ function apiKeyMiddleware(req, res, next) {
next();
}
/**
* Express middleware: accepts EITHER a valid X-API-Key (server-to-server / bot)
* OR a Bearer JWT belonging to a user with role=admin (UI dashboard).
*
* On JWT path: attaches decoded user to req.user.
*/
function adminOrApiKeyMiddleware(req, res, next) {
const apiKey = req.headers['x-api-key'];
if (apiKey && REFBOARD_API_KEY && apiKey === REFBOARD_API_KEY) {
return next();
}
const authHeader = req.headers.authorization;
if (authHeader && authHeader.startsWith('Bearer ')) {
try {
const decoded = verifyToken(authHeader.slice(7));
if (decoded.role !== 'admin') {
return res.status(403).json({ error: 'Admin access required' });
}
req.user = decoded;
return next();
} catch (err) {
if (err.name === 'TokenExpiredError') {
return res.status(401).json({ error: 'Token expired' });
}
return res.status(401).json({ error: 'Invalid token' });
}
}
return res.status(401).json({ error: 'Admin authentication required' });
}
module.exports = {
generateToken,
verifyToken,
@@ -89,5 +121,6 @@ module.exports = {
authMiddleware,
adminMiddleware,
apiKeyMiddleware,
adminOrApiKeyMiddleware,
JWT_SECRET,
};
+35 -1
View File
@@ -15,6 +15,32 @@ const execFileAsync = promisify(execFile);
const TIMEOUT_MS = 60_000;
class PopplerMissingError extends Error {
constructor(binary) {
super(
`RefBoard couldn't run "${binary}". PDF support requires poppler-utils to be installed on the host. ` +
`On macOS: brew install poppler. On Debian/Ubuntu: apt install poppler-utils. ` +
`The provided Dockerfile already installs it — this only matters for manual installs.`
);
this.code = 'POPPLER_MISSING';
this.binary = binary;
this.statusCode = 501;
}
}
function wrapEnoent(binary, fn) {
return async (...args) => {
try {
return await fn(...args);
} catch (err) {
if (err && err.code === 'ENOENT' && (err.path === binary || err.syscall === `spawn ${binary}`)) {
throw new PopplerMissingError(binary);
}
throw err;
}
};
}
/**
* Write a buffer to a temporary file. Returns { tmpPath, cleanup }.
* Caller MUST call cleanup() when done.
@@ -131,4 +157,12 @@ async function pdfRenderPage(filePath, pageNum, dpi = 150) {
}
}
module.exports = { pdfInfo, pdfRenderPage, bufferToTempFile };
const safePdfInfo = wrapEnoent('pdfinfo', pdfInfo);
const safePdfRenderPage = wrapEnoent('pdftoppm', pdfRenderPage);
module.exports = {
pdfInfo: safePdfInfo,
pdfRenderPage: safePdfRenderPage,
bufferToTempFile,
PopplerMissingError,
};
+53 -5
View File
@@ -1,11 +1,13 @@
const { Router } = require('express');
const { v4: uuidv4 } = require('uuid');
const { apiKeyMiddleware, hashPassword } = require('../auth');
const { adminOrApiKeyMiddleware, hashPassword } = require('../auth');
const {
db,
createUser,
getAllUsers,
getUserById,
getUserByEmail,
getUserByUsername,
deactivateUser,
updateUserPassword,
createCollection,
@@ -17,21 +19,29 @@ const {
const router = Router();
router.use(apiKeyMiddleware);
router.use(adminOrApiKeyMiddleware);
// ---- User management ----
router.post('/users', async (req, res) => {
try {
const { email, username, password, display_name, role } = req.body;
const { email, username, password, display_name, displayName, role } = req.body;
const dn = display_name || displayName;
if (!email || !username || !password) {
return res.status(400).json({ error: 'Email, username, and password are required' });
}
if (password.length < 6) {
return res.status(400).json({ error: 'Password must be at least 6 characters' });
}
const existing = getUserByEmail(email);
if (existing) {
return res.status(409).json({ error: 'Email already registered' });
}
const existingUsername = getUserByUsername(username);
if (existingUsername) {
return res.status(409).json({ error: 'Username already taken' });
}
const passwordHash = await hashPassword(password);
const user = createUser({
@@ -39,8 +49,8 @@ router.post('/users', async (req, res) => {
email,
username,
passwordHash,
displayName: display_name || username,
role: role || 'member',
displayName: dn || username,
role: role === 'admin' ? 'admin' : 'member',
});
return res.status(201).json({
@@ -75,6 +85,9 @@ router.delete('/users/:userId', (req, res) => {
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
if (req.user && req.user.id === req.params.userId) {
return res.status(400).json({ error: 'You cannot deactivate your own account' });
}
deactivateUser(req.params.userId);
return res.json({ message: 'User deactivated' });
} catch (err) {
@@ -83,6 +96,41 @@ router.delete('/users/:userId', (req, res) => {
}
});
router.put('/users/:userId/reactivate', (req, res) => {
try {
const row = db.prepare('SELECT id FROM users WHERE id = ?').get(req.params.userId);
if (!row) {
return res.status(404).json({ error: 'User not found' });
}
db.prepare("UPDATE users SET is_active = 1, updated_at = datetime('now') WHERE id = ?").run(req.params.userId);
return res.json({ message: 'User reactivated' });
} catch (err) {
console.error('[admin] reactivate user error:', err);
return res.status(500).json({ error: 'Internal server error' });
}
});
router.put('/users/:userId/role', (req, res) => {
try {
const { role } = req.body || {};
if (role !== 'admin' && role !== 'member') {
return res.status(400).json({ error: "role must be 'admin' or 'member'" });
}
const user = getUserById(req.params.userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
if (req.user && req.user.id === req.params.userId && role !== 'admin') {
return res.status(400).json({ error: 'You cannot demote your own admin account' });
}
db.prepare("UPDATE users SET role = ?, updated_at = datetime('now') WHERE id = ?").run(role, req.params.userId);
return res.json({ message: 'Role updated', role });
} catch (err) {
console.error('[admin] update role error:', err);
return res.status(500).json({ error: 'Internal server error' });
}
});
router.put('/users/:userId/password', async (req, res) => {
try {
const { password } = req.body;
+4
View File
@@ -250,6 +250,10 @@ router.post('/boards/:boardId/images', upload.single('image'), async (req, res)
if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(413).json({ error: `File too large (max ${MAX_FILE_SIZE_LABEL})` });
}
if (err.code === 'POPPLER_MISSING') {
console.error('[upload] poppler-utils missing — PDF support disabled until host installs it');
return res.status(err.statusCode || 501).json({ error: err.message, code: err.code });
}
console.error('[upload] error:', err);
return res.status(500).json({ error: 'Internal server error' });
}