Move to FastAPI with accounts, SQLite books, export and tax returns

Storage and export
- Keep books and transactions in SQLite (data/cashbook.db) instead of
  .ods files; existing .ods books are migrated once at startup
- Export a book as the cashbook spreadsheet (.xlsx/.ods, built from the
  template via LibreOffice) or as CSV
- GST rounded per transaction to match the spreadsheet

Tax
- GST return page with IRD GST101A boxes 5-15 per six-monthly,
  two-monthly or monthly period, due dates, and a Zero-rated GST type
- Income tax page with IR10 (financial statements summary) and IR4
  (company return) boxes, from the cashbook plus year-end amounts typed
  in and saved per book

FastAPI and accounts (following led-editor)
- Replace the stdlib server with a FastAPI app (src/cashbook_app) run by
  uvicorn; dependencies in Pipfile
- Cookie sessions with bcrypt passwords, first-run admin setup or
  BOOTSTRAP_ADMIN_*, invites (link or email), sign-in throttling,
  password change that signs out other sessions
- Users page for administrators: rename, reset password, promote or
  demote, delete, list and revoke invites; last admin is protected
- Replaces the shared CASHBOOK_PASSWORD basic auth; AUTH_* settings in
  .env (see .env.example)
- Docker image uses a venv with system site packages for python3-uno
- pytest suite for auth, user management, imports, GST and tax figures

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-10-24 22:43:18 +13:00
1 parent 17b48f25e8
commit 4b3e5f0932
47 files changed
+4189 -862

No files matched your search

