Files
davidandClaude Opus 5.5 1bb2a299c7 Add Coremarket: Federated Core VM sizing and cloud pricing app
Dockerised FastAPI web app that sizes a VM for a selection of Federated
Computer apps (Base/Good/Better/Best tiers or custom) and prices it across
14 cloud providers and ~250 regions, grouped by continent.

- Sizing model per app with shared databases, headroom and disk growth
- Live pricing from Vultr, Akamai/Linode and Azure (DigitalOcean and
  Hetzner with tokens); dated catalog for the rest
- Hand-maintained Contabo price sheet with editor and table paste,
  including the one-time setup fee
- HIPAA/SOC2/PCI DSS/GDPR status, SMTP port 25, IPv4 and egress notes
- Estimated latency to 40 cities, real RTT via Globalping probes
- Versioned REST API (/api/v1) with OpenAPI docs and CSV export
- Accounts with admin/user roles, first admin from ADMIN_USERNAME /
  ADMIN_PASSWORD, per-account API keys, SQLite storage

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:36:51 -07:00

134 lines
5.4 KiB
Python

"""Sign-in, account management and API-key endpoints (mounted under /api/v1)."""
from __future__ import annotations
from typing import Literal
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from pydantic import BaseModel, Field
from app import auth
router = APIRouter(prefix="/api/v1")
def _ip(request: Request) -> str:
return request.client.host if request.client else "?"
# ------------------------------------------------------------------ models
class LoginRequest(BaseModel):
username: str
password: str
class PasswordChange(BaseModel):
current_password: str
new_password: str = Field(min_length=auth.MIN_PASSWORD)
class NewUser(BaseModel):
username: str = Field(examples=["alice"])
password: str = Field(min_length=auth.MIN_PASSWORD)
role: Literal["admin", "user"] = "user"
class UserUpdate(BaseModel):
role: Literal["admin", "user"] | None = None
disabled: bool | None = None
password: str | None = Field(None, min_length=auth.MIN_PASSWORD, description="Set a new password (signs the user out everywhere)")
class NewKey(BaseModel):
name: str = Field("API key", max_length=100, examples=["CI pipeline"])
expires_days: int | None = Field(None, ge=1, le=3650, description="Omit for a key that never expires")
user_id: int | None = Field(None, description="Admin only: create the key for another account")
# ------------------------------------------------------------------ sign-in
@router.post("/auth/login", tags=["auth"], summary="Sign in (sets a session cookie)")
def login(req: LoginRequest, request: Request, response: Response):
token, user = auth.login(req.username.strip(), req.password, _ip(request))
response.set_cookie(auth.SESSION_COOKIE, token, max_age=int(auth.SESSION_HOURS * 3600), httponly=True,
samesite="lax", secure=auth.COOKIE_SECURE, path="/")
return dict(user=user)
@router.post("/auth/logout", tags=["auth"], summary="Sign out")
def logout(request: Request, response: Response):
auth.logout(request.cookies.get(auth.SESSION_COOKIE))
response.delete_cookie(auth.SESSION_COOKIE, path="/")
return dict(ok=True)
@router.get("/auth/me", tags=["auth"], summary="The signed-in account (or the API key's owner)")
def me(user: dict = Depends(auth.current_user)):
return {k: v for k, v in user.items() if k != "token_hash"}
@router.post("/auth/password", tags=["auth"], summary="Change your own password (signs out your other sessions)")
def change_password(req: PasswordChange, user: dict = Depends(auth.current_user)):
auth.change_own_password(user, req.current_password, req.new_password, user.get("token_hash"))
return dict(ok=True)
# ------------------------------------------------------------------ users (admin)
@router.get("/users", tags=["users"], summary="List accounts (admin)", dependencies=[Depends(auth.require_admin)])
def list_users():
return auth.list_users()
@router.post("/users", tags=["users"], summary="Create an account (admin)", status_code=201)
def create_user(req: NewUser, admin: dict = Depends(auth.require_admin)):
return auth.create_user(req.username.strip(), req.password, req.role)
@router.get("/users/{user_id}", tags=["users"], summary="One account (admin)", dependencies=[Depends(auth.require_admin)])
def get_user(user_id: int):
return auth.get_user(user_id)
@router.patch("/users/{user_id}", tags=["users"], summary="Change role, disable/enable, or reset password (admin)")
def update_user(user_id: int, req: UserUpdate, admin: dict = Depends(auth.require_admin)):
return auth.update_user(user_id, admin, role=req.role, disabled=req.disabled, password=req.password)
@router.delete("/users/{user_id}", tags=["users"], summary="Delete an account and its API keys (admin)")
def delete_user(user_id: int, admin: dict = Depends(auth.require_admin)):
auth.delete_user(user_id, admin)
return dict(ok=True)
# ------------------------------------------------------------------ API keys
@router.get("/keys", tags=["api keys"], summary="List API keys (yours; admins can see all)")
def list_keys(all: bool = Query(False, description="Admin only: every account's keys"),
user_id: int | None = Query(None, description="Admin only: one account's keys"),
user: dict = Depends(auth.current_user)):
if (all or user_id is not None) and user["role"] != "admin":
raise HTTPException(403, "admin role required")
if all:
return auth.list_keys()
return auth.list_keys(user_id if user_id is not None else user["id"])
@router.post("/keys", tags=["api keys"], summary="Create an API key (the key is shown only in this response)", status_code=201)
def create_key(req: NewKey, user: dict = Depends(auth.current_user)):
owner = user["id"]
if req.user_id is not None and req.user_id != user["id"]:
if user["role"] != "admin":
raise HTTPException(403, "admin role required to create keys for other accounts")
owner = req.user_id
key, info = auth.create_key(owner, req.name, req.expires_days)
return dict(key=key, **info, username=auth.get_user(owner)["username"],
warning="Store this key now; it cannot be shown again.")
@router.delete("/keys/{key_id}", tags=["api keys"], summary="Revoke an API key (your own; admins any)")
def delete_key(key_id: int, user: dict = Depends(auth.current_user)):
auth.delete_key(key_id, user)
return dict(ok=True)