SPB Git

Repository Public

app.py 27.4 KB 516 lines python

1# =============================================================================2#                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : MacLustr Identity7# File             : integrations/demo-wallet/app.py8# Description      : Northbank Wallet — demo application integrating MacLustr9#                    Identity with the Python SDK (full-page redirect).10# Module           : integrations11# Repository       : https://git.spboucher.ai/maclustr-identity12# Project Website  : https://identity.spboucher.ai13# Created          : 2026-12-0114# Last Modified    : 2026-12-0115#16# Author           : Simon-Pierre Boucher17# Position         : Professor of Finance18# Institution      : Université du Québec en Outaouais (UQO)19# Organization     : SP Boucher20# Website          : https://spboucher.ai21# Git              : https://git.spboucher.ai22#23# Preferred Contact: admin@spboucher.ai24# Technical Contact: dev@spboucher.ai25# Security/Admin   : admin@spboucher.ai26#27# Copyright (c) 202628# Simon-Pierre Boucher29# All rights reserved where applicable. This file is governed by the30# applicable project license, copyright notices and relevant law.31# Existing third-party rights and notices remain unaffected.32#33# License          : None specified (no license file in this repository)34#35# Do not embed credentials, private keys, access tokens,36# certificates or confidential personal information.37#38# =============================================================================39# END OF SP BOUCHER SOURCE HEADER40# =============================================================================4142"""Northbank Wallet — demo application integrating MacLustr Identity with the Python SDK (full-page redirect).4344What it shows:45  - the secret key lives in this server process only; the browser is redirected to the hosted page, nothing else;46  - "raise the transfer limit" is refused SERVER-SIDE until the user has a valid verification;47  - the request is kept as a draft before verification (draft-before-verify) and applied afterwards;48  - a webhook endpoint with signature verification on the raw body and event-id deduplication;49  - fail closed: when the identity service cannot be reached, the gated action stays refused.5051Demo shortcuts, not for production: unsigned login cookie, JSON file as a database, /api/debug/* endpoint.52"""53from __future__ import annotations5455import html56import json57import os58import time59from contextlib import asynccontextmanager60from pathlib import Path61from typing import Any6263from fastapi import FastAPI, Request64from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response6566from maclustr_identity import AsyncMacLustrIdentity, MacLustrIdentityError, SignatureVerificationError, Verification, Webhook, parse_datetime6768DIR = Path(__file__).resolve().parent6970# ------------------------------------------------------------------ configuration (server-side only)717273def _load_env_file(path: Path) -> None:74    if not path.exists():75        return76    for line in path.read_text().splitlines():77        key, sep, value = line.strip().partition("=")78        if sep and key and not key.startswith("#"):79            os.environ.setdefault(key, value)808182_load_env_file(DIR / ".env.local")83PORT = int(os.environ.get("PORT", "8882"))84PUBLIC_URL = os.environ.get("PUBLIC_URL", f"http://localhost:{PORT}")85IDENTITY_URL = os.environ.get("MLID_BASE_URL", "http://localhost:8870")86WEBHOOK_SECRET = os.environ.get("MLID_WEBHOOK_SECRET", "")87STATE_FILE = Path(os.environ.get("DEMO_STATE_FILE", str(DIR / "data" / "state.json")))88if not os.environ.get("MLID_SECRET_KEY") or not WEBHOOK_SECRET:89    raise SystemExit("Missing MLID_SECRET_KEY / MLID_WEBHOOK_SECRET. Run ./setup.sh first.")9091STANDARD_LIMIT, VERIFIED_LIMIT = 500, 10_00092USERS = {93    "dana": {"id": "dana", "name": "Dana", "handle": "dana", "balance": 4210.55},94    "eli": {"id": "eli", "name": "Eli", "handle": "eli", "balance": 980.00},95    "farah": {"id": "farah", "name": "Farah", "handle": "farah", "balance": 15300.10},96}9798identity: AsyncMacLustrIdentity99100101@asynccontextmanager102async def lifespan(_: FastAPI):103    global identity104    identity = AsyncMacLustrIdentity(os.environ["MLID_SECRET_KEY"], base_url=IDENTITY_URL,105                                     timeout=float(os.environ.get("MLID_TIMEOUT", "5")), max_retries=int(os.environ.get("MLID_MAX_RETRIES", "1")))106    yield107    await identity.aclose()108109110app = FastAPI(title="Northbank Wallet (demo)", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)111112# ------------------------------------------------------------------ storage (a JSON file stands in for a database)113114state: dict[str, Any] = {"identity": {}, "pending_session": {}, "limit": {}, "limit_request": {}, "events": {}, "rejected_webhooks": 0}115if STATE_FILE.exists():116    state.update(json.loads(STATE_FILE.read_text()))117118119def save() -> None:120    STATE_FILE.parent.mkdir(parents=True, exist_ok=True)121    tmp = STATE_FILE.with_suffix(".tmp")122    tmp.write_text(json.dumps(state, indent=2))123    tmp.replace(STATE_FILE)124125126def external_id(user_id: str) -> str:127    """Opaque identifier sent to the identity service: no name, no e-mail."""128    return f"wl_{user_id}"129130131def user_from_external(ext: str | None) -> dict | None:132    return USERS.get(ext[3:]) if isinstance(ext, str) and ext.startswith("wl_") else None133134135def store_verification(user_id: str, v: Verification, source: str, event_created: int | None = None) -> bool:136    """The only identity data kept about a user: verification_id, status, assurance_level, expires_at."""137    created = int(time.time()) if event_created is None else event_created138    # Deliveries are at-least-once and unordered. The rules below never rely on this server's clock.139    current = state["identity"].get(user_id)140    if current and current["verification_id"] == v.verification_id:141        if current["status"] == "revoked" and v.status != "revoked":142            return False                                   # a revocation is final143        if v.status == "manual_review" and current["status"] != "manual_review":144            return False                                   # a decision never goes back "under review"145        if source == "webhook" and current["updated_by"] == "webhook" and created < current["event_created"]:146            return False                                   # older event delivered late147    elif current:148        mine, theirs = parse_datetime(v.created_at), parse_datetime(current.get("verification_created_at"))149        if mine and theirs and mine < theirs:150            return False                                   # an event about an older verification, delivered after a newer one151    state["identity"][user_id] = {"verification_id": v.verification_id, "status": v.status, "assurance_level": v.assurance_level,152                                  "expires_at": v.expires_at, "updated_by": source, "event_created": created,153                                  "verification_created_at": v.created_at or (current.get("verification_created_at") if current and current["verification_id"] == v.verification_id else None)}154    if v.status != "verified" and state["limit"].get(user_id, STANDARD_LIMIT) > STANDARD_LIMIT:155        state["limit"][user_id] = STANDARD_LIMIT           # a revoked verification takes the raised limit away156    save()157    return True158159160def session_ended(user_id: str, session_id: str | None, verification_id: str | None, event_created: int) -> None:161    """A session ended without a decision (``verification.cancelled``: cancelled by us or consent withdrawn by the162    person; ``verification.expired``). Nothing was verified: the person may simply start again.163164    The pending session is forgotten, and a record still "under review" for that same session is closed: the review165    will never conclude (consent withdrawn during the manual review). A "verified" record of an earlier session is166    left untouched.167    """168    if session_id and state["pending_session"].get(user_id) == session_id:169        state["pending_session"].pop(user_id, None)170    current = state["identity"].get(user_id)171    if current and current["status"] == "manual_review" and verification_id and current["verification_id"] == verification_id:172        current.update(status="inconclusive", assurance_level=None, updated_by="webhook", event_created=event_created)173    save()174175176def locally_verified(user_id: str) -> bool:177    r = state["identity"].get(user_id)178    if not r or r["status"] != "verified":179        return False180    exp = parse_datetime(r["expires_at"])181    return exp is None or exp.timestamp() > time.time()182183184# ------------------------------------------------------------------ the gate185186async def limit_gate(user_id: str) -> tuple[bool, int, str | None]:187    """May this user raise the transfer limit? Returns (allowed, http status, error code).188189    Two conditions, both required: our record says "verified" and is not expired, AND the identity service confirms190    right now that the verification is still valid. Failing to reach the service refuses the action: fail closed.191    """192    record = state["identity"].get(user_id)193    if not locally_verified(user_id):194        pending = bool(record and record["status"] == "manual_review")195        return False, 403, "identity_verification_pending" if pending else "identity_verification_required"196    try:197        live = await identity.verifications.status(record["verification_id"])198    except MacLustrIdentityError as e:199        print(f"[gate] identity service unavailable: {e.code}", flush=True)200        return False, 503, "identity_unavailable"201    if not live.valid:202        record.update(status=live.status, expires_at=live.expires_at, updated_by="api", event_created=int(time.time()))203        state["limit"][user_id] = STANDARD_LIMIT204        save()205        return False, 403, "identity_verification_required"206    return True, 200, None207208209async def raise_limit(user_id: str) -> tuple[int, dict]:210    """The gated action. The request is remembered first, so nothing is lost while the person verifies."""211    state["limit_request"][user_id] = VERIFIED_LIMIT       # draft before verify212    save()213    allowed, status, error = await limit_gate(user_id)214    if not allowed:215        return status, {"error": error, "limit": state["limit"].get(user_id, STANDARD_LIMIT), "requested_limit": VERIFIED_LIMIT}216    state["limit"][user_id] = VERIFIED_LIMIT217    state["limit_request"].pop(user_id, None)218    save()219    return 200, {"limit": VERIFIED_LIMIT}220221222async def start_verification(user_id: str) -> str:223    """Creates the session on the server and returns the hosted URL the browser is sent to."""224    session = await identity.verification_sessions.create(225        purpose="Raise your Northbank transfer limit", external_user_id=external_id(user_id), locale="en-CA",226        return_url=f"{PUBLIC_URL}/verify/return", metadata={"app": "demo-wallet"})227    state["pending_session"][user_id] = session.id228    save()229    return session.url230231232async def refresh_from_service(user_id: str) -> None:233    """Catch-up used on the return page, in case the webhook has not arrived yet."""234    v = await identity.is_user_verified(external_id(user_id))235    if v is None:236        sid = state["pending_session"].get(user_id)237        session = await identity.verification_sessions.retrieve(sid) if sid else None238        if session is not None and session.verification_id:239            v = await identity.verifications.retrieve(session.verification_id)240    if v is not None:241        store_verification(user_id, v, "api")242243244def me(user_id: str) -> dict:245    r = state["identity"].get(user_id)246    return {"id": user_id, "name": USERS[user_id]["name"],247            "identity": {k: r[k] for k in ("status", "assurance_level", "expires_at", "updated_by")} if r else {"status": "unverified"},248            "identity_verified": locally_verified(user_id), "limit": state["limit"].get(user_id, STANDARD_LIMIT),249            "requested_limit": state["limit_request"].get(user_id),250            # Anything but "verified" or "under review" can be retried with a new session.251            "can_start_verification": not locally_verified(user_id) and not (r and r["status"] == "manual_review"),252            "pending_session": state["pending_session"].get(user_id)}253254255def current_user(request: Request) -> dict | None:256    return USERS.get(request.cookies.get("wl_user", ""))257258259# ------------------------------------------------------------------ webhook (authenticated by its signature)260261@app.post("/webhooks/identity")262async def identity_webhook(request: Request) -> JSONResponse:263    payload = await request.body()                         # exact bytes: never a parsed model264    try:265        event = Webhook.construct_event(payload, request.headers.get("mlid-signature"), WEBHOOK_SECRET)266    except SignatureVerificationError:267        state["rejected_webhooks"] += 1268        save()269        return JSONResponse({"error": "invalid_signature"}, status_code=400)270    if event.id in state["events"]:                        # at-least-once delivery: one event id is processed once271        return JSONResponse({"received": True, "duplicate": True})272    # The signature is valid: from here on the answer is 200, even for an event type or an object this version does273    # not know (a later service version may add some). Answering an error would only make the service retry it.274    created = event.created or int(time.time())275    external, object_id = None, None276    if event.verification is not None:277        # Decision events: verified, manual_review, rejected, revoked, inconclusive (for example reason278        # ``review_not_completed``: the review was not completed in time). Only "verified" opens the gate.279        v = event.verification280        external, object_id = v.external_user_id, v.verification_id281        user = user_from_external(external)282        if user and v.verification_id:283            store_verification(user["id"], v, "webhook", created)284    elif event.session is not None:285        s = event.session286        external, object_id = s.external_user_id, s.id287        user = user_from_external(external)288        if user and event.session_ended_without_decision:289            session_ended(user["id"], s.id, s.verification_id, created)290    # Recorded last: if the processing above fails, the redelivery is processed again instead of being skipped.291    state["events"][event.id] = {"type": event.type, "external_user_id": external, "object_id": object_id, "at": created}292    save()293    return JSONResponse({"received": True})294295296# ------------------------------------------------------------------ JSON API (used by the pages' forms and by integrations/e2e)297298@app.get("/health")299async def health() -> dict:300    return {"status": "ok", "app": "demo-wallet"}301302303@app.post("/api/login")304async def api_login(request: Request) -> Response:305    body = await request.json()306    if body.get("user") not in USERS:307        return JSONResponse({"error": "unknown_user"}, status_code=400)308    resp = JSONResponse(me(body["user"]))309    resp.set_cookie("wl_user", body["user"], httponly=True, samesite="lax")310    return resp311312313@app.get("/api/me")314async def api_me(request: Request) -> JSONResponse:315    user = current_user(request)316    return JSONResponse(me(user["id"])) if user else JSONResponse({"error": "sign_in_required"}, status_code=401)317318319@app.post("/api/limit/raise")320async def api_raise(request: Request) -> JSONResponse:321    user = current_user(request)322    if not user:323        return JSONResponse({"error": "sign_in_required"}, status_code=401)324    status, body = await raise_limit(user["id"])325    return JSONResponse(body, status_code=status)326327328@app.post("/api/verify/start")329async def api_verify_start(request: Request) -> JSONResponse:330    user = current_user(request)331    if not user:332        return JSONResponse({"error": "sign_in_required"}, status_code=401)333    try:334        url = await start_verification(user["id"])335    except MacLustrIdentityError as e:336        return JSONResponse({"error": "identity_unavailable", "request_id": e.request_id}, status_code=503)337    return JSONResponse({"url": url, "session_id": state["pending_session"][user["id"]]})338339340@app.get("/api/public/profile/{handle}")341async def api_profile(handle: str) -> JSONResponse:342    user = next((u for u in USERS.values() if u["handle"] == handle), None)343    if not user:344        return JSONResponse({"error": "not_found"}, status_code=404)345    return JSONResponse({"handle": handle, "identity_verified": locally_verified(user["id"])})    # a boolean, nothing else346347348@app.get("/api/debug/events")349async def api_debug_events() -> dict:350    """Demo-only introspection used by integrations/e2e."""351    return {"events": state["events"], "rejected_webhooks": state["rejected_webhooks"]}352353354# ------------------------------------------------------------------ pages (server-rendered)355356CSS = """357:root{--bg:#0f1a17;--panel:#16241f;--line:#2b3f37;--ink:#e9f0ec;--muted:#9db0a7;--accent:#7bd389;--accent-ink:#06210f;--warn:#f0c36a;--bad:#ff9d8a}358*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,"Segoe UI",sans-serif}359a{color:var(--accent)}header{border-bottom:1px solid var(--line)}.in{max-width:720px;margin:0 auto;padding:18px 20px}360.brand{margin:0;font:700 20px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:2px;text-transform:uppercase}361.brand b{color:var(--accent)}.who{color:var(--muted);font-size:14px;margin:8px 0 0;display:flex;gap:12px;align-items:center;flex-wrap:wrap}362.panel{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:22px;margin:18px 0}363h1{font-size:22px;margin:0 0 10px}h2{font-size:17px;margin:0 0 8px}p{margin:8px 0}.muted{color:var(--muted)}364.num{font:600 34px/1.1 ui-monospace,SFMono-Regular,Menlo,monospace}.grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}365@media(max-width:560px){.grid{grid-template-columns:1fr}}.k{color:var(--muted);font-size:13px;text-transform:uppercase;letter-spacing:1px}366button,.btn{font:600 15px system-ui,sans-serif;padding:10px 18px;border-radius:8px;border:1px solid var(--accent);background:var(--accent);color:var(--accent-ink);cursor:pointer;text-decoration:none;display:inline-block}367button.ghost{background:transparent;color:var(--ink);border-color:var(--line)}button:focus-visible,a:focus-visible,summary:focus-visible{outline:3px solid #fff;outline-offset:2px}368form{display:inline}.row{display:flex;gap:10px;flex-wrap:wrap;margin-top:14px}369.st{font-weight:700}.st.ok{color:var(--accent)}.st.wait{color:var(--warn)}.st.no{color:var(--bad)}370.note{border-left:3px solid var(--warn);padding:8px 12px;background:#1d2b25;margin:14px 0}371.badge{display:inline-block;font:600 13px system-ui,sans-serif;color:var(--accent);border:1px solid var(--accent);border-radius:999px;padding:3px 12px}372details{margin-top:14px;border-top:1px solid var(--line);padding-top:12px}summary{cursor:pointer;font-weight:600}373footer{color:var(--muted);font-size:13px}374"""375376STATUS_TEXT = {377    "unverified": ("no", "Identity not verified"), "verified": ("ok", "Identity verified"), "manual_review": ("wait", "Verification under review by a person"),378    "inconclusive": ("no", "Verification not conclusive"), "rejected": ("no", "Verification refused"), "revoked": ("no", "Verification revoked"),379}380ERROR_TEXT = {381    "identity_verification_required": "Raising the limit requires a verified identity. Your request is saved: verify your identity and it will be ready to confirm.",382    "identity_verification_pending": "Your verification is being reviewed by a person. Your request is saved and the limit stays unchanged until the review is complete.",383    "identity_unavailable": "The identity service cannot be reached right now, so the limit stays unchanged. Your request is saved. Try again in a moment.",384}385BADGE_EXPLANATION = """386<details><summary>What does "Identity verified" mean?</summary>387<p><b>What it certifies.</b> This person completed an identity check with MacLustr Identity: an identity document was examined388(and, depending on the method, compared with the person presenting it). The check is valid for a limited time and can be revoked.</p>389<p><b>What it does not certify.</b> It is not proof that this person owns an account, a property or any goods, nor that they have the right390to sell or advertise anything. It says nothing about their solvency or reliability, and it is not a recommendation by Northbank.</p>391<p><b>What you will never see.</b> No name, document number, date of birth, address or photo: Northbank does not hold them.</p>392</details>"""393394395def page(title: str, body: str, user: dict | None = None, status: int = 200) -> HTMLResponse:396    who = (f'<p class="who">Signed in as {html.escape(user["name"])} '397           f'<a href="/u/{user["handle"]}">public profile</a>'398           '<form method="post" action="/logout"><button class="ghost" type="submit">Switch user</button></form></p>') if user else ""399    doc = (f'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">'400           f'<title>{html.escape(title)} — Northbank Wallet (demo)</title><style>{CSS}</style></head><body>'401           f'<header><div class="in"><p class="brand">North<b>bank</b> Wallet</p>{who}</div></header><main class="in">{body}</main>'402           '<footer><div class="in">Demo application. Sandbox verifications are simulated and never involve a real document.</div></footer></body></html>')403    return HTMLResponse(doc, status_code=status, headers={"Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff",404                                                          "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' " + IDENTITY_URL + "; base-uri 'none'; frame-ancestors 'none'"})405406407def money(n: float) -> str:408    return f"${n:,.2f}"409410411@app.get("/", response_class=HTMLResponse)412async def home(request: Request, notice: str = "") -> Response:413    user = current_user(request)414    if not user:415        buttons = "".join(f'<form method="post" action="/login"><input type="hidden" name="user" value="{u["id"]}"><button type="submit">{html.escape(u["name"])}</button></form> '416                          for u in USERS.values())417        return page("Sign in", f'<div class="panel"><h1>Pick a demo user</h1><p class="muted">There is no password: this is a demonstration. '418                               f'Each user has their own verification status.</p><div class="row">{buttons}</div></div>')419    m = me(user["id"])420    st = m["identity"]["status"]421    cls, label = STATUS_TEXT.get(st, STATUS_TEXT["unverified"])422    if st == "verified" and not m["identity_verified"]:423        cls, label = "no", "Verification expired"424    note = f'<p class="note" role="alert">{html.escape(ERROR_TEXT[notice])}</p>' if notice in ERROR_TEXT else ""425    actions = ""426    if m["limit"] < VERIFIED_LIMIT:427        actions += f'<form method="post" action="/limit/raise"><button type="submit">Raise the transfer limit to {money(VERIFIED_LIMIT)}</button></form>'428    if not m["identity_verified"] and st != "manual_review":429        actions += ' <form method="post" action="/verify/start"><button class="ghost" type="submit">Verify my identity</button></form>'430    pending = (f'<p class="muted">Saved request: raise the limit to {money(m["requested_limit"])}. It will be applied when you confirm it with a verified identity.</p>'431               if m["requested_limit"] and m["limit"] < VERIFIED_LIMIT else "")432    body = (f'<div class="panel"><div class="grid"><div><p class="k">Balance</p><p class="num">{money(user["balance"])}</p></div>'433            f'<div><p class="k">Daily transfer limit</p><p class="num">{money(m["limit"])}</p></div></div></div>'434            f'<div class="panel"><h2>Identity</h2><p class="st {cls}">{label}</p>{note}{pending}<div class="row">{actions}</div>'435            '<p class="muted" style="margin-top:16px">Verification happens on a page operated by MacLustr Identity. Northbank never receives your document '436            'or your photo: only "verified or not", the level of the check and its expiry date.</p></div>')437    return page("Your wallet", body, user)438439440@app.post("/login")441async def login(request: Request) -> Response:442    form = (await request.body()).decode()443    chosen = dict(p.split("=", 1) for p in form.split("&") if "=" in p).get("user", "")444    resp = RedirectResponse("/", status_code=303)445    if chosen in USERS:446        resp.set_cookie("wl_user", chosen, httponly=True, samesite="lax")447    return resp448449450@app.post("/logout")451async def logout() -> Response:452    resp = RedirectResponse("/", status_code=303)453    resp.delete_cookie("wl_user")454    return resp455456457@app.post("/limit/raise")458async def limit_raise(request: Request) -> Response:459    user = current_user(request)460    if not user:461        return RedirectResponse("/", status_code=303)462    _, body = await raise_limit(user["id"])463    return RedirectResponse("/?notice=" + body.get("error", ""), status_code=303)464465466@app.post("/verify/start")467async def verify_start(request: Request) -> Response:468    user = current_user(request)469    if not user:470        return RedirectResponse("/", status_code=303)471    try:472        url = await start_verification(user["id"])473    except MacLustrIdentityError:474        return RedirectResponse("/?notice=identity_unavailable", status_code=303)475    return RedirectResponse(url, status_code=303)          # full-page redirect to the hosted verification page476477478@app.get("/verify/return", response_class=HTMLResponse)479async def verify_return(request: Request) -> Response:480    """Where the hosted page sends the person back. Nothing in the URL is trusted: the server looks the result up itself."""481    user = current_user(request)482    if not user:483        return RedirectResponse("/", status_code=303)484    unavailable = False485    try:486        await refresh_from_service(user["id"])487    except MacLustrIdentityError:488        unavailable = True489    m = me(user["id"])490    cls, label = STATUS_TEXT.get(m["identity"]["status"], STATUS_TEXT["unverified"])491    extra = ""492    if unavailable:493        extra = '<p class="note" role="alert">The identity service cannot be reached right now. Your status will update as soon as it answers.</p>'494    elif m["identity_verified"] and m["requested_limit"]:495        extra = (f'<p>Your saved request is ready.</p><div class="row"><form method="post" action="/limit/raise">'496                 f'<button type="submit">Confirm: raise the limit to {money(VERIFIED_LIMIT)}</button></form></div>')497    elif m["identity"]["status"] == "unverified":498        extra = '<p class="muted">The verification was not completed. You can start again from your wallet.</p>'499    return page("Verification", f'<div class="panel"><h1>Back at Northbank</h1><p class="st {cls}">{label}</p>{extra}'500                                '<div class="row"><a class="btn" href="/">Go to my wallet</a></div></div>', user)501502503@app.get("/u/{handle}", response_class=HTMLResponse)504async def profile(handle: str, request: Request) -> Response:505    user = next((u for u in USERS.values() if u["handle"] == handle), None)506    if not user:507        return page("Not found", '<div class="panel"><h1>No such profile</h1></div>', current_user(request), 404)508    badge = '<p><span class="badge">Identity verified</span></p>' if locally_verified(user["id"]) else '<p class="muted">This person has not verified their identity.</p>'509    return page(f"@{handle}", f'<div class="panel"><h1>@{html.escape(handle)}</h1><p class="muted">Public payment profile</p>{badge}{BADGE_EXPLANATION}</div>',510                current_user(request))511512513if __name__ == "__main__":514    import uvicorn515    uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="warning")516
Files main
Menu

Theme