Skip to content

Middleware

The CPR backend uses custom middleware for branch isolation, rate limiting, and request processing.

Custom Middleware

EnsureBranchContext

The most important custom middleware — enforces multi-branch data isolation on branch-scoped routes.

Location: app/Http/Middleware/EnsureBranchContext.php

What it does:

  1. Resolves the branch ID from (in priority order):
    • X-Branch-Id HTTP header
    • branch_id query parameter
    • User's default_branch_id
  2. Validates the branch exists
  3. Validates the user has access to that branch (via branch_users pivot)
  4. Sets current_branch_id on the request for downstream use

Error responses:

ScenarioStatusMessage
No branch context provided400Branch context required
User doesn't have access to branch403Access denied to this branch

Applied to: All branch-scoped routes (patients, visits, exams, queue, billing, dashboard).

Usage in routes:

php
Route::middleware(['auth:sanctum', 'branch.context'])->group(function () {
    Route::apiResource('patients', PatientController::class);
    Route::apiResource('patient-visits', PatientVisitController::class);
    // ... all branch-scoped routes
});

Client usage:

http
GET /api/v1/patients
Authorization: Bearer {token}
X-Branch-Id: 1

HandleAppearance

Reads the appearance cookie (theme preference) and shares it with views.

  • Default: 'system'
  • Shares via View::share('appearance', $value)

HandleInertiaRequests

Inertia.js middleware for the web frontend:

  • Sets root view to 'app'
  • Shares common props: app name, auth user, sidebar state
  • Reads sidebar state from cookie

Framework Middleware

The application also uses these Laravel/Sanctum middleware:

MiddlewareAliasPurpose
auth:sanctum-Authenticates Bearer token
throttle:api-Rate limit: 1000 req/min per user
throttle:authentication-Rate limit: 5 req/min per IP
throttle:public-Rate limit: 5 req/min per IP
permission:{name}-Spatie permission check (e.g., permission:admin.access)

Middleware Stack per Route Type

Public Routes

throttle:public

Authentication Routes

throttle:authentication

Standard API Routes

throttle:api → auth:sanctum

Branch-Scoped Routes

throttle:api → auth:sanctum → branch.context

Admin Routes

throttle:api → auth:sanctum → permission:admin.access

Rate Limiting Configuration

Rate limits are defined in AppServiceProvider::configureRateLimiting():

php
RateLimiter::for('api', function (Request $request) {
    return Limit::perMinute(1000)
        ->by($request->user()?->id ?: $request->ip());
});

RateLimiter::for('authentication', function (Request $request) {
    return Limit::perMinute(5)->by($request->ip());
});

RateLimiter::for('public', function (Request $request) {
    return Limit::perMinute(5)->by($request->ip());
});

CPR - Clinical Patient Records