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
+2 -2
View File
@@ -12,7 +12,7 @@ The completion contract for every change is [DEFINITION_OF_DONE.md](./DEFINITION
DevPlace is a server-rendered social network for developers. FastAPI backend serves Jinja2 templates with pure ES6 module JavaScript on the frontend. SQLite via the `dataset` library (auto-syncs schema). No JS framework, no NPM, no JWT.
- **Database:** `dataset` (auto-syncs schema, uses `uid` for PKs). SQLite.
- **Auth:** `session` cookie, plus `X-API-KEY` / `Authorization: Bearer <api_key>` / HTTP Basic (username-or-email:password) - all resolved in `get_current_user`. PBKDF2-SHA256 via passlib. No JWT. Every user has an `api_key` (uuid7), set at signup and backfilled in `init_db`/`devplace apikey backfill`. Docs site at `/docs` (`routers/docs/` package, `DOCS_PAGES` registry; FastAPI's Swagger is moved to `/swagger` so `/docs` is free).
- **Auth:** three account credentials: username+password, email+password, personal `api_key`. All password exchanges (`POST /auth/login` form+JSON, `POST /auth/token`, HTTP Basic, devRant `POST /api/users/auth-token`) take username-or-email as identifier (username case-sensitive, email lowered); the `api_key` rides `X-API-KEY` / `Authorization: Bearer` (client-side `DEVPLACE_API_KEY` env var holds its value, injected into containers) plus `session` cookie - all resolved in `get_current_user` (order: session, X-API-KEY, Bearer, Basic; headers also try DevRant/access tokens). Every JSON return of the personal key also returns `username`+`email` (login/signup `data`, gated `ProfileOut.email` beside `api_key`, regenerate), so `GET /profile` with an API key is the whoami/account fetch; never add `email` to public `UserOut`. PBKDF2-SHA256 via passlib. No JWT. Every user has an `api_key` (uuid7), set at signup and backfilled in `init_db`/`devplace apikey backfill`. Docs site at `/docs` (`routers/docs/` package, `DOCS_PAGES` registry; FastAPI's Swagger is moved to `/swagger` so `/docs` is free).
- **Static:** `devplacepy/static/` mounted at `/static`; URLs are boot-versioned (`/static/v<ts>/...`) via `static_url`/`assetUrl` and served immutable for a year.
- **Templates:** `devplacepy/templates/`. Shared `templates` instance from `devplacepy.templating` - all routers import from there, never instantiate their own.
- **Ports:** 10500 (dev), 10501 (tests; the serial suite uses a single uvicorn subprocess).
@@ -158,7 +158,7 @@ Server content renders on the backend for SEO (`render_content`/`render_title` i
### Auth
Session cookies named `session`, value a 64-char hex token. Passwords hashed with `pbkdf2_sha256` via passlib. `get_current_user(request)` returns user dict or `None`, per-process TTL cache (300s) keyed by token. `require_user(request)` raises a 303 redirect to `/` for guests; `require_admin(request)` redirects to `/feed` for non-admins. Public pages use `get_current_user` so guests can browse - POSTs are all guarded by `require_user`.
Session cookies named `session`, value a 64-char hex token. Passwords hashed with `pbkdf2_sha256` via passlib. `get_current_user(request)` returns user dict or `None`, per-process TTL cache (300s) keyed by token. `require_user(request)` raises a 303 redirect to `/` for guests; `require_admin(request)` redirects to `/feed` for non-admins. Public pages use `get_current_user` so guests can browse - POSTs are all guarded by `require_user`. Password exchanges (`routers/auth/login.py`, `routers/auth/token.py`) reuse the `LoginForm.email` field as username-or-email: look up `email=identifier.lower()` first, then `username=identifier` un-lowered (mirroring `_user_from_basic` semantics); never lower the identifier before the username lookup.
### Database
+14 -7
View File
@@ -351,13 +351,20 @@ accepts three header-based methods, resolved centrally in `get_current_user`
Every user has an `api_key` (a uuid7), set at signup and backfilled for existing
users on startup (and via `devplace apikey backfill`). The key is shown on the
profile page to its owner (and to admins for any user) with a live **Regenerate**
button; regenerating invalidates the old key immediately. A successful JSON
`POST /auth/login` or `POST /auth/signup` also returns the account's `email`,
`api_key`, and `is_admin` flag, and `GET /profile/{username}` as JSON reports
`profile_is_admin` plus the key (null unless the viewer owns the profile or is
an admin). Invalid credentials return `401`; requests with no credentials behave
as anonymous (browser redirect to login). Full details and copy-paste `curl`
examples live at `/docs/authentication.html`.
button; regenerating invalidates the old key immediately. The three account
credentials are username+password, email+password, and the personal API key: the
login form, JSON `POST /auth/login`, `POST /auth/token`, and HTTP Basic all accept
the username or the email address as the password identifier (usernames are
case-sensitive, email addresses are not), and clients conventionally carry the API
key in the `DEVPLACE_API_KEY` environment variable. Every JSON response that returns
the personal API key returns the account's `username` and `email` alongside it:
login/signup (`data`), `POST /profile/regenerate-api-key`, and the profile JSON
(`profile_user.username`, `email`, `api_key`; key and email null unless the viewer
owns the profile or is an admin). So a client holding only an API key fetches its
account in one call: `GET /profile` with `X-API-KEY` and `Accept: application/json`.
Invalid credentials return `401`; requests with no credentials behave as anonymous
(browser redirect to login). Full details and copy-paste `curl` examples live at
`/docs/authentication.html`.
```bash
curl -H "X-API-KEY: <your-key>" https://your-host/notifications
+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 %}
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "devplacepy"
version = "1.1.19"
version = "1.1.20"
description = "DevPlace - The Developer Social Network"
requires-python = ">=3.12"
dependencies = [
+119
View File
@@ -273,3 +273,122 @@ def test_login_failure_json_leaks_no_key(app_server):
)
assert response.status_code == 401
assert "api_key" not in response.text
def _member_mixed_case():
_counter_audit_log[0] += 1
name = f"AuMix{int(time.time() * 1000)}{_counter_audit_log[0]}"
s = requests.Session()
s.post(
f"{BASE_URL}/auth/signup",
data={
"username": name,
"email": f"{name.lower()}@t.dev",
"password": "secret123",
"confirm_password": "secret123",
"birth_date": "1990-01-01",
"accept_terms": "1",
},
allow_redirects=True,
)
return s, name
def test_login_json_accepts_username(seeded_db):
_, name = _member()
row = _db_user(name)
response = requests.post(
f"{BASE_URL}/auth/login",
headers=JSON_audit_log,
data={"email": name, "password": "secret123"},
allow_redirects=False,
)
assert response.status_code == 200, response.text[:300]
body = response.json()
assert body["ok"] is True
assert body["data"]["username"] == name
assert body["data"]["email"] == f"{name}@t.dev"
assert body["data"]["api_key"] == row["api_key"]
def test_login_form_accepts_username(seeded_db):
_, name = _member()
session = requests.Session()
response = session.post(
f"{BASE_URL}/auth/login",
data={"email": name, "password": "secret123"},
allow_redirects=False,
)
assert response.status_code in (200, 302, 303), response.text[:300]
assert session.cookies.get("session")
profile = session.get(f"{BASE_URL}/profile", allow_redirects=False)
assert profile.status_code == 200, profile.text[:300]
def test_login_json_accepts_mixed_case_username(seeded_db):
_, name = _member_mixed_case()
response = requests.post(
f"{BASE_URL}/auth/login",
headers=JSON_audit_log,
data={"email": name, "password": "secret123"},
allow_redirects=False,
)
assert response.status_code == 200, response.text[:300]
body = response.json()
assert body["data"]["username"] == name
assert body["data"]["email"] == f"{name.lower()}@t.dev"
assert body["data"]["api_key"]
def test_login_json_accepts_uppercase_email(seeded_db):
_, name = _member()
response = requests.post(
f"{BASE_URL}/auth/login",
headers=JSON_audit_log,
data={"email": f"{name.upper()}@T.DEV", "password": "secret123"},
allow_redirects=False,
)
assert response.status_code == 200, response.text[:300]
assert response.json()["data"]["username"] == name
def test_login_wrong_password_for_username_leaks_no_key(seeded_db):
_, name = _member()
response = requests.post(
f"{BASE_URL}/auth/login",
headers=JSON_audit_log,
data={"email": name, "password": "wrongpassword"},
allow_redirects=False,
)
assert response.status_code == 401
assert "api_key" not in response.text
def test_api_key_profile_returns_account_info(seeded_db):
_, name = _member()
row = _db_user(name)
response = requests.get(
f"{BASE_URL}/profile",
headers={**JSON_audit_log, "X-API-KEY": row["api_key"]},
allow_redirects=False,
)
assert response.status_code == 200, response.text[:300]
body = response.json()
assert body["api_key"] == row["api_key"]
assert body["email"] == f"{name}@t.dev"
assert body["profile_user"]["username"] == name
assert body["profile_user"]["uid"] == row["uid"]
def test_bearer_api_key_profile_returns_account_info(seeded_db):
_, name = _member()
row = _db_user(name)
response = requests.get(
f"{BASE_URL}/profile",
headers={**JSON_audit_log, "Authorization": f"Bearer {row['api_key']}"},
allow_redirects=False,
)
assert response.status_code == 200, response.text[:300]
body = response.json()
assert body["email"] == f"{name}@t.dev"
assert body["profile_user"]["username"] == name
+35
View File
@@ -58,6 +58,41 @@ def test_token_accepts_username_as_identifier(app_server):
assert r.json()["access_token"]
def _signup_mixed_case(password="secret123"):
_counter_token[0] += 1
name = f"TokMix{int(time.time() * 1000)}{_counter_token[0]}"
email = f"{name.lower()}@t.dev"
requests.post(
f"{BASE_URL}/auth/signup",
data={
"username": name,
"email": email,
"password": password,
"confirm_password": password,
"birth_date": "1990-01-01",
"accept_terms": "1",
},
allow_redirects=True,
)
return name, email, password
def test_token_accepts_mixed_case_username(app_server):
name, email, password = _signup_mixed_case()
r = requests.post(f"{BASE_URL}/auth/token", data={"email": name, "password": password})
assert r.status_code == 200, r.text[:300]
assert r.json()["access_token"]
def test_token_accepts_uppercase_email(app_server):
name, email, password = _signup()
r = requests.post(
f"{BASE_URL}/auth/token", data={"email": email.upper(), "password": password}
)
assert r.status_code == 200, r.text[:300]
assert r.json()["access_token"]
def test_token_via_json_body(app_server):
name, email, password = _signup()
r = requests.post(
+35
View File
@@ -762,4 +762,39 @@ def test_stranger_gets_no_key(app_server, seeded_db):
assert body["api_key"] is None
def test_owner_gets_email_alongside_key(app_server, seeded_db):
session, name = _privacy_member("keye")
body = _profile_json_body(session, name)
assert body["can_view_api_key"] is True
assert body["api_key"]
assert body["email"] == f"{name}@t.dev"
assert body["profile_user"]["username"] == name
def test_admin_gets_email_alongside_member_key(app_server, seeded_db):
_, name = _privacy_member("keym")
body = _profile_json_body(_admin_session(), name)
assert body["can_view_api_key"] is True
assert body["api_key"]
assert body["email"] == f"{name}@t.dev"
def test_stranger_gets_no_email(app_server, seeded_db):
_, name = _privacy_member("keyn")
stranger, _ = _privacy_member("keyw")
body = _profile_json_body(stranger, name)
assert body["can_view_api_key"] is False
assert body["api_key"] is None
assert body["email"] is None
def test_guest_gets_no_email(app_server, seeded_db):
body = requests.get(
f"{BASE_URL}/profile/alice_test",
headers={"Accept": "application/json"},
).json()
assert body["can_view_api_key"] is False
assert body["email"] is None
+10
View File
@@ -51,3 +51,13 @@ def test_regenerate_invalidates_old_key(app_server):
allow_redirects=False,
)
assert new.status_code in (302, 200)
def test_regenerate_returns_username_and_email(app_server):
session, name, email, _ = _signup_api_auth()
resp = session.post(f"{BASE_URL}/profile/regenerate-api-key")
assert resp.status_code == 200, resp.text[:300]
body = resp.json()
assert body["api_key"]
assert body["username"] == name
assert body["email"] == email
+8
View File
@@ -204,6 +204,14 @@ def test_login_next_redirects_to_target(page, app_server, seeded_db):
page.wait_for_url("**/gists", wait_until="domcontentloaded")
def test_login_with_username(page, app_server, seeded_db):
page.goto(f"{BASE_URL}/auth/login?next=/gists", wait_until="domcontentloaded")
page.fill("#email", seeded_db["alice"]["username"])
page.fill("#password", seeded_db["alice"]["password"])
page.click("button:has-text('Sign in')")
page.wait_for_url("**/gists", wait_until="domcontentloaded")
def test_login_next_rejects_external(page, app_server, seeded_db):
page.goto(
f"{BASE_URL}/auth/login?next=https://evil.example.com",