Add JWT issue/verify and auth middleware

This commit is contained in:
2026-06-03 09:49:47 +10:00
parent 0c88aa16ea
commit d770621ec8
+26
View File
@@ -0,0 +1,26 @@
import jwt from "jsonwebtoken";
const SECRET = process.env.JWT_SECRET;
if (!SECRET) {
console.error("FATAL: JWT_SECRET is not set. Create a .env file (see .env.example).");
process.exit(1);
}
const TOKEN_TTL = "8h";
export function issueToken(admin) {
return jwt.sign({ sub: admin.id, username: admin.username }, SECRET, { expiresIn: TOKEN_TTL });
}
// Express middleware: requires a valid Bearer token
export function requireAuth(req, res, next) {
const header = req.get("authorization") || "";
const match = header.match(/^Bearer (.+)$/i);
if (!match) return res.status(401).json({ error: "Missing token" });
try {
req.admin = jwt.verify(match[1], SECRET);
next();
} catch {
return res.status(401).json({ error: "Invalid or expired token" });
}
}