# Accounts

Make an app private, give a shop customer accounts, or let people play as guests, with one command and no OAuth client.

One command gives an app sign-in, users, roles, an account page and an
administration page. You register nothing and set no secrets: Ferrite proves who
somebody is, and your app keeps its own users in its own store.

| Preset | Who may enter | Use it for |
| --- | --- | --- |
| `private` | You, people you add in the Dashboard or in the app, and people you invite | An internal tool, a family app, a members' site |
| `customers` | Anyone who signs in | A shop, a booking site, a product with accounts |
| `players` | Anyone, as a guest first | A game, a quiz, anything people should try before signing in |

## Add accounts

```bash
ferrite add auth --for customers
ferrite check && ferrite test
ferrite deploy
```

The command installs the `auth` package into `src/auth/`, writes
`src/app_auth.rs`, and adds the store binding and forwarded headers to
`ferrite.json`. If it cannot place the call in your handler, it prints the line
to add.

New apps can start with it: `ferrite new webapp my-app --private`, or
`ferrite new webapp my-app --accounts customers`.

## Ask who is there

```rust
// Once, at start.
let auth = auth::App::open(&ctx, "state", auth::AuthOptions::customers()
    .named("Kiln & Co")
    .public(&["/", "/mugs/"])).await;

// For each request, first.
let visitor = match auth.answer(&request).await {
    auth::Answer::Reply(reply) => return reply,
    auth::Answer::Go(visitor) => visitor,
};
```

`answer` serves the sign-in, account and administration pages, and sends an
anonymous visitor to sign in for any path you did not make public. A public path
is exact, or a prefix when it ends in `/`. `.public_all()` leaves each handler to
ask.

```rust
let user = match visitor.require_user(&request) {
    Ok(user) => user,
    Err(reply) => return reply,
};
let key = format!("orders/{}", user.id);
```

Key everything you store on `user.id`. It belongs to your app and never changes.
Names, addresses and ways of signing in do.

- `visitor.user()` is `None` for an anonymous visitor on a public path.
- `visitor.require_account(&request)` also refuses guests.
- `visitor.require_role(&request, "staff")` asks for a role you granted.
- `visitor.csrf_field()` goes inside every form. A state-changing request without
  it is refused.

## People

Open `/auth/admin` as the app's owner to search people, suspend somebody, end
their sessions, grant roles, or delete an account. Suspending takes effect on
their next request. `/auth/admin.json` lists the same people for a script, and
`POST /auth/admin` takes the same actions as JSON.

Each person has `/auth/account`, where they choose the name others see, remove a
way of signing in, sign out everywhere, and delete their account.

Two ways of signing in with the same verified address are one user.

When somebody deletes their account, your app finds their id here and removes
what it kept:

```rust
for id in auth.deleted_users(50).await? {
    delete_orders(&ctx, &id).await?;
    auth.forget_user(&id).await?;
}
```

## Private apps

You are the owner. Add people in any of three places:

- **The Dashboard**, for teams and for several apps at once. Use groups, or
  `ferrite access`.
- **`/auth/access`** in the app, by address.
- **An invite** from the same page: a link that admits a set number of people.

Removing somebody in the Dashboard ends their sessions at once. If that message
does not reach your app, their next page after 10 minutes is checked again, and
nothing is answered after 60 until it has been.

## Guests

With `players`, the sign-in page offers **Play as a guest**, and your own page can
too:

```html
<form method="post" action="/auth/guest?return_to=/"><button>Play now</button></form>
```

A guest is a user with an id, in one browser, for 30 days after last use. Signing
in for the first time keeps the id, so nothing has to move. If that person
already has an account, decide what to do with the guest's data:

```rust
if let (Some(user), Some(guest)) = (visitor.user(), visitor.guest_to_merge()) {
    add_scores(&ctx, guest, &user.id).await?;
    auth.finish_merge(&visitor).await?;
}
```

Two requests can arrive at once and one can stop half way, so `add_scores` records
the guest's id in the same write as the new total, and adds nothing the second time.

## Live connections

A stream or WebSocket opens without cookies or headers, so it carries a ticket:

```js
const me = await (await fetch('/auth/session')).json();
const reply = await fetch('/auth/ticket', {
  method: 'POST',
  headers: { 'content-type': 'application/json', 'x-csrf-token': me.csrf_token },
  body: JSON.stringify({ for: 'room:7' }),
});
const { ticket } = await reply.json();
const stream = new EventSource('/events?ticket=' + ticket);
```

`auth.redeem_ticket(&ticket, "room:7").await?` answers once, within 30 seconds,
with `opened.user`. For a WebSocket, send the ticket in the first message. On a
connection that stays open, call `auth.still_here(&opened).await?` every few
seconds and close it when the answer is false.

## Agents

An AI assistant connected through the App Hub acts for one person with the scope
they granted. `visitor.agent()` names it and `visitor.user()` the person. Reading
needs `apps:read` and changing needs `apps:write`. An agent never has a role, so
it cannot administer. For an MCP endpoint, name the path with
`.agent_paths(&["/mcp"])` and check each tool with `visitor.require_scope`.

## The sign-in page

People sign in with Google, GitHub, or a six-digit code sent to their address.
Set your app's name, colour and logo in the Dashboard, or with the CLI:

```bash
ferrite access page --name "Kiln & Co" --color "#7a3b1d" --logo logo.png
```

To put your own name on Google's or GitHub's consent screen,
[register your own client](/developers/authentication/). Users, roles and pages
stay the same.

## Local development

`ferrite dev` signs you in without a provider. Pick one of the test people, or
type any address. An address that starts with `owner@` is the owner.

## Build with MCP alone

Pass `"packages": ["auth"]` to `deploy_source`, write the `App::open` call above
in your handler, and set three public values with `set_secret`:
`auth_public_origin`, `auth_broker_origin` and `auth_broker_jwks`. See
[Deploy directly over MCP](/developers/authentication/#deploy-directly-over-mcp).

## Examples

- [Orchard Club](https://github.com/iGentAI/ferrite-examples/tree/main/apps/accounts-club), a private noticeboard
- [Kiln & Co](https://github.com/iGentAI/ferrite-examples/tree/main/apps/accounts-shop), a shop with customers and staff
- [Lantern Walk](https://github.com/iGentAI/ferrite-examples/tree/main/apps/accounts-arena), a game with guests and a live scoreboard
