Skip to main content

Overview

The Horse Trust backend uses several middleware functions for authentication, authorization, and request validation.

Authentication Middleware

authenticate

Verifies JWT tokens in the Authorization header.
Reference: middleware/auth.ts:6-23 Usage:
Expected Header Format:
Response on Failure:
or

Authorization Middleware

requireAdmin

Ensures the authenticated user has admin role.
Reference: middleware/auth.ts:26-32 Usage:
Response on Failure:

requireSeller

Allows access to users with seller or admin role.
Reference: middleware/auth.ts:35-41 Usage:
Response on Failure:

optionalAuth

Attempts to authenticate but allows the request to proceed even if no token is provided. Useful for public routes that can benefit from user context.
Reference: middleware/auth.ts:44-55 Usage:

Middleware Chain Examples

Admin-Only Route

Seller Route (Seller or Admin)

Public Route with Optional Auth

Auth-Protected Route

AuthRequest Type

The middleware extends Express’s Request type with user information:

Rate Limiting Middleware

Defined in app.ts, two rate limiters are configured:

Global Rate Limiter

Applies to all routes:
Reference: app.ts:37-44

Auth Rate Limiter

Stricter limits for authentication endpoints:
Reference: app.ts:47-51

Validation Middleware

Validation errors are caught globally:
Reference: app.ts:55-62 Example Error Response: