WayrApp Backend & Ecosystem Documentation - v1.0.0
    Preparing search index...

    Function requireRole

    • 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.

      Parameters

      • allowedRoles: UserRole | UserRole[]

        Single role or array of roles that can access the endpoint

      Returns (req: Request, _res: Response, next: NextFunction) => void

      Express middleware function that validates user roles

      UNAUTHORIZED (401) - When user is not authenticated

      FORBIDDEN (403) - When user role is not in allowed 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
      );
      // Content creator and admin can update content
      router.put('/courses/:id',
      authenticateToken,
      requireRole(['admin', 'content_creator']),
      contentController.updateCourse
      );
      // Role hierarchy in practice
      // student: basic access
      // content_creator: can create/edit content
      // admin: full system access
      router.delete('/courses/:id',
      authenticateToken,
      requireRole('admin'), // Only admins can delete
      contentController.deleteCourse
      );