Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | INFRASTRUCTURE & AUTOMATION4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# Project : MacLustr Identity8# File : sdk/swift/Examples/demo-backend/server.py9# Description : Minimal demo backend for the MacLustr Identity mobile10# demos (standard library only).11# Module : sdk12# Repository : https://git.spboucher.ai/maclustr-identity13# Project Website : https://identity.spboucher.ai14# Created : 2026-12-0115# Last Modified : 2026-12-0116#17# Author : Simon-Pierre Boucher18# Position : Professor of Finance19# Institution : Université du Québec en Outaouais (UQO)20# Organization : SP Boucher21# Website : https://spboucher.ai22# Git : https://git.spboucher.ai23#24# Preferred Contact: admin@spboucher.ai25# Technical Contact: dev@spboucher.ai26# Security/Admin : admin@spboucher.ai27#28# Copyright (c) 202629# Simon-Pierre Boucher30# All rights reserved where applicable. This file is governed by the31# applicable project license, copyright notices and relevant law.32# Existing third-party rights and notices remain unaffected.33#34# License : None specified (no license file in this repository)35#36# Do not embed credentials, private keys, access tokens,37# certificates or confidential personal information.38#39# =============================================================================40# END OF SP BOUCHER SOURCE HEADER41# =============================================================================4243"""Minimal demo backend for the MacLustr Identity mobile demos (standard library only).4445It plays the role of the integrating app's own backend: it holds the secret API key and creates46verification sessions. The mobile app only ever receives the hosted URL (session id + client secret).4748 MLID_API_KEY=mlid_sk_test_... MLID_BASE_URL=http://localhost:8875 python3 server.py 88994950 POST /session -> {"url": "...", "session_id": "...", "client_secret": "..."}51 GET /result/<session> -> {"status": "...", "verification_id": "..."} (what the app should trust)5253Development only: no authentication, binds to 127.0.0.1.54"""55import json56import os57import sys58import urllib.request59import uuid60from http.server import BaseHTTPRequestHandler, HTTPServer6162API_KEY = os.environ.get("MLID_API_KEY", "")63BASE = os.environ.get("MLID_BASE_URL", "https://identity.spboucher.ai").rstrip("/")646566def api(method: str, path: str, body: dict | None = None) -> tuple[int, dict]:67 req = urllib.request.Request(BASE + path, method=method, data=json.dumps(body).encode() if body is not None else None,68 headers={"Authorization": "Bearer " + API_KEY, "Content-Type": "application/json"})69 try:70 with urllib.request.urlopen(req, timeout=20) as r:71 return r.status, json.loads(r.read())72 except urllib.error.HTTPError as e:73 return e.code, json.loads(e.read() or b"{}")747576class Handler(BaseHTTPRequestHandler):77 def _send(self, status: int, obj: dict) -> None:78 data = json.dumps(obj).encode()79 self.send_response(status)80 self.send_header("Content-Type", "application/json")81 self.send_header("Content-Length", str(len(data)))82 self.end_headers()83 self.wfile.write(data)8485 def do_POST(self):86 if self.path != "/session":87 return self._send(404, {"error": "not found"})88 status, s = api("POST", "/v1/verification-sessions", {"purpose": "demo", "external_user_id": "demo_" + uuid.uuid4().hex[:10]})89 if status != 200:90 return self._send(status, s)91 self._send(200, {"url": s["url"], "session_id": s["id"], "client_secret": s["client_secret"]})9293 def do_GET(self):94 if not self.path.startswith("/result/"):95 return self._send(404, {"error": "not found"})96 status, s = api("GET", "/v1/verification-sessions/" + self.path.split("/")[2])97 if status != 200:98 return self._send(status, s)99 self._send(200, {"status": s["status"], "verification_id": s["verification_id"]})100101 def log_message(self, *args):102 pass103104105if __name__ == "__main__":106 if not API_KEY.startswith("mlid_sk_"):107 sys.exit("Set MLID_API_KEY to a secret key (use a sandbox key, mlid_sk_test_..., for demos).")108 port = int(sys.argv[1]) if len(sys.argv) > 1 else 8899109 print(f"demo backend on http://127.0.0.1:{port} -> {BASE}")110 HTTPServer(("127.0.0.1", port), Handler).serve_forever()111