Complete FastAPI app
#Run with uvicorn app:app --port 8000 after registering http://localhost:8000/auth/ozvault/callback. Starlette's session cookie is signed but readable by the user, so it carries only state and the verifier; tokens stay in server storage (a dictionary here, your database in production). httpx's auth=(id, secret) sends HTTP Basic client authentication.
# app.py — pip install fastapi uvicorn httpx itsdangerous
import base64, hashlib, os, secrets, time
import httpx
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import RedirectResponse
from starlette.middleware.sessions import SessionMiddleware
OZVAULT = "https://ozvault.lol"
API = "https://api.ozvault.lol"
CLIENT_ID = os.environ["OZVAULT_CLIENT_ID"]
CLIENT_SECRET = os.environ["OZVAULT_CLIENT_SECRET"]
REDIRECT_URI = "http://localhost:8000/auth/ozvault/callback" # registered exactly
app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key=os.environ["SESSION_SECRET"], same_site="lax")
connections: dict[str, dict] = {} # replace with your database
@app.get("/auth/ozvault")
async def start(request: Request):
verifier, state = secrets.token_urlsafe(32), secrets.token_urlsafe(16)
request.session["oauth"] = {"state": state, "verifier": verifier}
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
query = httpx.QueryParams({
"response_type": "code",
"client_id": CLIENT_ID,
"redirect_uri": REDIRECT_URI,
"scope": "profile:read storage:quota:read storage:app:read storage:app:write offline_access",
"state": state,
"code_challenge": challenge,
"code_challenge_method": "S256",
})
return RedirectResponse(f"{OZVAULT}/oauth/authorize?{query}")
async def token_request(data: dict) -> dict:
async with httpx.AsyncClient(timeout=15) as client:
r = await client.post(f"{OZVAULT}/oauth/token", auth=(CLIENT_ID, CLIENT_SECRET), data=data)
body = r.json()
if r.status_code != 200:
raise HTTPException(502, body.get("error_description", "Token request failed"))
body["expires_at"] = time.time() + body["expires_in"]
return body
@app.get("/auth/ozvault/callback")
async def callback(request: Request, code: str | None = None, state: str | None = None,
error: str | None = None, iss: str | None = None):
saved = request.session.pop("oauth", None)
if not saved or state != saved["state"]:
raise HTTPException(400, "Invalid state")
if iss != OZVAULT:
raise HTTPException(400, "Unexpected issuer")
if error or not code:
raise HTTPException(400, "Authorization was not granted")
tokens = await token_request({"grant_type": "authorization_code", "code": code,
"redirect_uri": REDIRECT_URI, "code_verifier": saved["verifier"]})
session_id = secrets.token_urlsafe(16)
connections[session_id] = tokens
request.session["connection"] = session_id
return RedirectResponse("/quota")
async def access_token(request: Request) -> str:
tokens = connections.get(request.session.get("connection", ""))
if not tokens:
raise HTTPException(401, "Connect OzVault first")
if time.time() > tokens["expires_at"] - 60:
tokens.update(await token_request({"grant_type": "refresh_token", "refresh_token": tokens["refresh_token"]}))
return tokens["access_token"]
@app.get("/quota")
async def quota(request: Request):
token = await access_token(request)
async with httpx.AsyncClient(timeout=15) as client:
r = await client.get(f"{API}/v1/storage/quota", headers={"Authorization": f"Bearer {token}"})
return r.json()
@app.post("/backup")
async def backup(request: Request):
token = await access_token(request)
data = await request.body()
async with httpx.AsyncClient(timeout=60) as client:
r = await client.post(f"{API}/v1/app/files",
params={"name": f"backups/{int(time.time())}.bin"},
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/octet-stream"},
content=data)
if r.status_code != 201:
raise HTTPException(r.status_code, r.json()["error"]["message"])
return r.json()Clear documentation is part of the product.