UNPKG

create-auth-backend-cli

Version:

CLI to scaffold a Node.js Auth backend with Express, JWT, MongoDB

36 lines (28 loc) 1.14 kB
const jwt = require("jsonwebtoken"); /** * Middleware to verify JWT and optionally check user role * @param {Array<string>} allowedRoles - optional array of allowed roles */ const authMiddleware = (allowedRoles = []) => { return (req, res, next) => { const authHeader = req.headers.authorization; // 1. Check if header exists and starts with Bearer if (!authHeader || !authHeader.startsWith("Bearer ")) { return res.status(401).json({ error: "Authorization header missing or invalid" }); } const token = authHeader.split(" ")[1]; try { // 2. Verify token const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = decoded; // { id, role, iat, exp } // 3. Role-based access control (optional) if (allowedRoles.length > 0 && !allowedRoles.includes(decoded.role)) { return res.status(403).json({ error: "Access denied: insufficient permissions" }); } next(); } catch (err) { return res.status(401).json({ error: "Invalid or expired token" }); } }; }; module.exports = authMiddleware;