M0: backend skeleton — Quart factory, async DB, auth, ACL spine, migrations

Foundation & Identity backend for ThoughtSync:
- Quart app factory (create_app) with /api/health + SPA history-fallback
- async SQLAlchemy 2.0 + asyncpg engine/session (lazy; boots without a DB)
- native email+password auth via signed-cookie session (register/login/logout/me
  + login_required guard); bcrypt password hashing (72-byte safe)
- multi-user sharing-ACL spine (rule 47): users, groups, group_members, and a
  polymorphic shares table + visible_to_user() SQL predicate (owner OR direct
  share OR group share) that M1's notes will scope through
- Alembic async env (adapted from family pattern) + 0001 foundation migration
- DB-free unit tests (app/health/auth-guard, password roundtrip, ACL compile)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FRgehjoz7Yv8LkUfADxACm
This commit is contained in:
2026-07-19 13:09:37 -04:00
co-authored by Claude Opus 4.8
parent cefffa2bd6
commit 04e3ab20cf
21 changed files with 734 additions and 0 deletions
+100
View File
@@ -0,0 +1,100 @@
from __future__ import annotations
import functools
import uuid
from quart import Blueprint, g, jsonify, request, session
from sqlalchemy import select
from .db import session_scope
from .models.user import User
from .security import hash_password, verify_password
bp = Blueprint("auth", __name__, url_prefix="/api/auth")
SESSION_KEY = "user_id"
MIN_PASSWORD_LEN = 8
def _serialize_user(user: User) -> dict:
return {
"id": str(user.id),
"email": user.email,
"display_name": user.display_name,
"email_verified": user.email_verified,
}
def login_required(fn):
"""Guard: 401 unless a valid session is present. Sets g.user_id for the view."""
@functools.wraps(fn)
async def wrapper(*args, **kwargs):
raw = session.get(SESSION_KEY)
if not raw:
return jsonify({"error": "authentication required"}), 401
try:
g.user_id = uuid.UUID(raw)
except (ValueError, TypeError):
session.pop(SESSION_KEY, None)
return jsonify({"error": "authentication required"}), 401
return await fn(*args, **kwargs)
return wrapper
@bp.post("/register")
async def register():
data = await request.get_json(silent=True) or {}
email = (data.get("email") or "").strip().lower()
password = data.get("password") or ""
display_name = (data.get("display_name") or "").strip()
if not email or "@" not in email:
return jsonify({"error": "a valid email is required"}), 400
if len(password) < MIN_PASSWORD_LEN:
return jsonify({"error": f"password must be at least {MIN_PASSWORD_LEN} characters"}), 400
if not display_name:
display_name = email.split("@", 1)[0]
async with session_scope() as db:
existing = await db.scalar(select(User).where(User.email == email))
if existing is not None:
return jsonify({"error": "an account with that email already exists"}), 409
user = User(email=email, password_hash=hash_password(password), display_name=display_name)
db.add(user)
await db.commit()
await db.refresh(user)
session[SESSION_KEY] = str(user.id)
return jsonify(_serialize_user(user)), 201
@bp.post("/login")
async def login():
data = await request.get_json(silent=True) or {}
email = (data.get("email") or "").strip().lower()
password = data.get("password") or ""
async with session_scope() as db:
user = await db.scalar(select(User).where(User.email == email))
if user is None or not user.password_hash or not verify_password(password, user.password_hash):
return jsonify({"error": "invalid email or password"}), 401
session[SESSION_KEY] = str(user.id)
return jsonify(_serialize_user(user))
@bp.post("/logout")
async def logout():
session.pop(SESSION_KEY, None)
return jsonify({"ok": True})
@bp.get("/me")
@login_required
async def me():
async with session_scope() as db:
user = await db.get(User, g.user_id)
if user is None:
session.pop(SESSION_KEY, None)
return jsonify({"error": "authentication required"}), 401
return jsonify(_serialize_user(user))