feat: runtime self-registration toggle in admin dashboard

Self-registration is now controlled at runtime from the admin panel rather
than at build time via an env var. Default: off.

- New `settings` table (key/value/updated_at) plus getSetting/setSetting
  helpers. Idempotent first-boot migration seeds allow_self_registration
  from the ALLOW_SELF_REGISTRATION env var; after first boot the env var
  is ignored and admins control the toggle from the UI.
- New public GET /api/auth/config (no auth) — returns
  { allowSelfRegistration, hasUsers }. The Login page polls this on mount
  to decide whether to show a Register link, and to render
  "Create the first admin account" mode when the install is empty.
- New admin GET /api/admin/settings + PUT /api/admin/settings/:key for
  the dashboard. Constrained to a known-keys allowlist with type coercion
  so unrecognized keys can't be stored.
- POST /api/auth/register now reads the toggle from the database instead
  of process.env. The first user is still always allowed and is auto-
  promoted to admin.
- Admin.tsx grows a "Settings" card with a labelled toggle switch and
  toast feedback. The card sits above the user table.
- VITE_ALLOW_SELF_REGISTRATION dropped — runtime fetch replaces it.

Docs: README + .env.example clarify that ALLOW_SELF_REGISTRATION is now
an initial seed only, the going-public checklist points at the dashboard
toggle, and the features list calls out runtime control.
This commit is contained in:
Hiren Kangad
2026-04-28 20:56:52 +05:30
parent 782d6df9e0
commit 2fb71b4ae1
8 changed files with 234 additions and 22 deletions
+46
View File
@@ -207,6 +207,50 @@ catch { db.exec('ALTER TABLE images ADD COLUMN page_count INTEGER'); }
try { db.prepare('SELECT priority FROM media_jobs LIMIT 0').get(); }
catch { db.exec('ALTER TABLE media_jobs ADD COLUMN priority INTEGER DEFAULT 0'); }
// ---------------------
// Settings (runtime-tunable key/value pairs)
// ---------------------
db.exec(`
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
`);
function getSetting(key) {
const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(key);
return row ? row.value : null;
}
function setSetting(key, value) {
db.prepare(`
INSERT INTO settings (key, value, updated_at)
VALUES (?, ?, datetime('now'))
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = datetime('now')
`).run(key, String(value));
}
function getAllSettings() {
return db.prepare('SELECT key, value, updated_at FROM settings').all();
}
function getBoolSetting(key, defaultValue = false) {
const v = getSetting(key);
if (v === null) return defaultValue;
return v === 'true' || v === '1';
}
// First-boot: seed allow_self_registration from env var if it has never been
// stored. After first boot, the env var is ignored — admins control it from
// the dashboard.
(function seedSettingsFromEnv() {
if (getSetting('allow_self_registration') === null) {
const envValue = (process.env.ALLOW_SELF_REGISTRATION || '').toLowerCase() === 'true';
setSetting('allow_self_registration', envValue ? 'true' : 'false');
}
})();
// ---------------------
// User helpers
// ---------------------
@@ -701,6 +745,8 @@ module.exports = {
incrementThreadCommentCount, decrementThreadCommentCount,
// Comments
getCommentsByThread, getCommentsByBoard, getComment, createComment, updateComment, deleteComment,
// Settings
getSetting, setSetting, getAllSettings, getBoolSetting,
// Bootstrap
seedAdminFromEnv,
};
+57
View File
@@ -15,12 +15,69 @@ const {
updateCollection,
addCollectionMember,
createBoard,
getAllSettings,
setSetting,
getBoolSetting,
} = require('../db');
const router = Router();
router.use(adminOrApiKeyMiddleware);
// ---- Settings ----
const KNOWN_SETTINGS = {
allow_self_registration: { type: 'bool', default: false },
};
router.get('/settings', (_req, res) => {
try {
const stored = getAllSettings();
const map = Object.fromEntries(stored.map((s) => [s.key, s]));
const out = {};
for (const [key, def] of Object.entries(KNOWN_SETTINGS)) {
const row = map[key];
let value;
if (def.type === 'bool') {
value = row ? row.value === 'true' || row.value === '1' : def.default;
} else {
value = row ? row.value : def.default;
}
out[key] = { value, updated_at: row?.updated_at || null, type: def.type };
}
return res.json({ settings: out });
} catch (err) {
console.error('[admin] get settings error:', err);
return res.status(500).json({ error: 'Internal server error' });
}
});
router.put('/settings/:key', (req, res) => {
try {
const { key } = req.params;
const def = KNOWN_SETTINGS[key];
if (!def) {
return res.status(404).json({ error: `Unknown setting: ${key}` });
}
const raw = req.body?.value;
if (raw === undefined || raw === null) {
return res.status(400).json({ error: 'Missing "value" in request body' });
}
let stringValue;
if (def.type === 'bool') {
const b = raw === true || raw === 'true' || raw === 1 || raw === '1';
stringValue = b ? 'true' : 'false';
} else {
stringValue = String(raw);
}
setSetting(key, stringValue);
return res.json({ key, value: def.type === 'bool' ? stringValue === 'true' : stringValue });
} catch (err) {
console.error('[admin] set setting error:', err);
return res.status(500).json({ error: 'Internal server error' });
}
});
// ---- User management ----
router.post('/users', async (req, res) => {
+20 -1
View File
@@ -6,6 +6,7 @@ const {
createUser,
getUserById,
getUserCount,
getBoolSetting,
} = require('../db');
const {
hashPassword,
@@ -16,6 +17,24 @@ const {
const router = Router();
/**
* GET /api/auth/config
* Public, no auth — used by the Login page to decide whether to show the
* "Register" link. Only exposes booleans the UI needs; no internals.
*/
router.get('/config', (_req, res) => {
try {
const userCount = getUserCount();
return res.json({
allowSelfRegistration: getBoolSetting('allow_self_registration', false),
hasUsers: userCount > 0,
});
} catch (err) {
console.error('[auth] config error:', err);
return res.status(500).json({ error: 'Internal server error' });
}
});
/**
* POST /api/auth/register
* Create a new user. The first user automatically becomes admin.
@@ -32,8 +51,8 @@ router.post('/register', async (req, res) => {
return res.status(400).json({ error: 'Password must be at least 6 characters' });
}
const allowRegistration = (process.env.ALLOW_SELF_REGISTRATION || '').toLowerCase() === 'true';
const userCount = getUserCount();
const allowRegistration = getBoolSetting('allow_self_registration', false);
if (!allowRegistration && userCount > 0) {
return res.status(403).json({
error: 'Self-registration is disabled. Ask an admin to create your account.',