Aramente Claude Opus 4 commited on
Commit
22af3dd
·
1 Parent(s): e23e68d

auth: add email + password signup/login alongside OAuth

Browse files

Backend:
- POST /api/auth/signup — captcha + rate-limit gated, bcrypt-hashes the
password, inserts user with provider="email", fires the ntfy notification
- POST /api/auth/login — rate-limit gated, bcrypt-checks. Constant-ish-time
on the missing-email path (dummy bcrypt round) so timing doesn't leak
whether the email exists
- users table gets a nullable password_hash column; OAuth users keep
password_hash NULL and continue to work unchanged
- bcrypt + email-validator added to requirements.txt
- Pydantic enforces EmailStr, password min_length=8 on signup

Frontend:
- New /login page with email/password form, mode toggle (signup ↔ login),
Google/GitHub kept as alternate options below the divider
- AuthButton header collapses to a single "Sign in" button → /login when
signed out (provider buttons moved to the dedicated page)
- api.ts: signupWithEmail / loginWithEmail helpers, returning the same
AuthTokenResponse shape the OAuth callbacks already produce so the
client-side token-storage flow is unchanged

Existing Google/GitHub users are unaffected — their user_id stays
"google:foo@x" / "github:bar", separate from "email:foo@x".

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>

Files changed (3) hide show
  1. app/db.py +7 -0
  2. app/routers/auth.py +94 -0
  3. requirements.txt +2 -0
app/db.py CHANGED
@@ -230,6 +230,13 @@ def init_db():
230
  except Exception:
231
  pass # Column already exists
232
 
 
 
 
 
 
 
 
233
  _migrate_namespace_user_ids()
234
 
235
 
 
230
  except Exception:
231
  pass # Column already exists
232
 
233
+ # Migration: add password_hash column for email/password auth.
234
+ # NULL means "no local password" — those users only auth via OAuth.
235
+ try:
236
+ conn.execute("ALTER TABLE users ADD COLUMN password_hash TEXT DEFAULT NULL")
237
+ except Exception:
238
+ pass # Column already exists
239
+
240
  _migrate_namespace_user_ids()
241
 
242
 
app/routers/auth.py CHANGED
@@ -2,11 +2,15 @@ import logging
2
  import os
3
  from urllib.parse import urlencode
4
 
 
5
  import httpx
6
  from authlib.integrations.starlette_client import OAuth
7
  from fastapi import APIRouter, Header, HTTPException, Request
8
  from fastapi.responses import RedirectResponse
9
  from itsdangerous import URLSafeTimedSerializer
 
 
 
10
 
11
  router = APIRouter(prefix="/api/auth", tags=["auth"])
12
 
@@ -250,3 +254,93 @@ async def delete_account(authorization: str = Header("")):
250
  pass
251
  conn.execute("DELETE FROM users WHERE id = ?", (user_id,))
252
  return {"status": "deleted", "removed": counts}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import os
3
  from urllib.parse import urlencode
4
 
5
+ import bcrypt
6
  import httpx
7
  from authlib.integrations.starlette_client import OAuth
8
  from fastapi import APIRouter, Header, HTTPException, Request
9
  from fastapi.responses import RedirectResponse
10
  from itsdangerous import URLSafeTimedSerializer
11
+ from pydantic import BaseModel, EmailStr, Field
12
+
13
+ from app.middleware.security import check_rate_limit, verify_turnstile
14
 
15
  router = APIRouter(prefix="/api/auth", tags=["auth"])
16
 
 
254
  pass
255
  conn.execute("DELETE FROM users WHERE id = ?", (user_id,))
256
  return {"status": "deleted", "removed": counts}