+296
View File
@@ -0,0 +1,296 @@
"""User accounts: passwords, sessions and invites (same approach as led-editor)."""
from __future__ import annotations
import datetime as dt
import os
import secrets
import smtplib
import threading
import time
from email.message import EmailMessage
import bcrypt
from sqlalchemy import delete, func, select
from sqlalchemy.orm import Session
from cashbook_app.config import env_flag
from cashbook_app.db.models import AuthSession, InviteToken, User, utc_now
SESSION_COOKIE_NAME = "cashbook_session"
SESSION_DAYS_DEFAULT = 14
def auth_enabled() -> bool:
return env_flag("AUTH_ENABLED", True)
def register_open() -> bool:
return env_flag("AUTH_REGISTER_OPEN", True)
def invite_required() -> bool:
return env_flag("AUTH_INVITE_ONLY", True)
def session_ttl_days() -> int:
try:
return max(1, min(365, int(os.environ.get("AUTH_SESSION_DAYS", str(SESSION_DAYS_DEFAULT)))))
except ValueError:
return SESSION_DAYS_DEFAULT
# --- passwords ----------------------------------------------------------------
def hash_password(password: str) -> str:
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("ascii")
def verify_password(plain: str, hashed: str) -> bool:
try:
return bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("ascii"))
except (ValueError, TypeError):
return False
# a real hash to check against when the user doesn't exist, so timing doesn't reveal it
_DUMMY_HASH = hash_password(secrets.token_urlsafe(16))
# --- failed sign-in throttle ----------------------------------------------------
MAX_FAILURES = 5
FAILURE_WINDOW = 15 * 60 # seconds
_failures: dict[str, list[float]] = {}
_failures_lock = threading.Lock()
def _recent(key: str) -> list[float]:
cutoff = time.monotonic() - FAILURE_WINDOW
times = [t for t in _failures.get(key, []) if t > cutoff]
_failures[key] = times
return times
def login_blocked(*keys: str) -> bool:
with _failures_lock:
return any(len(_recent(k)) >= MAX_FAILURES for k in keys)
def record_failure(*keys: str) -> None:
with _failures_lock:
for k in keys:
_recent(k).append(time.monotonic())
def clear_failures(*keys: str) -> None:
with _failures_lock:
for k in keys:
_failures.pop(k, None)
# --- users ----------------------------------------------------------------------
def get_user_by_username(db: Session, username: str) -> User | None:
return db.scalars(select(User).where(func.lower(User.username) == username.strip().lower())).one_or_none()
def get_user_by_id(db: Session, user_id: int) -> User | None:
return db.get(User, user_id)
def count_users(db: Session) -> int:
return int(db.scalar(select(func.count()).select_from(User)) or 0)
def list_users(db: Session) -> list[User]:
return list(db.scalars(select(User).order_by(User.username)).all())
def create_user(db: Session, username: str, password: str, *, is_superuser: bool = False) -> User:
if get_user_by_username(db, username):
raise ValueError("Username already taken")
user = User(username=username.strip(), password_hash=hash_password(password), is_superuser=is_superuser)
db.add(user)
db.commit()
db.refresh(user)
return user
def register_user(db: Session, username: str, password: str) -> User:
"""Open registration. The very first account becomes the admin."""
return create_user(db, username, password, is_superuser=count_users(db) == 0)
def register_user_with_invite(db: Session, username: str, password: str, invite_token: str) -> User:
invite = get_valid_invite(db, invite_token)
if invite is None:
raise ValueError("Invite is invalid or expired")
user = create_user(db, username, password, is_superuser=bool(invite.grants_superuser))
invite.used_at = utc_now()
invite.consumed_by_user_id = user.id
db.commit()
return user
def authenticate(db: Session, username: str, password: str) -> User | None:
user = get_user_by_username(db, username)
if user is None:
verify_password(password, _DUMMY_HASH)
return None
if not verify_password(password, user.password_hash):
return None
user.last_login_at = utc_now()
db.commit()
return user
def _other_admins(db: Session, user_id: int) -> int:
return int(db.scalar(select(func.count()).select_from(User)
.where(User.is_superuser.is_(True), User.id != user_id)) or 0)
def update_user(db: Session, user_id: int, *, username: str | None = None,
password: str | None = None, is_superuser: bool | None = None) -> User | None:
user = get_user_by_id(db, user_id)
if user is None:
return None
if username is not None and username.strip() != user.username:
dup = get_user_by_username(db, username)
if dup is not None and dup.id != user_id:
raise ValueError("Username already taken")
user.username = username.strip()
if password is not None:
user.password_hash = hash_password(password)
delete_sessions(db, user.id) # sign them out everywhere
if is_superuser is not None:
if user.is_superuser and not is_superuser and not _other_admins(db, user_id):
raise ValueError("Cannot remove the last administrator")
user.is_superuser = is_superuser
db.commit()
db.refresh(user)
return user
def change_password(db: Session, user: User, current: str, new: str, keep_token: str | None) -> None:
if not verify_password(current, user.password_hash):
raise ValueError("Current password is wrong")
user.password_hash = hash_password(new)
delete_sessions(db, user.id, except_token=keep_token) # other devices sign in again
db.commit()
def delete_user(db: Session, user_id: int) -> bool:
user = get_user_by_id(db, user_id)
if user is None:
return False
if user.is_superuser and not _other_admins(db, user_id):
raise ValueError("Cannot delete the last administrator")
db.delete(user)
db.commit()
return True
# --- sessions ---------------------------------------------------------------------
def create_session(db: Session, user: User) -> AuthSession:
row = AuthSession(user_id=user.id, token=secrets.token_urlsafe(48),
expires_at=utc_now() + dt.timedelta(days=session_ttl_days()))
db.add(row)
# tidy up expired sessions while we're here
db.execute(delete(AuthSession).where(AuthSession.expires_at < utc_now()))
db.commit()
db.refresh(row)
return row
def get_session_user(db: Session, token: str | None) -> User | None:
if not token:
return None
row = db.scalars(select(AuthSession).where(AuthSession.token == token)).one_or_none()
if row is None or row.expires_at < utc_now():
return None
return get_user_by_id(db, row.user_id)
def delete_session(db: Session, token: str | None) -> None:
if token:
db.execute(delete(AuthSession).where(AuthSession.token == token))
db.commit()
def delete_sessions(db: Session, user_id: int, except_token: str | None = None) -> None:
stmt = delete(AuthSession).where(AuthSession.user_id == user_id)
if except_token:
stmt = stmt.where(AuthSession.token != except_token)
db.execute(stmt)
# --- invites ----------------------------------------------------------------------
def create_invite(db: Session, email: str, invited_by_user_id: int | None = None,
expires_days: int = 7, grants_superuser: bool = False) -> InviteToken:
row = InviteToken(
email=email.strip().lower(), token=secrets.token_urlsafe(36),
expires_at=utc_now() + dt.timedelta(days=max(1, min(30, int(expires_days)))),
invited_by_user_id=invited_by_user_id, grants_superuser=grants_superuser,
)
db.add(row)
db.commit()
db.refresh(row)
return row
def get_valid_invite(db: Session, token: str | None) -> InviteToken | None:
if not token:
return None
row = db.scalars(select(InviteToken).where(InviteToken.token == token.strip())).one_or_none()
if row is None or row.used_at is not None or row.expires_at < utc_now():
return None
return row
def list_pending_invites(db: Session) -> list[InviteToken]:
return list(db.scalars(select(InviteToken)
.where(InviteToken.used_at.is_(None), InviteToken.expires_at >= utc_now())
.order_by(InviteToken.created_at.desc())).all())
def revoke_invite(db: Session, invite_id: int) -> bool:
row = db.get(InviteToken, invite_id)
if row is None or row.used_at is not None:
return False
db.delete(row)
db.commit()
return True
def build_invite_url(token: str, base_url: str) -> str:
base = (os.environ.get("PUBLIC_BASE_URL") or base_url).rstrip("/")
return f"{base}/register?invite={token}"
def send_invite_email(email: str, invite_url: str) -> bool:
host = (os.environ.get("SMTP_HOST") or "").strip()
if not host:
return False
port = int((os.environ.get("SMTP_PORT") or "587").strip())
user = (os.environ.get("SMTP_USER") or "").strip()
password = os.environ.get("SMTP_PASSWORD") or ""
sender = (os.environ.get("SMTP_FROM") or user or "noreply@cashbook.local").strip()
msg = EmailMessage()
msg["Subject"] = "You're invited to the Cashbook"
msg["From"] = sender
msg["To"] = email
msg.set_content(
"You've been invited to the Cashbook.\n\n"
f"Use this link to create your account:\n{invite_url}\n\n"
"If you didn't expect this invite, you can ignore this message.\n"
)
with smtplib.SMTP(host, port, timeout=10) as smtp:
if env_flag("SMTP_TLS", True):
smtp.starttls()
if user:
smtp.login(user, password)
smtp.send_message(msg)
return True