Add JWT issue/verify and auth middleware
This commit is contained in:
@@ -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" });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user