08 Companion mock_device_auth.py (1/5)

File: examples/companions/device-code-catalog/mock_device_auth.py (126 lines)

#!/usr/bin/env python3
"""Mock OAuth 2.0 device-code server for the device-code-catalog example.

    python3 mock_device_auth.py            # listens on 0.0.0.0:8081

Flow:
  POST /device/code   -> {device_code, user_code, verification_uri, interval, expires_in}
  POST /device/token  -> {"error":"authorization_pending"} until approved, then {"access_token": ...}
  GET  /activate      -> page where you type the user code and approve it
  GET  /api/books     -> JSON list of books (Bearer token required)
  GET  /files/<name>  -> serves an EPUB from ./books (Bearer token required)

Both form-encoded and JSON request bodies are accepted.
"""
import html
import sys
sys.stdout.reconfigure(line_buffering=True)   # print events immediately, also when piped
import json
import pathlib
import secrets
import socket
import time
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

PORT = 8081
BOOKS = pathlib.Path(__file__).with_name("books")
PENDING = {}   # device_code -> {"user_code", "expires", "approved"}
TOKENS = set()

def lan_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(("192.0.2.1", 9))   # no packet is sent; picks the outgoing interface
        return s.getsockname()[0]
    except OSError:
        return "127.0.0.1"
    finally:
        s.close()
‹ PreviousReader file (.txt)Next ›