Skip to main content

Authentication & SSO

ContentsVision does not manage passwords. It trusts AdjustSquare as the identity provider: AdjustSquare issues a signed JWT, ContentsVision validates it, and on first sight it auto-creates the matching team and user. Everything else in the app is scoped to that team.

The login flow​

  1. An unauthenticated user is redirected to the AdjustSquare login page (adjustsquare_login_url) with a return_to pointing back at the ContentsVision callback. The frontend can fetch this URL from the public GET /api/auth/config.
  2. After login, AdjustSquare redirects back to /auth/callback?token=<JWT>.
  3. The callback page (app/auth/callback/page.tsx) calls GET /api/auth/me with the token as a bearer header.
  4. The backend validates the JWT and provisions the team and user.
  5. The frontend stores the token and user in localStorage and navigates to the dashboard.

GET /api/auth/me returns more than identity: is_admin, the user's timezone, the team's resolved component visibility (features, see component_visibility), and the user's effective access profile (permissions, access_profile, access_profile_name). features.training is forced on whenever the user has any training assigned, so a user can never be locked out by training they cannot reach. PUT /api/auth/me updates the caller's display preferences (today only timezone, an IANA name or "" for the browser's local time). GET /api/auth/debug is a local-development view of the resolved user and team, the raw JWT claims, and the auth mode, with the team token masked.

Local auth bypass (development only)​

When APP_ENV=local (the default) and LOCAL_AUTH_USER_EMAIL is set, get_current_user skips the JWT entirely and signs every request in as that email. Adjust Square sign-in only redirects to the real sites, so without this a local checkout could never log in. If the user is not in the local database yet (each git worktree has its own empty SQLite file), it is created on first request on an "Adjust Square (Local Dev)" team. The optional LOCAL_AUTH_USER_EXTERNAL_ID is stamped on that user; set it to an id on ADMIN_EXTERNAL_USER_IDS to get the admin pages locally. Both can live once per machine in ~/.contentsvision/local.env (see signing in locally).

GET /api/auth/config reports local_bypass: true in that mode, and the login page then goes straight to the dashboard instead of offering a sign-in that cannot work. Any other APP_ENV (staging, production) ignores LOCAL_AUTH_USER_EMAIL. An instance that forgets APP_ENV runs in local mode, which alone does not open it, but never set LOCAL_AUTH_USER_EMAIL on a deployed instance.

How the token reaches the backend​

The get_current_user dependency (core/auth_deps.py) accepts the token two ways:

  1. Authorization: Bearer <jwt> header (the normal case; the API client always sends it).
  2. The bt_shared_data cookie (adjustsquare_cookie_name), for deployments hosted on the same .adjustsquare.com subdomain where AdjustSquare already set the cookie.

If neither is present, the request gets 401.

Validating the JWT​

core/security.py decodes the token with python-jose using HS256 and the shared secret ADJUSTSQUARE_JWT_SECRET. Audience and subject verification are disabled (AdjustSquare sets sub as an integer, and the user id is read from the payload directly). Missing required claims raise a clear error, which the route turns into 401.

The JWT claims​

decode_token returns an AdjustSquareClaims with these fields:

ClaimMaps toNotes
user_idUser.external_idRequired. A string (Contents Estimation, now the login source of truth, issues its user UUID; a legacy Adjust Square integer is normalized to its string form). Forwarded to Adjust Square as the integer adjuster_id only when it is a legacy integer id; a UUID user omits it (AS uses the team default adjuster).
user_nameUser.name
emailUser.emailUsed as a fallback identity key.
current_team_idTeam.external_idRequired. Still an integer (the Adjust Square team id; from CE's Team.legacy_id).
current_team_nameTeam.name
current_team_tokenTeam.team_tokenThe Adjust Square API token for this team.
current_team_ce_intake_keyTeam.contents_estimation_keyOptional, and empty today: the tokens are seeded directly instead (backend/scripts/seed_team_ce_tokens.py). When non-empty this claim OVERWRITES the stored token on every login, so shipping it with values that differ from the seeded ones would silently break the Contents Estimation push. That token is the only thing identifying the firm to Contents Estimation, and there is no fallback. See the Contents Estimation integration.

The token is minted by Contents Estimation (GET /sso/contentsvision/authorize), signed with a secret shared with ContentsVision (CE's CONTENTSVISION_SSO_SECRET == CV's ADJUSTSQUARE_JWT_SECRET). Point ADJUSTSQUARE_LOGIN_URL at CE to route logins through it; CV's /auth/callback exchanges the ?token= unchanged.

Auto-provisioning teams and users​

On every authenticated request, the backend ensures the team and user exist (auth_deps.py):

  • Team is looked up by the stable Adjust Square team id (Team.external_id, from current_team_id) first, then by team_token (the token can be empty or rotate, so it is only a fallback); if absent, created. When duplicates already exist the earliest row wins. On every login an existing team's name (if blank), team_token, and Contents Estimation key are refreshed from the JWT when they differ.
  • User is looked up by external_id first, then by email (a fallback for accounts created before external_id was tracked, or a legacy integer id moving to a Contents Estimation UUID); if absent, created on the team. A user matched by email has its external_id refreshed to the one in the token.
  • If a known user's team_id no longer matches (they moved teams in AdjustSquare), it is updated. This keeps team membership in sync on every login.

The provisioned User is what get_current_user returns; get_actor (core/actor.py) derives an Actor from it: user_id, user_name, team_id, plus is_admin, the effective access-profile permissions, visible_team_ids (organization visibility, below), and training_locked (overdue required training). Endpoints that only ever touch real claims (imports, integrations) use get_unlocked_actor, which refuses a training-locked user.

As a side effect, get_current_user also stamps users.last_seen_at (at most once a minute per user, best-effort). This powers the admin dashboard's "Active Users (live)" stat: a user counts as active if they made an authenticated request in the last 5 minutes.

Team scoping​

Because every claim carries a team_id, the API enforces isolation: a user can never see or touch another team's data. team_id is the application's security boundary (it is not a database foreign key, so it is enforced in code, not by the database).

Organization visibility: a user whose access profile holds claims.view_org also sees every team's claims in their organization. get_actor puts those teams on Actor.visible_team_ids and team_allowed accepts them, so the same 404/403 checks cover it. Without an organization, or without the permission, scoping is exactly the team as before.

Admin exception: allowlisted admins (Actor.is_admin, derived server-side from the same allowlist as require_admin) bypass team ownership checks on id-addressed resources (team_allowed in core/ownership.py), so an operator can open any team's claim, rooms, jobs, and items directly, e.g. following a link from the admin dashboard, Logs, or Media pages, without impersonating. List endpoints (dashboard claims, recent jobs) stay scoped to the admin's own team; the system-wide lists live under /api/admin/....

The ownership chain​

The tenant boundary is Claim.team_id. Everything else hangs off a claim, so ownership is resolved by walking up to the claim:

InventoryItem -> ProcessingJob -> Room -> Claim.team_id
ProcessingJob -> Room -> Claim.team_id
Room -> Claim.team_id

app/core/ownership.py provides the shared helpers load_claim_for_team, load_room_for_team, load_job_for_team, and load_item_for_team (plus claim_allowed(actor, claim) for an already-loaded claim, which also applies the training gate). Each loads a resource by id and verifies it belongs to the caller's team, raising 404 (not 403) for both a missing id and a cross-team id, so a response never reveals that another team's resource exists. Every id-taking endpoint (in jobs.py, inventory.py, rooms.py, upload.py, uploads.py, activity.py) funnels through one of these. The activity log is scoped by a team_id column on activity_log, set from the actor when each row is written.

The same module carries a second, unrelated gate: load_item_for_edit is load_item_for_team plus the Contents Estimation edit lock, returning 409 when that item has been sent to Contents Estimation on a claim an admin has not unlocked. Every endpoint that changes an existing item uses it in place of load_item_for_team; read-only endpoints, and creating a new item, do not. assert_job_items_editable applies the same rule to the bulk endpoint, which has no single item id.

Capability URLs (media bytes)​

A few endpoints serve raw bytes to elements that cannot send an Authorization header, so they are not team-checked and instead rely on the unguessable resource id (a UUID) as a capability:

EndpointLoaded byWhy it can't carry auth
GET /jobs/{id}/video, /audio<video> / <audio src>media elements send no headers
GET /jobs/{id}/frames/{name}<img src>image elements send no headers
GET /photos/{job_id}/{name}<img src> + the imgproxy CDNthe CDN fetches from a public origin
GET /jobs/{id}/stream (SSE)EventSourceEventSource sends no headers

The id is only discoverable through the team-scoped list endpoints, so cross-team access requires already knowing the UUID. Filenames on the byte-serving routes are traversal-checked (safe_path_segment) so they can't escape the job's directory. Inventory exports (Excel/CSV), by contrast, ARE team-scoped: the frontend downloads them with an authenticated fetch + blob (downloadExport) rather than a plain <a download> link.

Admin access (internal dashboard)​

The internal admin dashboard is the one place that deliberately ignores team scoping: it aggregates across every team. Access is restricted to an explicit allowlist of operators.

  • The allowlist lives in config as ADMIN_EXTERNAL_USER_IDS (a set of strings, defaults to {"7", "10"}, that is Dan and Nathan). These are identity-provider user IDs, stored on users.external_id, not the local users.id UUID. Values are strings so they match both a legacy Adjust Square integer id (as its string form) and a Contents Estimation user UUID; set them to the operators' current ids as login moves to Contents Estimation.
  • is_admin(user) (core/auth_deps.py) returns true when str(user.external_id) is in that set. Identity comes from the verified JWT, so a client cannot spoof it.
  • require_admin is a FastAPI dependency that depends on get_current_user and raises 403 "This page is restricted." for anyone not on the allowlist. Every /api/admin/... endpoint is guarded by it. This is the real gate; hiding the nav link is only cosmetic.
  • GET /api/auth/me surfaces is_admin: bool so the frontend can show the admin-only nav entries (Logs, Updates (the internal changelog), and Admin) only to admins, each marked with a small "Admin" badge in the sidebar. Those pages also guard themselves (page guard plus the API 403, belt and suspenders).

To change who has access, edit ADMIN_EXTERNAL_USER_IDS (see configuration); no code change is needed.

Impersonation​

Admins can view the app as any other user to debug their exact experience. From the admin dashboard's Impersonate a User picker, POST /api/admin/impersonate/{user_id} mints a short-lived AdjustSquare-format token for the target (signed with the same shared secret the app validates against, so it authenticates as that user) and returns it with the target's profile. lib/auth.tsx swaps the active token to the minted one while stashing the admin's own token, so every request now runs as the target; an app-wide amber banner shows who is being viewed and offers Stop impersonating, which restores the admin's session. The minted token carries an impersonated_by claim and the action is written to the activity log, so impersonation is always auditable. A user with no external_id cannot be impersonated (400; the token needs an identity-provider user id). The minted token expires after one hour.

Product access (Enterprise)​

On an Enterprise deployment ContentsEstimation pushes each person's product access to this app, and get_current_user refuses (403 with an X-Access-Denied header) anyone whose stored record says ContentsVision is switched off or the account is deactivated. It runs on every authenticated request, before a user or team is created, so it covers the ContentsEstimation hand-off, a direct sign-in, the cookie and the local bypass alike, and an already signed-in person is refused on their next request. With no stored record (every SMB deployment) nothing is checked. Internal admins and impersonation sessions are never restricted. The full story, including the push routes and the timing, is in product access.

Before this, ContentsVision kept no per-person product access at all: a valid token was enough, and users.is_active was never read at sign-in.

The frontend session​

lib/auth.tsx keeps the session resilient:

  • On load it restores the token and user from localStorage (cv_auth_token, cv_auth_user).
  • If there is no stored session and the user did not explicitly log out this tab (a sessionStorage flag), it probes /api/auth/me to pick up a cookie-based session.
  • Logout fires a keepalive POST to /api/auth/logout (so it survives the immediate client-side navigation), sets the logged-out flag, clears local storage, and resets state.

Session expiry (auto sign-out)​

AdjustSquare JWTs expire (about 12 hours). Once expired, every authenticated API call returns 401 "Invalid or expired token". Rather than surface that raw error on the page, a global guard signs the user out cleanly:

  • components/SessionGuard.tsx wraps window.fetch once in the browser and watches every response. The decision of whether a response means "session expired" is the pure shouldLogoutOnResponse(url, status) in lib/sessionGuard.mjs (unit-tested): true only for a 401 from /api/*, excluding /api/auth/* (so signing out or probing the session can't loop), excluding /api/public/* (see below), and excluding third-party hosts like Sentry/PostHog ingest.
  • On a match, lib/session.ts handleSessionExpired() fires once: it records a Sentry breadcrumb (not an issue: expiry is expected, and captureMessage was opening a Sentry issue for every sign-out) plus a PostHog session_expired event, clears the local session, and hard-redirects to /login?reason=expired.
  • The login page reads that flag and shows a "You were signed out, your session expired" notice, then offers the normal Adjust Square sign-in.

The same guard watches for a 403 carrying X-Access-Denied (accessDeniedReason in lib/sessionGuard.mjs, on every /api/* route including /api/auth/*, never /api/public/*). That is a person whose ContentsVision access was switched off: handleAccessOff() clears the session and shows /no-access instead of the login page. An ordinary 403 never signs anybody out. lib/auth.tsx also asks GET /api/auth/access once a minute while a tab is visible, so an idle tab finds out within 60 seconds. See product access.

This turns an opaque red "Invalid or expired token" into a graceful re-authentication. How often it happens is visible in PostHog (session_expired). Sentry keeps it as a breadcrumb on whatever error happens next, not as its own issue.

The public surfaces (no JWT at all)​

Two things in this app are reachable without a token, and it is worth knowing exactly which:

SurfaceWhat it isWrite access
GET /api/training/certificates/{code}, page /verify/{code}Confirms a shared training certificate is genuine. Returns only what the certificate itself displays; never emails or ids.Read only
/api/public/insured/..., page /insured/{token}The insured inventory link: a homeowner building their own inventory for one claim.Yes

The second is the app's only public write surface. It does not use this page's auth model at all; a secrets.token_urlsafe(32) token in the URL is the whole credential, and only its SHA-256 hash is stored. What replaces JWT scoping there:

  • The link resolves to exactly one claim_id, and every room and draft row is re-checked against it, so a valid token for one claim can do nothing to another.
  • Unknown, revoked, and expired tokens all return the same 404, so a prober learns nothing.
  • Links expire (INSURED_LINK_TTL_DAYS) and can be revoked, which takes effect on the holder's next request.
  • Rate limits are per token, plus a per-IP limit on unknown tokens (core/rate_limit.py), and there are per-file, per-link-lifetime, and row-count ceilings.
  • It never answers 401. The session guard above logs a user out on any 401 from /api/*, and a homeowner has no account to log back into, so a 401 there would strand them on a login page forever. The backend is written not to send one, and shouldLogoutOnResponse excludes the prefix as a second line.

Both public pages render outside AppShell, which treats /verify/ and /insured/ as public prefixes, so neither shows the sidebar or is redirected to /login.

Signing the user back INTO Contents Estimation​

The same trust runs the other way. The Integrations page's ContentsEstimation card opens Contents Estimation already signed in: GET /api/sso/contents-estimation/authorize mints a short-lived HS256 token for the signed-in user with the same shared secret, and the browser is sent to {CONTENTS_ESTIMATION_APP_URL}/auth/contentsvision?token=..., where CE trades it for a session of its own.

Because one secret signs both directions, every token in this system carries a direction marker (aud + purpose); a token minted for one door is refused at the other. The full contract, the safety properties, and how to check the two implementations still agree live in the Contents Estimation integration.

Operational notes​

  • A login event is written to the activity log only when GET /api/auth/me is called with a bearer token, not on cookie session checks, to avoid noise. Note that lib/auth.tsx also refreshes /api/auth/me with the bearer token in the background when it restores a stored session on page load, so those refreshes log a login too.
  • If ADJUSTSQUARE_JWT_SECRET is unset, the backend logs a loud error and every token fails validation. This is the first thing to check if "everyone is suddenly logged out." See troubleshooting.
  • The same team_token from the JWT is what authenticates claim submission to Adjust Square, tying login and submission together. See the Adjust Square integration.
  • ADJUSTSQUARE_JWT_SECRET is now used in both directions: it validates the tokens that sign people in here, and (unless CONTENTS_ESTIMATION_SSO_SECRET overrides it) signs the ones that sign them into Contents Estimation. It must match CE's CONTENTSVISION_SSO_SECRET.