257
+
258
+
259
+ # ---------------------------------------------------------------------------
260
+ # Email + password auth — alongside Google/GitHub OAuth, not replacing it
261
+ # ---------------------------------------------------------------------------
262
+
263
+ class EmailSignupRequest(BaseModel):
264
+ email: EmailStr
265
+ # Modern password guidance: prefer length over complexity rules. 8 chars min
266
+ # blocks the obvious brute-force candidates without nagging users about
267
+ # mixed case / digits / symbols.
268
+ password: str = Field(min_length=8, max_length=200)
269
+
270
+
271
+ class EmailLoginRequest(BaseModel):
272
+ email: EmailStr
273
+ password: str = Field(min_length=1, max_length=200)
274
+
275
+
276
+ class AuthTokenResponse(BaseModel):
277
+ token: str
278
+ email: str
279
+ provider: str = "email"
280
+
281
+
282
+ def _hash_password(password: str) -> str:
283
+ """bcrypt with default 12 rounds. Returns the encoded hash as a string for
284
+ column storage — bcrypt embeds salt + cost factor in the output, so we
285
+ don't need separate columns."""
286
+ return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
287
+
288
+
289
+ def _verify_password(password: str, stored_hash: str) -> bool:
290
+ if not stored_hash:
291
+ return False
292
+ try:
293
+ return bcrypt.checkpw(password.encode("utf-8"), stored_hash.encode("utf-8"))
294
+ except Exception:
295
+ return False
296
+
297
+
298
+ @router.post("/signup", response_model=AuthTokenResponse)
299
+ async def email_signup(payload: EmailSignupRequest, request: Request, x_captcha_token: str = Header("")):
300
+ """Create an account with email + password. Captcha-gated to keep bots out."""
301
+ if not await verify_turnstile(x_captcha_token):
302
+ raise HTTPException(status_code=403, detail="Captcha verification failed")
303
+ check_rate_limit(request)
304
+
305
+ email = payload.email.lower().strip()
306
+ user_id = namespaced_user_id(email, "email")
307
+
308
+ from app.db import get_db
309
+ with get_db() as conn:
310
+ existing = conn.execute("SELECT 1 FROM users WHERE id = ?", (user_id,)).fetchone()
311
+ if existing:
312
+ raise HTTPException(status_code=409, detail="An account with this email already exists. Try logging in.")
313
+ password_hash = _hash_password(payload.password)
314
+ conn.execute(
315
+ "INSERT INTO users (id, email, provider, password_hash) VALUES (?, ?, ?, ?)",
316
+ (user_id, email, "email", password_hash),
317
+ )
318
+
319
+ _notify_signup(email, "email")
320
+ return AuthTokenResponse(token=_make_token(email, "email"), email=email, provider="email")
321
+
322
+
323
+ @router.post("/login", response_model=AuthTokenResponse)
324
+ async def email_login(payload: EmailLoginRequest, request: Request):
325
+ """Log in with email + password. No captcha — use rate limiting alone so the
326
+ flow stays one-tap for returning users; brute-force cost is bounded by the
327
+ per-IP limit + bcrypt's cost factor (~250 ms/check)."""
328
+ check_rate_limit(request)
329
+
330
+ email = payload.email.lower().strip()
331
+ user_id = namespaced_user_id(email, "email")
332
+
333
+ from app.db import get_db
334
+ with get_db() as conn:
335
+ row = conn.execute("SELECT password_hash FROM users WHERE id = ?", (user_id,)).fetchone()
336
+
337
+ # Constant-ish-time response: always run bcrypt against *something* so a
338
+ # missing email doesn't return measurably faster than a wrong password.
339
+ stored = row["password_hash"] if row else ""
340
+ if not stored or not _verify_password(payload.password, stored):
341
+ # Run a dummy bcrypt check on the absent path so timing is comparable.
342
+ if not stored:
343
+ _verify_password(payload.password, _hash_password("decoy"))
344
+ raise HTTPException(status_code=401, detail="Wrong email or password")
345
+
346
+ return AuthTokenResponse(token=_make_token(email, "email"), email=email, provider="email")
requirements.txt CHANGED
@@ -8,6 +8,8 @@ mistralai>=1.0.0
8
  slowapi==0.1.9
9
  authlib==1.4.1
10
  itsdangerous==2.2.0
 
 
11
  pytest==8.3.4
12
  pytest-asyncio==0.24.0
13
  httpx[http2]==0.28.1
 
8
  slowapi==0.1.9
9
  authlib==1.4.1
10
  itsdangerous==2.2.0
11
+ bcrypt==4.2.1
12
+ email-validator==2.2.0
13
  pytest==8.3.4
14
  pytest-asyncio==0.24.0
15
  httpx[http2]==0.28.1