Middleware & Session Management

The DatabaseSessionMiddleware is the core security component that executes on every request.

Middleware Logic

  1. Extracts and decodes the JWT session token from the cookie or Bearer header.
  2. Periodically fetches the full session record from the database to ensure it's still active.
  3. Performs Session Hijack Detection by comparing the request's device and region with the session record. If they don't match, the session is invalidated.
  4. Rotates a per-request token (random_string) within the session to mitigate replay attacks.
  5. Injects user_id and session_id into request.state for dependencies.