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:
1 parent
17b48f25e8
commit
4b3e5f0932
47 files changed
+4189
-862
No files matched your search
@@ -0,0 +1,125 @@
|
||||
import logging
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
import ledger
|
||||
from cashbook_app import config
|
||||
from cashbook_app.db.models import Base
|
||||
from cashbook_app.db.session import get_engine, get_session_factory
|
||||
from cashbook_app.routers.auth_routes import router as auth_router
|
||||
from cashbook_app.routers.books import router as books_router
|
||||
from cashbook_app.routers.frontend import router as frontend_router
|
||||
from cashbook_app.routers.statements import router as statements_router
|
||||
from cashbook_app.routers.users_admin import router as users_router
|
||||
from cashbook_app.services import accounts, spreadsheets
|
||||
|
||||
log = logging.getLogger("cashbook")
|
||||
|
||||
|
||||
class _SkipHealthChecks(logging.Filter):
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
return "/healthz" not in record.getMessage()
|
||||
|
||||
|
||||
logging.getLogger("uvicorn.access").addFilter(_SkipHealthChecks())
|
||||
|
||||
SECURITY_HEADERS = {
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"X-Frame-Options": "DENY",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
"Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; "
|
||||
"style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'",
|
||||
}
|
||||
|
||||
|
||||
def _bootstrap_admin() -> None:
|
||||
"""First run: create an admin from BOOTSTRAP_ADMIN_USERNAME/PASSWORD if there are no users."""
|
||||
username = os.environ.get("BOOTSTRAP_ADMIN_USERNAME", "").strip()
|
||||
password = os.environ.get("BOOTSTRAP_ADMIN_PASSWORD", "").strip()
|
||||
if not (accounts.auth_enabled() and username and password):
|
||||
return
|
||||
db = get_session_factory()()
|
||||
try:
|
||||
if accounts.count_users(db) == 0:
|
||||
accounts.create_user(db, username, password, is_superuser=True)
|
||||
log.warning("Created administrator %r from BOOTSTRAP_ADMIN_USERNAME", username)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def _migrate_spreadsheets() -> None:
|
||||
"""Copy any .ods cashbooks left in the data folder into the database (once each)."""
|
||||
if not any(f.endswith(".ods") and f != "template.ods" for f in os.listdir(config.data_dir())):
|
||||
return
|
||||
from migrate import migrate_folder
|
||||
conn = ledger.connect(config.database_path())
|
||||
try:
|
||||
for message in migrate_folder(conn, str(config.data_dir()), spreadsheets.office().open):
|
||||
log.warning(message)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
Base.metadata.create_all(bind=get_engine())
|
||||
ledger.connect(config.database_path()).close() # create / upgrade the books tables
|
||||
_bootstrap_admin()
|
||||
_migrate_spreadsheets()
|
||||
if not accounts.auth_enabled():
|
||||
log.warning("AUTH_ENABLED=false: anyone who can reach this server can see and change the books")
|
||||
yield
|
||||
spreadsheets.stop()
|
||||
|
||||
|
||||
def _same_origin(request: Request) -> bool:
|
||||
"""Refuse state-changing requests made from other websites.
|
||||
|
||||
Compares the Origin's host name (ports differ behind Docker and proxies) with Host,
|
||||
X-Forwarded-Host and CASHBOOK_ALLOWED_HOSTS.
|
||||
"""
|
||||
origin = request.headers.get("origin")
|
||||
if not origin:
|
||||
return True
|
||||
host_of = lambda h: urlparse("//" + h.strip()).hostname
|
||||
allowed = {"localhost", "127.0.0.1", "::1"} | config.allowed_hosts()
|
||||
for h in [request.headers.get("host", "")] + request.headers.get("x-forwarded-host", "").split(","):
|
||||
if h.strip():
|
||||
allowed.add(host_of(h))
|
||||
if urlparse(origin).hostname in allowed:
|
||||
return True
|
||||
log.warning("Refused %s %s: Origin %s is not one of %s; add it to CASHBOOK_ALLOWED_HOSTS if it's yours",
|
||||
request.method, request.url.path, origin, sorted(allowed))
|
||||
return False
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
app = FastAPI(title="Cashbook", lifespan=lifespan, docs_url=None, redoc_url=None)
|
||||
|
||||
@app.middleware("http")
|
||||
async def security(request: Request, call_next):
|
||||
if request.method not in ("GET", "HEAD", "OPTIONS") and not _same_origin(request):
|
||||
return JSONResponse({"detail": "Refused: this page's address doesn't match the server's. "
|
||||
"See the server log, or set CASHBOOK_ALLOWED_HOSTS."}, status_code=403)
|
||||
response = await call_next(request)
|
||||
for k, v in SECURITY_HEADERS.items():
|
||||
response.headers.setdefault(k, v)
|
||||
if request.url.path.startswith("/api/"):
|
||||
response.headers.setdefault("Cache-Control", "no-store")
|
||||
return response
|
||||
|
||||
app.mount("/static", StaticFiles(directory=str(config.STATIC_DIR)), name="static")
|
||||
app.include_router(frontend_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(users_router)
|
||||
app.include_router(books_router)
|
||||
app.include_router(statements_router)
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
Reference in new issue
Block a user