2025-12-19 20:44:46 -06:00
|
|
|
const logger = require("../config/logger");
|
|
|
|
|
const { sendUnauthorized, sendForbidden } = require("../utils/responseHelpers");
|
|
|
|
|
|
|
|
|
|
const isAuthenticated = (req) => {
|
|
|
|
|
return req.session?.user?.id;
|
|
|
|
|
};
|
|
|
|
|
|
2025-12-13 17:53:34 -06:00
|
|
|
const requireAuth = (req, res, next) => {
|
2025-12-19 20:44:46 -06:00
|
|
|
if (isAuthenticated(req)) {
|
2025-12-13 17:53:34 -06:00
|
|
|
return next();
|
|
|
|
|
}
|
2025-12-19 20:44:46 -06:00
|
|
|
|
|
|
|
|
logger.warn("Unauthorized access attempt", {
|
|
|
|
|
path: req.path,
|
|
|
|
|
ip: req.ip,
|
|
|
|
|
});
|
|
|
|
|
sendUnauthorized(res);
|
2025-12-13 17:53:34 -06:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const requireRole = (allowedRoles) => {
|
2025-12-13 22:34:11 -06:00
|
|
|
const roles = Array.isArray(allowedRoles) ? allowedRoles : [allowedRoles];
|
|
|
|
|
|
2025-12-13 17:53:34 -06:00
|
|
|
return (req, res, next) => {
|
2025-12-19 20:44:46 -06:00
|
|
|
if (!isAuthenticated(req)) {
|
|
|
|
|
logger.warn("Unauthorized access attempt", {
|
|
|
|
|
path: req.path,
|
|
|
|
|
ip: req.ip,
|
|
|
|
|
});
|
|
|
|
|
return sendUnauthorized(res);
|
2025-12-13 17:53:34 -06:00
|
|
|
}
|
2025-12-13 22:34:11 -06:00
|
|
|
|
|
|
|
|
const userRole = req.session.user.role_id || "role-admin";
|
|
|
|
|
|
|
|
|
|
if (roles.includes(userRole)) {
|
2025-12-13 17:53:34 -06:00
|
|
|
return next();
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-19 20:44:46 -06:00
|
|
|
logger.warn("Forbidden access attempt", {
|
|
|
|
|
path: req.path,
|
|
|
|
|
ip: req.ip,
|
|
|
|
|
userRole,
|
|
|
|
|
requiredRoles: roles,
|
2025-12-13 22:34:11 -06:00
|
|
|
});
|
2025-12-19 20:44:46 -06:00
|
|
|
|
|
|
|
|
sendForbidden(res, "Access denied. Insufficient permissions.");
|
2025-12-13 22:34:11 -06:00
|
|
|
};
|
2025-12-13 17:53:34 -06:00
|
|
|
};
|
|
|
|
|
|
2025-12-13 22:34:11 -06:00
|
|
|
module.exports = { requireAuth, requireRole };
|