Appearance
Middleware ​
Overview ​
app/Http/Middleware holds 25 classes. They are wired in app/Http/Kernel.php (Laravel 11 framework, older skeleton): seven run globally, some belong to the web and api groups, and the rest are route aliases used in routes/*.php. No controller calls $this->middleware(), so the route files are the only place route middleware is attached.
Most custom guards answer with RestResponse::warning($message, $code), which returns {"status": false, "code": <code>, "message": ...} with the HTTP status equal to code. The workspace guards use the non-standard status 420.
For the order in which global and group middleware run, see Architecture.
Global and group middleware ​
| Class | Where | What it does |
|---|---|---|
TrustProxies | Global | Trusts X-Forwarded-For, -Host, -Port, -Proto and AWS ELB headers. $proxies is not set. |
CheckForMaintenanceMode | Global | Extends the framework maintenance check; no exceptions. |
PreventRequestsDuringMaintenance | Global | Framework maintenance check; no exceptions. |
TrimStrings | Global | Trims input except password and password_confirmation. |
TrustHosts | Not registered (commented out in the global stack) | Would trust all subdomains of the app URL. |
EncryptCookies | web group | Encrypts cookies; no exceptions. |
VerifyCsrfToken | web group | CSRF check, except filepreviews/webhook. |
LogApiRequests | api group (first) | When bigquerylog.enabled is true: assigns a request id, counts DB queries and time, adds X-Request-Id to the response, and in terminate() writes an api_requests row through Spooler. Skips bigquerylog.excluded_paths. Resolves the workspace from bq_workspace_id, the dam_instance attribute set by DAMAPIMiddleware, dam_workspace_id, or the url_workspace_id / workspace_id slug. Failures are logged as warnings and never change the response. |
Route middleware aliases ​
From App\Http\Kernel::$routeMiddleware. "Applied in" comes from searching routes/.
| Alias | Class | Applied in |
|---|---|---|
auth | App\Http\Middleware\Authenticate | auth:api (api.php), auth:dam-api (dam-api.php), auth:external-api (external-api.php) |
auth.basic | Illuminate\Auth\Middleware\AuthenticateWithBasicAuth | Not used |
auth.session | Illuminate\Session\Middleware\AuthenticateSession | Not used |
cache.headers | Illuminate\Http\Middleware\SetCacheHeaders | Not used |
can | Illuminate\Auth\Middleware\Authorize | Not used |
guest | App\Http\Middleware\RedirectIfAuthenticated | Not used |
password.confirm | Illuminate\Auth\Middleware\RequirePassword | Not used |
signed | Illuminate\Routing\Middleware\ValidateSignature | Not used |
throttle | Illuminate\Routing\Middleware\ThrottleRequests | throttle:600,1 on the authenticated groups of api.php, dam-api.php, external-api.php and the /admin group of web.php; throttle:10,1 on POST status/check; throttle:verify-token (named limiter, 1200/min per token) on GET api/v1/auth/verify, which also drops the group's throttle:api with withoutMiddleware; throttle:reauth (named limiter, 5/min per user id, IP when signed out) on passkeys/register/options, DELETE passkeys/{id} and user/auth-change-password; throttle:20,1 on auth/social/exchange; throttle:10,1,sso-domain-verify on sso/domains/verify; throttle:30,1 on dam/v1/check-public-portal; throttle:3,10 on the dam-db-backup group (all added in PR #453) |
verified | Illuminate\Auth\Middleware\EnsureEmailIsVerified | Not used |
social | SocialMiddleware | api.php: auth/login/{service} and its callback |
checkUserWithWS | VerifyUserWithWorkSpace | api.php: the workspace group (workspace settings, sso, user, external-user, announcement) and the digital-assets group |
checkWorkspaceOwner | VerifyWorkspaceOwner | api.php: sso group (connection, sync, test, activity, domains, domains/verify, domains/remove) |
checkSsoAllowed | VerifyWorkspaceSsoAllowed | api.php: sso group |
checkMobileUserWithWS | VerifyPMMobileUserWithWorkSpace | Not used in any route file |
checkStorageLimit | DAMStorageLimit | Not used in any route file |
dam-api | DAMAPIMiddleware | dam-api.php: the authenticated group |
external-api | ExternalAPIMiddleware | external-api.php: the authenticated group |
CheckETag | CheckETag | Not used |
IfNoneMatchEtag | IfNoneMatchEtag | api.php digital-assets group; dam-api.php authenticated group |
setEtag | SetETag | api.php digital-assets group; dam-api.php authenticated group |
check.external | CheckExternalUser | api.php: check-external-access, get-external-user, external-upload, submit-request, external-logout, upload-zip-preview |
auth.user-or-external | AuthenticateUserOrExternalToken | api.php: GET auth/verify (added in commit 6ac8a4f) |
adminSession | VerifyAdminSession | web.php: the whole /admin group except five routes that opt out with withoutMiddleware, and the dam-db-backup group (added in PR #453) |
dam.viewer-timezone | ConvertDatesToViewerTimezone | dam-api.php: the public share-link group (show-share-assets, view-share-files-with-category, get-count/{categoryId}, search-share-data) and the authenticated group, listed last (added in 6c70cbc) |
ApplyWorkspaceMailConfig exists but has no alias and is not referenced anywhere. Per-workspace mail settings are applied instead by the ApplyWorkspaceMailToMessage listener on MessageSending (see Events).
Class reference ​
Authenticate ​
Extends the framework Authenticate. redirectTo() returns route('login') only for non-JSON requests. unauthenticated() always aborts with {"error": "Unauthenticated."} and status 401, after logging why: no bearer token, token is not a parseable JWT, jti not found in oauth_access_tokens (deleted, or a lagging replica), token revoked, token expired, OAuth client revoked, or, when the token is valid in the database, a signature failure (check that storage/oauth-public.key matches the private key). The logging is wrapped in try/catch so it never changes the 401.
RedirectIfAuthenticated ​
If Auth::guard($guard)->check() passes, redirects to RouteServiceProvider::HOME (/home). Registered as guest but unused.
VerifyUserWithWorkSpace (checkUserWithWS) ​
Runs after auth:api. Reads url_workspace_id (a workspace url_slug) from the request. Every failure below returns 420 "You are not authorized person to access this Workspace.". Checks, in order (PR #453):
url_workspace_idorworkspace_idis an array: 420. (Before, an array skipped every check.)- The workspace with that
url_slugexists. - The user has an active
workspace_usersrow for it (workspace_status = 1); deactivated members are now refused. - When
workspace_idis present and names a different slug thanurl_workspace_id, the user must also be an active member of that workspace, because controllers act onworkspace_id.
It then calls App\Services\Sso\SsoEntryCheck::response(), which enforces the SSO re-check from saml.recheck_days.
SsoEntryCheck lets the request through when the workspace has no enabled SSO connection, when the user has no SSO identity for it, or on any internal error. It returns 403 while last_recheck_failed_at is within saml.recheck_failure_hold_minutes, and 428 with a redirect URL through the IdP when the re-check is due.
VerifyPMMobileUserWithWorkSpace (checkMobileUserWithWS) ​
Same workspace membership check as VerifyUserWithWorkSpace, but reads workspace_id instead of url_workspace_id and has no SSO check. Not used by any route file.
VerifyWorkspaceOwner (checkWorkspaceOwner) ​
Takes the slug from url_workspace_id or workspace_id. Returns 420 when there is no user, no slug, the slug is an array, or the workspace does not exist. Returns 403 "Only the workspace owner can manage Single Sign-On." when workspaces.user_id is not the current user.
VerifyWorkspaceSsoAllowed (checkSsoAllowed) ​
Takes the same slug. Returns 420 when it is missing or an array, and 403 with VerifyWorkspaceSsoAllowed::MESSAGE ("Single Sign-On is not enabled for this workspace. Contact Collage support to switch it on.") when the workspace's sso_enabled is falsy.
DAMAPIMiddleware (dam-api) ​
Guards the brand portal API after auth:dam-api. The token must belong to the dam-api guard and be named DAM Api Token. If an instance id is present (instance_id input, then the X-Instance-Id header, then the user's instance_id), the portal must be active and the user must be an active member of it. Backend portal users (is_backend_user) need a dam_instances_users row too (they get one from login-with-id). When the request carries a non-empty workspace_id, it must be this portal's workspace (its url_slug or numeric id), otherwise 403 You do not have access to this instance., because controllers read the workspace from the request. On success it merges dam_instance_id and dam_workspace_id into the request and stores the DamInstance in the dam_instance request attribute for controllers and LogApiRequests.
ExternalAPIMiddleware (external-api) ​
Continues only when Auth::guard('external-api')->check() passes and the token name is External Api Token. Otherwise it returns {"status": false, "code": 403, "message": "Access denied."} with HTTP status 400.
CheckExternalUser (check.external) ​
Reads the user from the external-user guard. No user: 401 {"error": "Unauthenticated."}. User with is_active false: 403 {"error": "Your account is inactive."}. A workspace mismatch check is present but commented out.
AuthenticateUserOrExternalToken (auth.user-or-external) ​
Added in commit 6ac8a4f for GET /api/v1/auth/verify. Accepts a Passport bearer token issued either to a User (guard api) or to an ExternalUser (guard external-user), and makes the matching guard the default so $request->user() returns the right model.
Steps, in order (any failure returns 401 {"error": "Unauthenticated."}):
- Read the bearer token. None: 401.
- Split the JWT into 3 parts and base64url-decode the payload without verifying it; take
jti(must be a non-empty string). - Look up
oauth_access_tokensby primary keyjti(columnsid,name,revoked). Missing or revoked: 401. - Pick the guard from the token name:
external-token(EXTERNAL_TOKEN_NAME) usesexternal-user;Api TokenorSSO Token(USER_TOKEN_NAMES) usesapi. Any other name (for exampleDAM Api Token,External Api Token): 401. Auth::guard($guard)->user()runs Passport's real signature, expiry and revocation check. No user: 401. An external user withis_activefalse: 401 (not the 403 thatcheck.externalreturns).Auth::shouldUse($guard)and the request attributeauth_guard=apiorexternal-user.
The reason, from the class docblock: every token comes from the one personal access client, whose provider is NULL, so auth:api,external-user would let an external token with user_id = 7 authenticate as users.id = 7. Choosing the guard by token name prevents that. The flow diagram is on Admin API routes.
VerifyAdminSession (adminSession) ​
Added in PR #453 for the internal super-admin panel in routes/web.php. Passes when session('is_logged_in') is set (stored by AdminController::authenticate). Otherwise a request that expects JSON, or an AJAX request, gets 401 {"message":"Unauthenticated"} and any other request is redirected to /admin/login. Excluded routes: GET and POST /admin/login, GET /admin/subscription/checkout-session-complete, GET /admin/subscription/customer-invoice-paid, GET /admin/subscription/payment-success/{id}. See Web routes.
ConvertDatesToViewerTimezone (dam.viewer-timezone) ​
Added in 6c70cbc for the Portal API (routes/dam-api.php). It rewrites every datetime in a JSON response into the viewer's timezone, taken from the X-Timezone header the Brand Portal sends on every browser request (ResolvesViewerTimezone::VIEWER_TIMEZONE_HEADER). Partner users (dealer_users) have no profile timezone, so without a valid header the response is returned untouched: nothing is guessed.
The header goes through App\Support\TimezoneName::canonical(), which maps 148 legacy IANA aliases from the backward file to their current names (for example Asia/Calcutta to Asia/Kolkata, America/Indianapolis to America/Indiana/Indianapolis) and returns null for anything PHP cannot load. Chrome still sends some legacy names, and Ubuntu 24.04 moved them into the optional tzdata-legacy package. ResolvesViewerTimezone and the dashboard, portal and feedback date formatting use the same helper and fall back to UTC.
It runs after the controller (it calls $next first) and is listed last in the authenticated group (auth:dam-api, dam-api, throttle:600,1, setEtag, IfNoneMatchEtag, dam.viewer-timezone). Being innermost, it rewrites the body before the ETag middlewares hash it, so ETag and 304 match the converted body.
A value is converted only when all of these hold:
| Rule | Detail |
|---|---|
| It is a string under a date-looking key | Key matches /(_at|dates?|times?|_on|login|activity|expir[a-z]*|timestamps?)$/i, for example created_at, modified_at, last_login, trial_end_date, expiration. Items of a list inherit the parent key, so a list of timestamps under a date key is converted too. |
| It has a time of day | Matches Y-m-d H:i[:s[.u]] or ISO 8601, optionally with Z or an offset. Date-only values (2026-11-04), unix timestamps and relative strings are left alone. |
| It is not a zero date | Values starting with 0000- are skipped. |
Conversion uses toViewerIso(): naive values (uncast columns) are read in config('app.timezone'), zoned values keep their zone, and the output is ISO 8601 with offset.
text
X-Timezone: America/Denver, APP_TIMEZONE Asia/Kolkata
"modified_at": "2026-11-05 02:30:00" -> "2026-11-04T14:00:00-07:00"
"created_at": "2026-11-04T21:00:00.000000Z" -> "2026-11-04T14:00:00-07:00"
"expiration": "2026-11-20" -> unchanged (no time of day)DAMStorageLimit (checkStorageLimit) ​
Only acts when the request has url_workspace_id. It sums AssetsVersion.file_size for the workspace where final_deleted = 0, reads features.storage.default_value from the workspace's SubscriptionUsers row and formats it with DamInstance::formatSubscriptionStorage(). When storage is not unlimited it computes a percentage and returns RestResponse::warning('You storage limit is over for this workspace.', 201) if $totalSize > $percentage. Note that the code compares the byte total with the percentage value, not the percentage with 100. Finally it calls DamInstance::damStorageLimitCheck(), which resets the 50 / 75 / 95 / 100 percent storage mail flags in storage_mail_status as usage drops. The alias is not attached to any route at this commit.
When storage is unlimited, the middleware skips the comparison and goes straight to damStorageLimitCheck().
SocialMiddleware (social) ​
Builds the list of enabled services from google, facebook, microsoft, keeping those with a services.<name> config entry. If the {service} route parameter is not in that list it returns 403 {"success": false, "message": "Invalid Social Service"} for JSON requests, or redirects back otherwise. config/services.php defines google and microsoft but not facebook.
ETag middleware ​
| Class | Behaviour |
|---|---|
SetETag (setEtag) | After the response is built, sets ETag to md5 of the response body. |
IfNoneMatchEtag (IfNoneMatchEtag) | Treats HEAD as GET, builds the response, computes md5 of the body and calls setNotModified() when it matches one of the request's If-None-Match values. Restores the original method. |
CheckETag (CheckETag) | Same HEAD handling as IfNoneMatchEtag and sets the ETag, but never returns 304. Not used. |
The digital-assets group in api.php and the authenticated dam-api.php group use setEtag and IfNoneMatchEtag together, so clients that send If-None-Match get 304 for unchanged JSON. In the dam-api.php group dam.viewer-timezone runs inside them, so the hash is taken over the timezone-converted body and the response carries Vary: X-Timezone.
ApplyWorkspaceMailConfig ​
Resolves a workspace from the workspace_id route parameter, input or X-Workspace-Id header (slug first, then numeric id), falling back to the user's default_workspace. Calls WorkspaceMailContext::setForWorkspace() and WorkspaceMailService::applyForWorkspace(). Not registered.