Single role or array of roles that can access the endpoint
Express middleware function that validates user roles
// Admin-only endpoint
router.get('/users',
authenticateToken,
requireRole('admin'),
userController.getAllUsers
);
// Multiple roles allowed for content creation
router.post('/courses',
authenticateToken,
requireRole(['admin', 'content_creator']),
contentController.createCourse
);
Role-Based Access Control Middleware Factory
Creates middleware that enforces role-based access control by validating that the authenticated user has one of the required roles. This middleware must be used after authenticateToken as it depends on req.user being populated with user information.
The middleware supports both single role and multiple role authorization patterns, allowing flexible access control for different endpoint requirements. Failed authorization attempts are logged with user and role information for security auditing.
This middleware is used extensively in admin-only endpoints and content management routes where different user roles have different levels of access to functionality.