Files
refboard-ayon/backend/auth.js
T
Hiren KangadandClaude Opus 4.7 76a6e462ee feat: zero-config first boot and pluggable storage backend
Two changes that drop the friction in self-hosting RefBoard so the install
story becomes "docker compose up, open the URL".

1. JWT_SECRET is now optional. On first boot the backend generates a
   64-byte random secret and persists it in the existing settings table.
   process.env.JWT_SECRET still wins when set, so ops setups that manage
   secrets out-of-band are unaffected. The prod-throws-without-env guard
   is gone (auto-generation is a strictly safer default than the previous
   hardcoded dev fallback).

2. STORAGE_BACKEND=fs|minio picks between MinIO (default, unchanged) and
   a new local-filesystem adapter. The FS adapter exposes a fake minioClient
   that mirrors the methods RefBoard calls (statObject, getObject,
   getPartialObject, listObjectsV2, putObject, removeObject(s), bucketExists,
   makeBucket), so consumers swap require('./minio') for require('./storage')
   and nothing else changes. Sidecar .mime files hold Content-Type so the
   range-aware media proxy still serves the right response headers.

examples/compose/minimal-fs.yml is the single-container variant that uses
the FS adapter. The default docker-compose.yml still spins up MinIO.

README quick-start collapses to one block (cp .env, docker compose pull,
docker compose up -d). The first user you register on the Login screen is
auto-promoted to admin, same as before.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 09:51:20 +05:30

130 lines
3.7 KiB
JavaScript

const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d';
const BCRYPT_ROUNDS = 12;
const REFBOARD_API_KEY = process.env.REFBOARD_API_KEY || '';
// Memoized — resolved lazily so db.js is required after its module
// initialization side-effects have run. After the first call the secret is
// cached for the life of the process.
let _cachedJwtSecret = null;
function jwtSecret() {
if (_cachedJwtSecret) return _cachedJwtSecret;
const { getOrCreateJwtSecret } = require('./db');
_cachedJwtSecret = getOrCreateJwtSecret();
return _cachedJwtSecret;
}
function generateToken(user) {
return jwt.sign(
{ id: user.id, email: user.email, role: user.role, username: user.username, display_name: user.display_name },
jwtSecret(),
{ expiresIn: JWT_EXPIRES_IN }
);
}
function verifyToken(token) {
return jwt.verify(token, jwtSecret());
}
async function hashPassword(password) {
return bcrypt.hash(password, BCRYPT_ROUNDS);
}
async function comparePassword(password, hash) {
return bcrypt.compare(password, hash);
}
/**
* Express middleware: validates Bearer token from Authorization header.
* Attaches decoded user to req.user.
*/
function authMiddleware(req, res, next) {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Authentication required' });
}
const token = authHeader.slice(7);
const decoded = verifyToken(token);
req.user = decoded;
next();
} catch (err) {
if (err.name === 'TokenExpiredError') {
return res.status(401).json({ error: 'Token expired' });
}
return res.status(401).json({ error: 'Invalid token' });
}
}
/**
* Express middleware: checks that authenticated user has admin role.
* Must be used after authMiddleware.
*/
function adminMiddleware(req, res, next) {
if (!req.user || req.user.role !== 'admin') {
return res.status(403).json({ error: 'Admin access required' });
}
next();
}
/**
* Express middleware: validates X-API-Key header against REFBOARD_API_KEY env var.
* Used for admin/bot API routes.
*/
function apiKeyMiddleware(req, res, next) {
const apiKey = req.headers['x-api-key'];
if (!REFBOARD_API_KEY) {
return res.status(503).json({ error: 'API key not configured on server' });
}
if (!apiKey || apiKey !== REFBOARD_API_KEY) {
return res.status(401).json({ error: 'Invalid or missing API key' });
}
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,
hashPassword,
comparePassword,
authMiddleware,
adminMiddleware,
apiKeyMiddleware,
adminOrApiKeyMiddleware,
};