Auth: username+password, email+password and API key everywhere; key returns carry username and email

POST /auth/login (form and JSON) now accepts the username in the email field, like HTTP Basic and POST /auth/token always did; the token endpoint no longer lowercases the identifier before the username lookup, fixing mixed-case usernames. The login field is relabelled and type=text so browsers accept a username.

Every JSON return of the personal API key now also returns the account username and email: the profile JSON gains a can_view_api_key-gated email beside api_key (username already rides profile_user), and POST /profile/regenerate-api-key returns {api_key, username, email}. A client holding only its DEVPLACE_API_KEY value can now fetch its full account via GET /profile in one call.

Documented fully: authentication prose page (three credentials, precedence, DEVPLACE_API_KEY, account fetch, separate DevRant/WebSocket auth domains), new auth-token docs_api card, regenerated-key sample, conventions, README, CLAUDE.md, OpenAPI description, corrected profile key hint. Summary in changes.md (left unversioned per request).

Tests: username/mixed-case/uppercase-email login and token cases, API-key account fetch via X-API-KEY and Bearer, owner/admin vs stranger/guest email gating, regenerate shape, browser login by username. Failing-first observed red, green after.
This commit is contained in:
2026-11-11 16:07:43 +01:00
parent 33eb090e27
commit dbdd0d29dd
20 changed files with 357 additions and 45 deletions
+35 -8
View File
@@ -23,8 +23,10 @@ The POST endpoints are **actions**: they accept form fields, set or clear the `s
and return a `302` redirect (or the JSON envelope for JSON callers).
**Sign-up requires a unique `username` and `email`** plus a `confirm_password` that matches the
password; **you log in with your `email` and password**. JSON callers receive validation errors
as a `422` with the shape `{ "fields": {...}, "messages": [...] }`.
password; **you log in with your `username` or your `email`, plus your password** (the `email`
field accepts either identifier; usernames are case-sensitive, email addresses are not). The
same identifier rule applies to `POST /auth/token` and HTTP Basic. JSON callers receive
validation errors as a `422` with the shape `{ "fields": {...}, "messages": [...] }`.
""",
"endpoints": [
endpoint(
@@ -89,20 +91,20 @@ as a `422` with the shape `{ "fields": {...}, "messages": [...] }`.
method="POST",
path="/auth/login",
title="Log in",
summary="Authenticate with email and password. Sets the session cookie.",
summary="Authenticate with username (or email) and password. Sets the session cookie.",
auth="public",
encoding="form",
params=[
field("email", "form", "string", True, "alice@example.com", "Your registered email."),
field("email", "form", "string", True, "alice@example.com", "Your username or your registered email."),
field("password", "form", "string", True, "mysecret", "Your password."),
field("remember_me", "form", "string", False, "on", "Send 'on' to extend the session to the remember-me lifetime."),
field("next", "form", "string", False, "", "Redirect target after login."),
],
notes=[
"JSON callers receive the account's `email`, `api_key`, and "
"`is_admin` flag in `data`, so a script can trade one email/password "
"login for a reusable key. Failed logins return 401 and never "
"include the key.",
"JSON callers receive the account's `username`, `email`, `api_key`, "
"and `is_admin` flag in `data`, so a script can trade one "
"username/password or email/password login for a reusable key. "
"Failed logins return 401 and never include the key.",
],
sample_response={
"ok": True,
@@ -115,6 +117,31 @@ as a `422` with the shape `{ "fields": {...}, "messages": [...] }`.
},
},
),
endpoint(
id="auth-token",
method="POST",
path="/auth/token",
title="Issue access token",
summary="Exchange username (or email) and password for a short-lived access token. No session cookie is set.",
auth="public",
encoding="form",
params=[
field("email", "form", "string", True, "alice@example.com", "Your username or your registered email."),
field("password", "form", "string", True, "mysecret", "Your password."),
],
notes=[
"Accepts a JSON body with the same fields. The returned token "
"works as an `Authorization: Bearer` or `X-API-KEY` credential "
"until it expires (default 7 days). Missing fields return 400, "
"wrong credentials 401, a deactivated account 403; failures "
"never include a token.",
],
sample_response={
"access_token": "ACCESS_TOKEN",
"token_type": "bearer",
"expires_in": 604800,
},
),
endpoint(
id="auth-forgot-password",
method="GET",
+5 -4
View File
@@ -19,10 +19,11 @@ Every example uses your current host:
## Authentication
Each endpoint is tagged **public**, **user**, or **admin**. Authenticate user and admin
endpoints with any of the four methods in [Authentication](/docs/authentication.html): the
`session` cookie, an `X-API-KEY` header, a `Bearer` token, or HTTP Basic credentials. The
interactive panels on this site pre-fill your own API key, so you can run user-level calls
immediately.
endpoints with any of the methods in [Authentication](/docs/authentication.html): the
`session` cookie, an `X-API-KEY` header, a `Bearer` token, or HTTP Basic credentials
(username or email, plus password; the headers also accept native access tokens and
DevRant auth tokens). The interactive panels on this site pre-fill your own API key, so
you can run user-level calls immediately.
## Request bodies
+5 -1
View File
@@ -379,7 +379,11 @@ four ways to sign requests.
"> Running this invalidates the key these documentation panels use. Do it from your "
"[profile page](/profile/{{ username }}) instead, then reload these docs.",
],
sample_response={"api_key": "NEW_UUID"},
sample_response={
"api_key": "NEW_UUID",
"username": "alice",
"email": "alice@example.com",
},
),
endpoint(
id="profile-give-award",
+9
View File
@@ -77,6 +77,15 @@ logging.getLogger("alembic.runtime.migration").setLevel(logging.WARNING)
app = FastAPI(
title="DevPlace",
description=(
"Authentication: username+password, email+password (login form, JSON "
"POST /auth/login, POST /auth/token, and HTTP Basic all accept the "
"username or the email address), or the personal API key from the "
"profile page sent as X-API-KEY or Authorization: Bearer "
"(conventionally carried in the DEVPLACE_API_KEY environment variable). "
"GET /profile with an API key returns the account username, email, and "
"API key. Full reference: /docs/authentication.html"
),
docs_url="/swagger",
redoc_url=None,
openapi_url="/openapi.json",
+3 -2
View File
@@ -52,13 +52,14 @@ async def login_page(request: Request, next: str | None = None):
@router.post("/login")
async def login(request: Request, data: Annotated[LoginForm, Depends(json_or_form(LoginForm))]):
email = data.email.strip().lower()
identifier = data.email.strip()
email = identifier.lower()
password = data.password
remember_me = data.remember_me == "on"
errors = []
users = get_table("users")
user = users.find_one(email=email)
user = users.find_one(email=email) or users.find_one(username=identifier)
if not user or not await verify_password_async(password, user["password_hash"]):
errors.append("Invalid email or password")
+2 -2
View File
@@ -22,7 +22,7 @@ async def token(
request: Request,
data: Annotated[LoginForm, Depends(json_or_form(LoginForm))],
):
identifier = data.email.strip().lower()
identifier = data.email.strip()
password = data.password
if not identifier or not password:
@@ -32,7 +32,7 @@ async def token(
)
users = get_table("users")
user = users.find_one(email=identifier) or users.find_one(
user = users.find_one(email=identifier.lower()) or users.find_one(
username=identifier
)
+1 -1
View File
@@ -14,7 +14,7 @@ The **Legal** section (`SECTION_LEGAL`, in the `AUDIENCE_START` tier so it is on
`DOCS_PAGES` entries take optional `admin: True` (hidden + 404 for non-admins, but still indexed and surfaced only to admins by `docs_search`) and `section: "..."` (a nested sidebar group rendered by `docs_base.html`). The sidebar groups `section`s under four ordered **audience tiers** (`AUDIENCES` in `routers/docs/pages.py`): `Start here` (General), `Build with the API` (API, Components, Styles), `Contribute and internals` (Architecture, Services, Devii internals, Bots internals, Testing, Claude Code), and `Operate` (Administration, Production). `nav_groups(visible_pages)` builds the `[(audience, [(section, [pages])])]` tree from the flat visible-page list (so a section's pages collect under one heading regardless of `DOCS_PAGES` order or the API/Administration interleave from `api_doc_pages()`); `views.py` passes it as `nav`, and `docs_base.html` renders an audience super-header (`.sidebar-tier`) above each section subheading (`.sidebar-subheading`). `DOCS_PAGES` stays the canonical list for search/export/routing - the tiering is sidebar-only.
The public `getting-started` page (`SECTION_GENERAL`) is the new-contributor on-ramp (install/run, the four-faces workflow, validation); gate its deep-internals links with `{% if is_admin(user) %}` so guests get no 404s. Keep one canonical home per concept: the `auth` API group intro in `docs_api.py` defers method detail to the `authentication` prose page rather than re-listing the four methods. The member-facing `devii` prose page is functional; admins also get a `Devii internals` section of `devii-*` technical subpages.
The public `getting-started` page (`SECTION_GENERAL`) is the new-contributor on-ramp (install/run, the four-faces workflow, validation); gate its deep-internals links with `{% if is_admin(user) %}` so guests get no 404s. Keep one canonical home per concept: the `auth` API group intro in `docs_api.py` defers method detail to the `authentication` prose page rather than re-listing the auth methods (three account credentials: username+password, email+password, personal API key; the prose page is canonical for precedence, `DEVPLACE_API_KEY`, the `GET /profile` account fetch, and the separate DevRant/WebSocket auth domains). The member-facing `devii` prose page is functional; admins also get a `Devii internals` section of `devii-*` technical subpages.
## Single source of truth
+9 -1
View File
@@ -322,6 +322,7 @@ async def profile_page(
viewer_is_admin = bool(current_user and current_user.get("role") == "Admin")
can_view_api_key = bool(current_user and (is_owner or viewer_is_admin))
api_key = profile_user.get("api_key") if can_view_api_key else None
email = profile_user.get("email") if can_view_api_key else None
ai_correction_enabled = (
bool(profile_user.get("ai_correction_enabled")) if is_owner else False
)
@@ -485,6 +486,7 @@ async def profile_page(
"media_pagination": media_pagination,
"can_view_api_key": can_view_api_key,
"api_key": api_key,
"email": email,
"ai_correction_enabled": ai_correction_enabled,
"ai_correction_sync": ai_correction_sync,
"ai_correction_prompt": ai_correction_prompt,
@@ -594,7 +596,13 @@ async def regenerate_api_key(request: Request):
summary=f"{user['username']} regenerated their API key",
links=[audit.target("user", user["uid"], user["username"])],
)
return JSONResponse({"api_key": new_key})
return JSONResponse(
{
"api_key": new_key,
"username": user["username"],
"email": user["email"],
}
)
+1
View File
@@ -45,6 +45,7 @@ class ProfileOut(_Out):
profile_is_admin: bool = False
can_view_api_key: bool = False
api_key: Optional[str] = None
email: Optional[str] = None
ai_correction_enabled: bool = False
ai_correction_sync: bool = False
ai_correction_prompt: Optional[str] = None
+60 -13
View File
@@ -3,11 +3,16 @@
<div class="docs-content" data-render>
# Authentication
DevPlace accepts four interchangeable authentication methods. The website uses the
session cookie; the other three authenticate **any request** - any page or action -
without a browser login, ideal for scripts and automation. See
[Conventions & Errors](/docs/conventions.html) for the base URL, request bodies,
content negotiation, pagination, and status codes that every endpoint shares.
DevPlace recognizes three account credentials: your **username and password**, your
**email address and password**, and your **personal API key**. The password
credentials work everywhere a password is asked for: the login form, the JSON login,
the token endpoint, and HTTP Basic (the identifier may be the username or the email
address; usernames are case-sensitive, email addresses are not). The API key
authenticates **any request** - any page or action - without a browser login, ideal
for scripts and automation. On top of those, the `X-API-KEY` and `Bearer` headers also
accept two token kinds (native access tokens and DevRant auth tokens, sections 5
and 6). See [Conventions & Errors](/docs/conventions.html) for the base URL, request
bodies, content negotiation, pagination, and status codes that every endpoint shares.
{% if not user %}
> You are not logged in. Examples below use placeholders. [Log in](/auth/login) and
@@ -19,6 +24,15 @@ content negotiation, pagination, and status codes that every endpoint shares.
Your API key is a UUID shown on your [profile page]({% if user %}/profile/{{ uname }}{% else %}/profile/YOUR_USERNAME{% endif %}).
You can regenerate it there at any time; the previous key stops working immediately.
Clients and examples conventionally carry this personal key in the
`DEVPLACE_API_KEY` environment variable; DevPlace containers inject it automatically.
`DEVPLACE_API_KEY` is only the name of that variable - on the wire the value is always
sent as the `X-API-KEY` header or a `Bearer` token shown below.
Credentials are resolved in a fixed order: session cookie first, then `X-API-KEY`,
then `Authorization: Bearer`, then HTTP Basic. A valid browser session therefore wins
over header credentials sent along with it. Inactive accounts are rejected by every
method.
The interactive panels throughout the [API reference](/docs/index.html) pre-fill your API
key, so you can run user-level calls directly from these pages. Vote, reaction, bookmark, and
@@ -103,6 +117,10 @@ curl -H "X-API-KEY: $TOKEN" \
{{ base }}/notifications
```
The `email` field accepts your username or your email address (usernames are
case-sensitive, email addresses are not), and the body may be JSON or form data.
Missing fields return `400`, wrong credentials `401`, and a deactivated account `403`.
Tokens are valid for the configured session lifetime (default 7 days). Manage
tokens with the CLI: `devplace token issue <user>`, `devplace token list <user>`,
`devplace token revoke <uid>`, `devplace token revoke-all <user>`.
@@ -129,8 +147,9 @@ curl -H "X-API-KEY: YOUR_DEVRANT_TOKEN_KEY" \
## Logging in from a script
`POST /auth/login` (and `POST /auth/signup`) accept JSON as well as form data.
A successful JSON login returns the account's email, API key, and admin flag,
so one email/password call bootstraps every later request:
The `email` field accepts your username or your email address. A successful JSON
login returns the account's username, email, API key, and admin flag, so one
username/password or email/password call bootstraps every later request:
```bash
curl -X POST {{ base }}/auth/login \
@@ -153,12 +172,30 @@ curl -X POST {{ base }}/auth/login \
```
Store the `api_key` and use it as an `X-API-KEY` or Bearer credential from then
on; there is no need to log in again. `GET /profile/{username}` with
`Accept: application/json` reports the same picture per profile:
`profile_is_admin` tells whether the profile owner is an admin,
`viewer_is_admin` and `is_owner` describe the viewer, and `api_key` holds the
profile's key only for its owner or an admin (`can_view_api_key`), null for
everyone else.
on; there is no need to log in again.
## Fetching your account with only an API key
A client that starts out knowing nothing but an API key (for example from
`DEVPLACE_API_KEY`) can fetch the account it belongs to with `GET /profile`:
```bash
curl -H "X-API-KEY: $DEVPLACE_API_KEY" \
-H "Accept: application/json" \
{{ base }}/profile
```
Every response that returns your personal API key returns your username and email
address alongside it, so the account is fully identified in one call: JSON
login/signup (`data.username`, `data.email`, `data.api_key`), the profile JSON
(`profile_user.username`, `profile_user.uid`, `email`, `api_key`), and
`POST /profile/regenerate-api-key` (`username`, `email`, `api_key`).
`GET /profile/{username}` with `Accept: application/json` reports the same picture
per profile: `profile_is_admin` tells whether the profile owner is an admin,
`viewer_is_admin` and `is_owner` describe the viewer, and `api_key` plus `email`
are filled in only for the profile's owner or an admin (`can_view_api_key`), null
for everyone else.
## Performing actions
@@ -185,6 +222,16 @@ curl -X POST -H "Authorization: Bearer YOUR_DEVRANT_TOKEN_KEY" \
{{ base }}/posts/create
```
## Separate auth domains
Two surfaces deliberately do not take the credentials above. The DevRant-compatible
API under `/api/*` authenticates with its own `token_id` and `token_key` request
parameters (its `POST /api/users/auth-token` exchange does accept username or email
plus password); a personal API key, access token, Basic credentials, or session
cookie authenticate nothing there. WebSocket endpoints accept the session cookie or
an API key (header or one-time ticket, depending on the socket) but never HTTP Basic,
because browsers cannot set WebSocket headers.
## Errors
Invalid credentials make protected endpoints respond with `401 Unauthorized`. Requests
+2 -2
View File
@@ -22,8 +22,8 @@
<form class="auth-form" method="POST" action="/auth/login">
<input type="hidden" name="next" value="{{ next_url or '' }}">
<div class="auth-field">
<label for="email">Email address</label>
<input type="email" id="email" name="email" value="{{ email or '' }}" required aria-required="true" maxlength="255" placeholder="you@example.com">
<label for="email">Username or email address</label>
<input type="text" id="email" name="email" value="{{ email or '' }}" required aria-required="true" maxlength="255" autocomplete="username" placeholder="you@example.com or username">
</div>
<div class="auth-field">
+1 -1
View File
@@ -189,7 +189,7 @@
<button type="button" class="btn btn-sm btn-primary" data-regen-api-key>Regenerate</button>
{% endif %}
</div>
<p class="api-key-hint">Use this key with <code>X-API-KEY</code>, <code>Authorization: Bearer</code>, or HTTP Basic auth on any request. {% if is_owner %}Regenerating immediately invalidates the old key.{% endif %}</p>
<p class="api-key-hint">Use this key with <code>X-API-KEY</code> or <code>Authorization: Bearer</code> on any request (clients usually carry it in the <code>DEVPLACE_API_KEY</code> environment variable). HTTP Basic uses your username or email plus password instead. {% if is_owner %}Regenerating immediately invalidates the old key.{% endif %}</p>
</div>
{% endif %}