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

    Function authenticateToken

    • JWT Authentication Middleware

      Verifies JWT access tokens and attaches authenticated user information to the Express request object. This middleware extracts Bearer tokens from the Authorization header, validates them against the JWT secret, and populates req.user with the decoded payload.

      The middleware handles various JWT validation scenarios including missing tokens, invalid tokens, expired tokens, and configuration errors. All authentication failures are logged for security monitoring and result in appropriate HTTP error responses.

      This middleware is used extensively across protected routes in authentication, user management, and content management endpoints. It serves as the foundation for all authenticated operations in the application.

      Parameters

      • req: Request

        Express request object containing Authorization header

      • _res: Response

        Express response object (unused)

      • next: NextFunction

        Express next function to continue middleware chain

      Returns Promise<void>

      Promise that resolves when authentication is complete

      UNAUTHORIZED (401) - When token is missing, invalid, or expired

      INTERNAL_SERVER_ERROR (500) - When JWT_SECRET is not configured

      // Protect user profile endpoint
      router.get('/profile', authenticateToken, userController.getProfile);
      // Protect logout endpoint
      router.post('/logout', authenticateToken, authController.logout);
      // Chain with other middleware for complex authorization
      router.put('/users/:id/role',
      authenticateToken,
      requireRole('admin'),
      userController.updateUserRole
      );
      // Access user information in route handler
      const protectedHandler = (req: Request, res: Response) => {
      const userId = req.user?.sub; // Available after authenticateToken
      const userRole = req.user?.role;
      // ... handle authenticated request
      };