The seeded role is SuperAdmin, but the middleware only matched superAdmin, so SuperAdmin could be denied documents and other new permissions.
36 lines
924 B
JavaScript
36 lines
924 B
JavaScript
// /middlewares/permissionMiddleware.js
|
|
|
|
const AppError = require('../utils/AppError');
|
|
|
|
const requirePermission = (requiredPermission) => {
|
|
return (req, res, next) => {
|
|
try {
|
|
if (!req.user) {
|
|
return next(new AppError('UNAUTHORIZED'));
|
|
}
|
|
|
|
const role = req.user.role;
|
|
if (!role) {
|
|
return next(new AppError('FORBIDDEN'));
|
|
}
|
|
|
|
const roleName = String(role.name || '').toLowerCase();
|
|
if (roleName === 'superadmin' || (role.isSystem && role.permissions.includes('*'))) {
|
|
return next();
|
|
}
|
|
|
|
// Check if required permission is held by role
|
|
if (Array.isArray(role.permissions) && role.permissions.includes(requiredPermission)) {
|
|
return next();
|
|
}
|
|
|
|
return next(new AppError('FORBIDDEN'));
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
};
|
|
};
|
|
|
|
module.exports = requirePermission;
|
|
module.exports.requires = requirePermission;
|