Files
Church-Music/new-site/backend/middleware/auth.js

53 lines
1.2 KiB
JavaScript
Raw Normal View History

2026-01-27 18:04:50 -06:00
const jwt = require("jsonwebtoken");
const authenticate = (req, res, next) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return res.status(401).json({ error: "No token provided" });
}
const token = authHeader.split(" ")[1];
const decoded = jwt.verify(
token,
process.env.JWT_SECRET || "your-super-secret-jwt-key",
);
req.user = decoded;
next();
} catch (error) {
if (error.name === "TokenExpiredError") {
return res.status(401).json({ error: "Token expired" });
}
return res.status(401).json({ error: "Invalid token" });
}
};
const authorize = (...roles) => {
return (req, res, next) => {
if (!req.user) {
return res.status(401).json({ error: "Not authenticated" });
}
if (!roles.includes(req.user.role)) {
return res.status(403).json({ error: "Not authorized" });
}
next();
};
};
const isAdmin = (req, res, next) => {
if (!req.user || req.user.role !== "admin") {
return res.status(403).json({ error: "Admin access required" });
}
next();
};
module.exports = {
authenticate,
authorize,
isAdmin,
};