"""Mountable HTTP route handlers for `/api/fauth/*` across FleetMesh web services."""
from __future__ import annotations
from typing import Any, Dict, Optional
from urllib.parse import parse_qs
from fleetmesh_auth.engine import FleetmeshAuthEngine
from fleetmesh_auth.errors import refusal
from fleetmesh_auth.principal import resolve_widget_config
from fleetmesh_auth.ui_widget import render_auth_widget_js
# Registration refusals that mean "fix the form", answered 400; the rest
# (a provider or method switched off, a provider bug) are answered 401.
REGISTER_VALIDATION_ERRORS = frozenset({
"handle_taken", "invalid_handle", "weak_password", "invalid_email",
"provider_required", "unknown_provider", "registration_unsupported",
})
# Handle-check refusals that mean "fix the request", answered 400; the rest
# (provider switched off, a provider bug or its store down) are answered 401.
HANDLE_CHECK_VALIDATION_ERRORS = frozenset({
"provider_required", "unknown_provider", "handle_check_unsupported", "registration_unsupported",
})
[docs]def handle_fauth_get(
handler: Any,
engine: FleetmeshAuthEngine,
path: str,
query_string: str = "",
) -> bool:
"""Handle `GET /api/fauth/*` requests on a BaseHTTPRequestHandler-compatible handler.
Returns ``True`` if the path matched `/api/fauth/*` and a response was sent.
"""
if not path.startswith("/api/fauth/"):
return False
qs = parse_qs(query_string or "")
preset = (qs.get("preset") or ["standard"])[0]
if path == "/api/fauth/config":
cfg = engine.get_widget_config(preset=preset)
handler._send_json(200, {"ok": True, "config": cfg})
return True
if path == "/api/fauth/providers":
handler._send_json(200, {"ok": True, "providers": engine.list_providers()})
return True
if path == "/api/fauth/challenge":
domain = (qs.get("domain") or [engine.domain])[0]
res = engine.issue_challenge(domain=domain)
handler._send_json(200, res)
return True
if path == "/api/fauth/session":
token = (qs.get("token") or [""])[0] or extract_request_token(handler)
req_role = (qs.get("required_role") or [None])[0]
res = engine.verify_session(token, required_role=req_role)
handler._send_json(200 if res.get("ok") else 401, res)
return True
if path == "/api/fauth/register/check":
provider_id = (qs.get("provider") or qs.get("provider_id") or [""])[0]
handle = (qs.get("handle") or qs.get("username") or [""])[0]
res = engine.check_handle(provider_id, handle, app_preset=preset)
if res.get("ok"):
status = 200
elif res.get("error") in HANDLE_CHECK_VALIDATION_ERRORS:
status = 400
else:
status = 401
handler._send_json(status, res)
return True
if path == "/api/fauth/widget.js":
cfg = resolve_widget_config(preset)
js_body = render_auth_widget_js(cfg).encode("utf-8")
handler.send_response(200)
handler.send_header("Content-Type", "application/javascript; charset=utf-8")
handler.send_header("Content-Length", str(len(js_body)))
handler.send_header("Cache-Control", "no-store")
apply_cors_headers(handler)
handler.end_headers()
handler.wfile.write(js_body)
return True
handler._send_json(404, refusal("unknown_fauth_endpoint", path=path))
return True
[docs]def handle_fauth_post(
handler: Any,
engine: FleetmeshAuthEngine,
path: str,
payload: Dict[str, Any],
) -> bool:
"""Handle `POST /api/fauth/*` requests on a BaseHTTPRequestHandler-compatible handler.
Returns ``True`` if the path matched `/api/fauth/*` and a response was sent.
"""
if not path.startswith("/api/fauth/"):
return False
body = payload or {}
if path == "/api/fauth/challenge":
domain = str(body.get("domain") or engine.domain)
res = engine.issue_challenge(domain=domain)
handler._send_json(200, res)
return True
if path in ("/api/fauth/login", "/api/fauth/verify"):
preset = str(body.get("app_preset") or body.get("preset") or "standard")
req_role = body.get("required_role")
res = engine.authenticate(
body,
app_preset=preset,
required_role=str(req_role) if req_role else None,
)
status = 200 if res.get("ok") else 401
handler._send_json(status, res)
return True
if path == "/api/fauth/register":
preset = str(body.get("app_preset") or body.get("preset") or "standard")
res = engine.register(body, app_preset=preset)
if res.get("ok"):
status = 200
elif res.get("error") in REGISTER_VALIDATION_ERRORS:
status = 400
else:
status = 401
handler._send_json(status, res)
return True
if path == "/api/fauth/logout":
token = extract_request_token(handler, body)
res = engine.revoke_session(token)
handler._send_json(200, res)
return True
handler._send_json(404, refusal("unknown_fauth_endpoint", path=path))
return True