---
url: /saas-starter/v0.10.1/guide/accounts.md
---
# Accounts

::: tip What this page covers
Every choice of `--Persistence`, `--Auth`, `--IncludeTests` and `--Aspire`: a label says
which options a part is for. The copy in your app's `docs/` folder has only the parts for yours.
`ApiHost` stands for your app's name.
:::

Accounts use ASP.NET Core Identity, with the app's own JSON Web Tokens instead of cookies. The
endpoints are features, like the Todos: `src/ApiHost/Features/Auth/` (signing in and
registering), `Features/Account/` (the signed-in user's own account) and `Features/Admin/`. What
they share (users, tokens, roles, lockout, emails, providers, passkey set-up and two-factor
authentication) is in
`src/ApiHost/Identity/`. The pages match: `src/Client/src/features/auth/`, `features/account/`
and `features/admin/`. For how each part protects users, see
[Security](./security.md).

## Signing in

```mermaid
sequenceDiagram
    participant B as Browser tab
    participant A as API

    B->>A: POST /api/auth/login
    A-->>B: access token (kept in memory)<br/>and refresh token (HttpOnly cookie)
    B->>A: requests, with Authorization: Bearer
    Note over B,A: 15 minutes later, the access token has expired
    B->>A: a request
    A-->>B: 401 Unauthorized
    B->>A: POST /api/auth/refresh, with the cookie<br/>(one tab at a time)
    A-->>B: a new access token, and a new cookie<br/>(the old one is revoked)
    B->>A: the request again
    Note over B,A: after a reload or in a new tab, the page<br/>refreshes with the cookie as it loads
```

* **Tokens.** Login returns a short-lived access token (a JWT) and a refresh token. The client
  refreshes automatically when a request gets a 401; each refresh replaces the refresh token.
  Lifetimes are under `Jwt` in `appsettings.json`.
* **Where the browser keeps them.** The access token only in the page's memory. The refresh token
  in an HttpOnly, `SameSite=Strict` cookie (`__Secure-refresh_token` over HTTPS, path `/api`)
  that page scripts can't read, so an injected script can't steal it. The client asks for the cookie with the
  `X-Refresh-Token-Cookie: true` header on its requests, and the API only reads the cookie when
  that header comes with it, which a page on another site can't add (`Identity/RefreshTokenCookie.cs`).
* **Tabs and reloads.** Every tab shares the cookie, so reloading, opening a new tab or duplicating
  one keeps you signed in: the page gets a new access token with the cookie as it loads. Tabs take
  turns to refresh (a Web Lock), and signing in or out in one tab does the same in the others at
  once (a `BroadcastChannel`).
* **Mobile and desktop apps** use the same API and leave the header out: their refresh token comes
  back in the response body, to keep in the platform's secure storage. See
  [Sign in from a mobile or desktop app](./how-to/sign-in-from-a-mobile-app.md).
* **Reuse detection.** A replaced refresh token is still accepted for
  `Jwt:RefreshTokenReuseGraceSeconds` (30 by default), so two tabs refreshing at the same moment,
  or an app retrying a refresh whose response it lost, aren't mistaken for theft. Reusing one after
  that signs the user out everywhere.
* **Ways to sign in:** email and password, a passkey, or Google/GitHub when configured. With
  [two-factor authentication](#two-factor-authentication) on, a password or Google/GitHub sign-in
  also needs a code.
* &#x20;**Data belongs to organisations.** Each user works in one organisation at a time (see [Organisations](#organisations)), and sees only its data.
* &#x20;**Each user sees only their own data.** Endpoints scope queries to the signed-in user (`principal.GetUserId()`), and SignalR updates go only to that user's tabs.

## Account emails

* **Confirmation.** Registering emails a link to `/confirm-email`, and login is refused (with a
  "send it again" button) until it's opened.
* **Email changes.** A new email in Settings is only used once the link sent to it is opened.
  Asking for one needs the password too, and a code with two-factor on (see
  [Confirming it's you](#confirming-its-you)).
* **Password reset.** `/forgot-password` emails a link to `/reset-password`. Resetting also
  confirms the email and lifts a lockout from failed logins.
* **Security emails.** People are told when their password is changed or reset, their email
  changes (sent to the old address), two-factor authentication is turned on or off (also by an
  admin), they get new recovery codes or use one, a passkey or a Google/GitHub sign-in is added
  or removed, the account is [locked](#lockout), or someone signs in from a new device (see
  [New sign-ins](#new-sign-ins)). Each says what to do if it wasn't them. They're always sent:
  they aren't notifications people can turn off. The wording is in
  `Identity/Email/SecurityNotices.cs`; send one for a new kind of change by adding to
  `SecurityChange` and returning a `SendSecurityNotice`. The lockout and recovery-code emails are
  sent by `ApplicationUserManager` (`Identity/ApplicationUserManager.cs`), wherever a wrong
  password or code is counted or a recovery code is used, so new endpoints get them too.
* **How they're sent.** Endpoints don't send email themselves: they return a message
  (`SendEmailConfirmation`, `SendPasswordReset`, ...) that Wolverine stores in its durable inbox,
  and `AccountEmailHandler` (`Identity/Email/AccountEmails.cs`) sends it in the background with
  MailKit, retrying if the mail server is down. The handler creates the one-time token when it
  sends, so tokens are never stored. To change the wording, edit the handler.
* **In Development** the emails go to Mailpit (http://localhost:8025). For production, see
  [Send email through your email provider](./how-to/configure-email.md).

## Settings

Settings has three tabs, each its own URL (`features/account/SettingsLayout.tsx`):

* **Profile** (`/settings`): a profile picture, the display name and the email.
* **Security** (`/settings/security`): the password (changing it signs out the other sessions),
  passkeys, [two-factor authentication](#two-factor-authentication), [sessions](#sessions), and
  linking Google/GitHub.
* **Preferences** (`/settings/preferences`): which emails the user gets, the theme, cookies,
  product news and terms, downloading their data, and deleting the account
  (`/settings/notifications` redirects here).

Settings won't remove the last way a user can sign in.

### Confirming it's you

Changing the email address and deleting the account ask again who it is, so someone using a
browser left signed in, or a stolen access token, can't take the account over or delete it:
whoever controls the email can reset the password. They need the password (if the account has
one) and, with two-factor on, a code or recovery code (`TwoFactor.ConfirmItsYouAsync`). Wrong ones
count towards the [lockout](#lockout). `GET /api/auth/me` says what to ask for (`hasPassword`,
`twoFactorEnabled`). An account with neither (Google, GitHub or passkeys only) is asked to type its
email address before deleting, so it isn't deleted with one click.

### New sign-ins

When someone signs in on a device that hasn't signed in to the account before, they get an email:
"A new sign-in to your account: Chrome on Windows", with what to do if it wasn't them
(`Identity/KnownDevices.cs`). A device is known when it has the `__Secure-known_device` cookie naming the
account: HttpOnly, encrypted, sent only to `/api/auth`, kept for a year, and set at every sign-in
and at registration (so the first sign-in after signing up isn't reported). The User-Agent alone
isn't used, as every computer with the same browser version sends the same one. Apps that don't
keep cookies get the email each time they sign in, which is rarely, as refresh tokens keep them
signed in.

Accepting an invitation and signing up with Google or GitHub don't send one. The email says the
browser and system but not where, as the IP address isn't kept.

### Sessions

**Settings → Sessions** lists where the user is signed in: one entry per sign-in on a device, with
its browser and system ("Chrome on Windows", from the User-Agent), when it started and when it was
last active, and "This device" on the current one. They can sign out one session, or every session
but this one (`Features/Account/SessionEndpoints.cs`).

* **A session is a chain of refresh tokens.** Each token replaced by a refresh keeps the session's
  ID (`RefreshToken.SessionId`), when it started, and the User-Agent; the access token carries the
  ID (the `sid` claim) so the API knows which session is asking.
* **Signing a session out** revokes its refresh token, so it ends when its access token expires
  (`Jwt:AccessTokenLifetimeMinutes`, 15 minutes by default).
* **How long a session lasts:** until it goes unused for `Jwt:RefreshTokenLifetimeDays` (14), and
  at most `Jwt:SessionLifetimeDays` (30) after signing in, however much it's used. Then the user
  signs in again.
* **Only the User-Agent is kept,** not the IP address, so the list says which device but not where.

### Deleting an account

Settings → **Delete account** deletes it for good, after [confirming it's you](#confirming-its-you).

::: info With organisations
It publishes an `AccountDeleted` message; each feature that stores user data
handles it to delete that data. The user leaves each of their organisations, and one they were
the only member of is deleted with its data (`Organisations/LeaveOrganisationsOfDeletedAccountHandler.cs`).
Todos in organisations that others are still in stay: they belong to the organisation, not the
user, and keep the deleted user's id as their `OwnerId`, in the Todo and in its event history.
Nothing else about the user (email, name) is kept with them. If your data needs to forget its
authors too, clear or replace those ids in an `AccountDeleted` handler.
:::

::: info Without organisations
It publishes an `AccountDeleted` message; each feature that stores user data
handles it to delete that data (see `Features/Todos/DeleteTodosOfDeletedAccountHandler.cs`).
:::

## Preferences

Each user has one preferences record (`Identity/UserPreferences.cs`), separate from their account:
signing in and refreshing tokens don't load it, and it can grow without widening the users table.
It holds their cookie choices ([analytics](./analytics.md)), their theme, which version of the
[terms and privacy policy](#terms-and-privacy-policy) they accepted, and whether they want
[product news](#product-news). It's the place for other
preferences you add, such as a language or time zone.

**Settings → Preferences** shows them: the theme, the cookie choice with a **Cookie settings**
button (when analytics is on), product news, and when the terms were accepted (when they're set). Add new
preferences there (`features/account/PreferencesSection.tsx`).

The theme (System, Light or Dark: in the footer of public pages, and in Settings) works for everyone: the browser remembers it,
and with an account it's saved in the preferences too, so it follows people to their other
devices. When someone signs in, the theme saved in their preferences wins; if there's none, the
browser's is saved.

* **To add a preference,** add a property to `UserPreferences` with a sensible default (people who
  never set it get that), and a `PUT` endpoint that changes it with
  `IUserPreferencesStore.UpdateAsync`, like `PUT /api/account/consent` in
  `Features/Account/PreferenceEndpoints.cs`. The client reads them all with
  `GET /api/account/preferences` (`usePreferences()`).
* **No migration needed:** the preferences are stored as JSON (a Marten document, or one `jsonb`
  column with EF Core), so a new property changes no table.
* **Renaming or removing a property** loses what people saved under the old name, so keep the
  old one readable until you've moved the values over.
* **Export and deletion are covered:** the preferences are in "Download your data", and deleted
  with the account.

Settings that belong to one feature stay with that feature, such as which notifications are
emailed (`Notifications/`).

### Product news

Sign-up has an unticked **Send me product news** box, separate from accepting the terms, and
**Settings → Preferences** a box to change it later. The choice and when it was made are kept in
the preferences (`ProductNews`: `subscribed` and `chosenAt`), so there's a record of consent and
it's in "Download your data". People who signed up with Google or GitHub, or were invited, haven't
been asked (`ProductNews` is null), which counts as no.

The template doesn't send product news itself: send it with your newsletter tool, only to people
with `ProductNews.Subscribed` true, and include an unsubscribe link that turns it off
(`PUT /api/account/product-news`). Set `Accounts:AskForProductNews=false` if the app doesn't send
any.

## Terms and privacy policy

Set `Legal:TermsUrl` and `Legal:PrivacyUrl` to your documents: a page of the app (`/terms`) or
a full address. Then:

* **The footer links to them** (in every app).
* **Signing up needs them accepted:** the form has an "I agree" checkbox, and the API refuses a
  sign-up without it. What they accepted, and when, is saved in their
  [preferences](#preferences).
* **Everyone else is asked after signing in:** people who signed up with Google or GitHub, or
  were invited, see an "Accept our terms" prompt. They can accept, or sign out.
* **Raise `Legal:Version`** when either document changes in a way people should agree to again.
  Everyone is asked to accept the new version ("We've updated our terms") the next time they use
  the app.

Without either setting, there are no links and nothing to accept. The prompt is in the client
(`features/account/TermsGate.tsx`); the API doesn't refuse other requests from someone who hasn't
accepted yet, so API keys and mobile apps keep working. If you need that, check
`UserPreferences.Terms` where it matters. The record is in "Download your data" and deleted with
the account.

## Profile pictures

::: info With organisations
People's pictures appear in the sidebar's user menu, the member list and the admin page, and the
organisation's logo in the switcher. A person's picture is, in order:
:::

::: info Without organisations
People's pictures appear in the sidebar's user menu and the admin page. Each is, in order:
:::

1. **The picture they uploaded** in Settings. The browser crops the middle square of the file and
   resizes it to 256 × 256 pixels (`features/account/pictures.ts`), then uploads it to
   `PUT /api/account/picture`. The server needs no image library: it checks the bytes are a PNG,
   JPEG or WebP picture of at most 512 KB and 1024 pixels a side (`Pictures/ImageFiles.cs`),
   whatever the file name or type claims, and keeps it with [file storage](./file-storage.md) under
   `users/{id}/` with a new random name each time. It's served at `/media/...` with a
   one-year cache lifetime: a new picture gets a new address, so caches never show an old one.
   Anyone with the address can see the picture, as with most apps' avatars; the random name makes
   it unguessable.
2. **Their [Gravatar](https://gravatar.com)**, if they have one and you've set
   `Pictures:Gravatar` to `true` (it's off by default). The browser asks Gravatar for it by the
   SHA-256 hash of the user's email, so Gravatar, a third party, learns that hash and the viewer's
   IP address: under the GDPR, say so in your privacy policy before turning it on. The
   Content-Security-Policy allows Gravatar's pictures only when it's on.
3. **Their initials.**

::: info With organisations
Owners and admins set an organisation's logo on `/organisation` (its General tab) the same way
(`PUT /api/organisation/logo`).
:::

Each person can upload `Pictures:UploadsPerMinute` files a minute (10 by default, counting
pictures, logos and Todo attachments); more get `429 Too Many Requests`, since every upload writes
a file.

**Old pictures are cleaned up** (`Pictures/PictureCleanup.cs`) so that nothing is left in storage
with nothing pointing at it:

* When a picture is replaced or removed, the previous one is deleted in the background, once the
  change is saved, unless its owner is using it again by then.
* Each new picture is checked again 10 minutes later and deleted if its owner isn't using it.
  That catches the rare races: two uploads at the same moment, or a request that loaded the user
  before an upload and saved after it.
* If saving the owner fails after the file was written, the file is deleted straight away.

::: info With organisations
Deleting the account deletes everything under `users/{id}/`, and deleting an organisation
everything under `organisations/{id}/`, through a `DeleteStoredFiles` message of its own. If file
storage is unreachable at that moment, the rest of the deletion still completes, and deleting the
files is retried (after 1 minute, 10 minutes, 1 hour and 6 hours).
:::

::: info Without organisations
Deleting the account deletes everything under `users/{id}/`, through a `DeleteStoredFiles`
message of its own. If file storage is unreachable at that moment, the rest of the deletion
still completes, and deleting the files is retried (after 1 minute, 10 minutes, 1 hour and 6
hours).
:::

## Notifications

The bell in the sidebar lists the user's latest notifications, such as a Todo reminder that came
due, with the number unread. They arrive live (over the realtime connection) and are kept per
user (`Notifications:KeepPerUser`, 100). Each one is also emailed, unless the user turned that
kind off in Settings ("Email notifications") or with the link at the bottom of the email. The link
needs no login, and mail apps show a one-click "Unsubscribe" button for it (the
`List-Unsubscribe` headers). Account emails, such as password resets, can't be turned off.

To notify someone, publish `SendNotification(userId, category, title, body, link)` from an
endpoint or handler (it goes through the outbox). Add new kinds to `NotificationCategories` in
`Notifications/Notification.cs`, with the description users see in Settings. The reminder handler
(`Features/Todos/RemindTodoEndpoint.cs`) is an example.

## Download your data

::: info With organisations
Settings has "Download your data": everything the app stores about the user as one JSON file
(their account, sign-ins and passkeys, preferences, notifications and email choices,
and the organisations they belong to). Organisation owners download the organisation's data
from the organisation page: its Todos, members, billing and integrations.
:::

::: info Without organisations
Settings has "Download your data": everything the app stores about the user as one JSON file
(their account, sign-ins and passkeys, preferences, notifications and email choices,
and their Todos).
:::

Privacy laws such as the GDPR and Thailand's PDPA give people this right. Never the password hash
or other secrets.

A feature that stores data about users adds its section by registering an `IPersonalDataSource`
(`DataExport/DataExport.cs`), like `NotificationsPersonalData`.

::: info With organisations
A feature that stores organisation data registers an `IOrganisationDataSource`, like
`TodosOrganisationData`.
:::

## Lockout

Repeated wrong passwords (or two-factor codes, at sign-in or when [confirming it's
you](#confirming-its-you)) lock the account for a while (ASP.NET Core Identity's lockout,
configured in `ConfigureIdentity` in `Identity/IdentityJwtSetup.cs`). While locked, login is
refused without checking the password, refresh tokens stop working, and resetting the password
lifts the lock. The owner is emailed when the lock starts ("Your account was locked"), once per
lock, as it may be someone guessing their password. An admin can also lock an account until they
unlock it; that isn't emailed.

## Roles and the back office

Roles are constants in `Identity/AppRoles.cs`, created in the database at startup
(`RoleSeeder`). Protect endpoints with `[Authorize(Roles = AppRoles.Admin)]`. A changed role
reaches the user's access token at their next token refresh.

The back office (`/admin`, Admin role only) has these sections:

* &#x20;**Users:** search users, change their roles, lock and unlock accounts (an admin lock ends the user's sessions), end a user's sessions (sign them out everywhere: their refresh tokens are revoked, and each session ends when its access token expires), resend the confirmation email, turn off two-factor authentication for someone who lost their phone and recovery codes, and invite people. An invitation creates the account and emails a link to choose a password, valid for a week. Each user's organisations are listed too.

* &#x20;**Dashboard, Organisations and Feature flags:** see [Plans, trials and limits](./billing.md#the-back-office).

* &#x20;**Users:** search users, change their roles, lock and unlock accounts (an admin lock ends the user's sessions), end a user's sessions (sign them out everywhere: their refresh tokens are revoked, and each session ends when its access token expires), resend the confirmation email, turn off two-factor authentication for someone who lost their phone and recovery codes, and invite people. An invitation creates the account and emails a link to choose a password, valid for a week.

* **Audit log:** every change an admin makes, with who made it and when
  (`Features/Admin/IAuditLog.cs`). Record new admin actions with `IAuditLog.RecordAsync`.

* **Failed messages:** background work that failed every attempt and waits in Wolverine's
  dead-letter queue, such as an email the SMTP server refused. Fix the cause, then replay the
  message (it runs again) or discard it.

* The first admins come from configuration: see [Make someone an admin](./how-to/make-an-admin.md).

* `Accounts:AllowRegistration=false` makes accounts invitation-only.

* To add a role, see [Add a role](./how-to/add-a-role.md).

## Google and GitHub

Each provider is turned on by setting its client ID and secret; see
[Set up external sign-in](./how-to/set-up-external-sign-in.md). The provider must vouch for the
email address: a verified email signs into (and links to) the account with that email, or creates
one. After the provider, the API redirects to `/external-login` with a refresh token in the URL
fragment (a full page load can't ask for the cookie), which the client exchanges at once for new
tokens, and the cookie.

## Passkeys

Users add passkeys in Settings and can then use "Log in with a passkey": the browser offers the
passkeys it has for the site, so no email is typed. This is ASP.NET Core Identity's own WebAuthn
support (`IPasskeyHandler`), used without cookies: the ceremony's state is encrypted and handed to
the client for a few minutes (`Identity/Passkeys/PasskeySetup.cs`).

Passkeys belong to the site's host name: a passkey created on one domain doesn't work on another,
so moving the app to a new domain means users add new passkeys. In development, passkeys work on
`localhost`.

## Two-factor authentication

Users turn it on in **Settings → Two-factor authentication**: they scan a QR code with an
authenticator app (Google Authenticator, Microsoft Authenticator, 1Password and others), and enter
one code from it to prove it worked. They then get ten recovery codes to save, each usable once,
for when they lose their phone. This is ASP.NET Core Identity's authenticator support (TOTP, six
digits every 30 seconds), used without cookies (`Identity/TwoFactor.cs`).

* **Signing in:** with it on, the right password (or a Google/GitHub sign-in) returns a 403 with
  `reason: "TwoFactorRequired"` and a `twoFactorTicket` instead of tokens. The client asks for a
  code and sends it with the ticket to `POST /api/auth/two-factor`. The ticket lasts five minutes
  and stops working if the password changes or two-factor is turned off.
* **Passkeys don't ask for a code:** a passkey is already two factors (the device, and the
  fingerprint, face or PIN that unlocks it).
* **Wrong codes count towards the lockout**, the same as wrong passwords.
* **Each code works once.** Identity accepts a code for a minute or so either side of its 30
  seconds, for phones whose clocks drift; a code that has worked is refused after that, so one
  seen over someone's shoulder is no use (`ApplicationUserManager`). Used codes are remembered in
  memory, by each instance of the app.
* **Using a recovery code is emailed,** with how many are left: whoever used it may have the
  password too.
* **Changing it needs a code:** turning it off or getting new recovery codes needs a current code
  (or a recovery code), so someone using a session left open can't turn it off.
* **Lost phone and recovery codes:** an admin can turn it off from the back office (**Turn off
  two-factor**, recorded in the audit log). Check it's really them first, through some other
  channel.
* **The name in the authenticator app** is `Accounts:TwoFactorIssuer` (the app's name by default).
* **Changing the email or deleting the account needs a code** as well as the password (see
  [Confirming it's you](#confirming-its-you)).
* **Recovery codes** are five groups of five letters and digits (`ABCDE-FGHJK-...`, 125 random
  bits), shown once and stored only as SHA-256 hashes.
* **Stored by Identity:** the authenticator key and the unused recovery codes' hashes are kept with
  the user (with EF Core, in `AspNetUserTokens`; with Marten, on the user document). They're
  secrets, so "Download your data" says only whether two-factor is on.

**Requiring it for admins:** with `Accounts:RequireTwoFactorForAdmins=true`, the Admin role only
counts for admins whose account is protected: two-factor authentication is on, or they sign in only
with passkeys. Other admins' tokens leave the role out, so the API refuses their back office
requests, and `/admin` asks them to set it up in Settings first. Turn it on in production once your
admins have set it up.

## Passwords

A new password (at sign-up, changing or resetting it, or accepting an invitation) needs at least 8
characters, of any kind: no rules about upper case, digits or symbols, which make passwords harder
to remember rather than to guess (NIST SP 800-63B). Paste and password managers work, and nothing
is trimmed or changed. Instead, `Identity/CommonPasswords.cs` refuses:

* the 10,000 most common passwords of 8 characters or more, in any case (`common-passwords.txt`,
  from SecLists, MIT licence);
* passwords made mostly of the user's email address, the app's name, or the words in
  `Accounts:PasswordBlockedWords` (add your product and company names): taking those out must
  leave at least 8 characters, so `MyApp2024!` is refused, but a long passphrase that contains the
  app's name isn't.

Passwords never expire: people change them when they want to, or when one turns out to be known
(below). Change the length in `ConfigureIdentity` (`Identity/IdentityJwtSetup.cs`).

### Breached passwords

With `Accounts:RejectBreachedPasswords=true`, a new password (at sign-up, changing or resetting it,
or accepting an invitation) is refused if it's known from a data breach, as NIST SP 800-63B
advises: those are the passwords attackers try first. It's checked with Have I Been Pwned's
[Pwned Passwords](https://haveibeenpwned.com/API/v3#PwnedPasswords), which is free and needs no
key, without sending the password: only the first five characters of its SHA-1 hash go to the
service, which answers with every breached hash that starts with them (padded, so the answer's
size gives nothing away), and the match is made on the server (`Identity/BreachedPasswords.cs`).
If the service doesn't answer within three seconds, the password is accepted and a warning logged.
It's off by default because it calls an outside service.

::: info With organisations

## Organisations

Data belongs to organisations, the app's tenants. The code is in `src/ApiHost/Organisations/`
(the model, its store, and choosing a session's organisation) and `Features/Organisations/`
(the endpoints); the pages are in `src/Client/src/features/organisations/`.

* **Everyone has one.** A new account gets its own organisation, named after the user ("Ada's
  organisation"). Users can create more, and be invited into others; the switcher at the top of the
  sidebar picks the current one.
* **The access token names the organisation** (the `org` claim), chosen when the token is issued:
  the one the session was in, or the one the user used last. Switching issues new tokens.
  Every request checks that the user is still a member, so removing someone, or deleting the
  organisation, takes effect at once; the browser then refreshes its tokens into another of the
  user's organisations.
* &#x20;**Multi-tenancy.** Wolverine reads the claim as each request's tenant id and carries it on the messages the request sends. Tenanted data (`Todo`, which implements `ITenanted`) is stored with a tenant id (Marten's conjoined multi-tenancy), so queries only ever see the current organisation's, without a filter in each endpoint. Organisations, memberships and invitations themselves aren't tenanted.
* &#x20;**Multi-tenancy.** Wolverine reads the claim as each request's tenant id and carries it on the messages the request sends. Tenanted data (`Todo`, which implements `ITenanted`) is stored with a tenant id (Wolverine's conjoined multi-tenancy for EF Core: a `tenant_id` column and a global query filter), so queries only ever see the current organisation's, without a filter in each endpoint. Organisations, memberships and invitations themselves aren't tenanted.
* **Roles:** Owner, Admin and Member. Owners and admins invite and remove members and change
  roles, but only owners make owners, change an owner's role, rename or delete the organisation.
  There's always an owner: the last one can't leave or step down, and can't delete their account
  while others are members (`Features/Organisations/OrganisationRules.cs`). Each change checks
  again after saving and undoes itself if a change at the same moment left no owner; and if an
  owner's account is deleted after someone joined, their longest-standing admin (or member)
  becomes the owner.
* **Invitations** go by email, with a link to `/join` that works for a week. Someone with an
  account logs in with the invited email and accepts; someone without one chooses a password,
  and the link confirms their email. Only a hash of the link's token is stored, and the page
  sends the token in request bodies, never in a URL the API would log. Each user can send 20
  invitations an hour and an organisation can have 100 waiting (`Organisations:InvitationsPerHour`,
  `Organisations:MaxPendingInvitations`; see `Organisations/OrganisationOptions.cs`), so the app
  can't be used to send spam.
* **Requiring two-factor authentication:** an owner can require it of every member (the
  organisation page; the owner must have it on first). Members without it (or who don't sign in only
  with passkeys) can't work in the organisation: their tokens stop working at once, a new session
  starts in another of their organisations, and the switcher marks it "needs two-factor". The
  members list shows who has it. The access token carries whether the user has two-factor (the
  `tfa` claim), so this costs no extra query per request. API keys aren't affected: they're their
  own credential.
* **Deleting an organisation** deletes it for everyone. Its data is deleted in the background:
  each feature handles `OrganisationDeleted`, which runs for that organisation's tenant (see
  `Features/Todos/DeleteTodosOfDeletedOrganisationHandler.cs`). The message is published in the
  same transaction as the deletion, so the data is never left behind.
* **Realtime updates** go to everyone working in the organisation; the browser reconnects when it
  switches. Reminders go only to the member who set them, while they're still a member. A
  connection is closed when its access token expires, so someone removed from an organisation
  stops getting its updates within one token lifetime.
  :::

## Development

The demo user (`demo@example.com` / `Demo123!`) is created at startup in Development only, is
already confirmed, and is an admin. Change it under `DevelopmentUser` in
`src/ApiHost/appsettings.Development.json` and in `src/Client/.env.development`.
