|
| 1 | +import json |
| 2 | +import logging |
| 3 | +import re |
| 4 | +import typing as t |
| 5 | + |
| 6 | +import sqlalchemy as sa |
| 7 | +from pydantic import BaseModel |
| 8 | +from quart import g |
| 9 | +from quart import Quart |
| 10 | +from quart import request |
| 11 | +from quart import Request |
| 12 | +from quart import Response |
| 13 | +from quart_schema import QuartSchema |
| 14 | + |
| 15 | +from .. import Base |
| 16 | +from .. import SQLAlchemyConfig |
| 17 | +from ..framework import QuartSQLAlchemy |
| 18 | +from .util import ObjectID |
| 19 | + |
| 20 | + |
| 21 | +AUTHORIZATION_PATTERN = re.compile(r"Bearer (?P<token>.+)") |
| 22 | +logging.basicConfig(level=logging.INFO) |
| 23 | +logger = logging.getLogger(__name__) |
| 24 | + |
| 25 | + |
| 26 | +class MyBase(Base): |
| 27 | + type_annotation_map = {ObjectID: sa.Integer} |
| 28 | + |
| 29 | + |
| 30 | +app = Quart(__name__) |
| 31 | +db = QuartSQLAlchemy( |
| 32 | + SQLAlchemyConfig.parse_obj( |
| 33 | + { |
| 34 | + "model_class": MyBase, |
| 35 | + "binds": { |
| 36 | + "default": { |
| 37 | + "engine": {"url": "sqlite:///file:mem.db?mode=memory&cache=shared&uri=true"}, |
| 38 | + "session": {"expire_on_commit": False}, |
| 39 | + }, |
| 40 | + "read-replica": { |
| 41 | + "engine": {"url": "sqlite:///file:mem.db?mode=memory&cache=shared&uri=true"}, |
| 42 | + "session": {"expire_on_commit": False}, |
| 43 | + "read_only": True, |
| 44 | + }, |
| 45 | + "async": { |
| 46 | + "engine": { |
| 47 | + "url": "sqlite+aiosqlite:///file:mem.db?mode=memory&cache=shared&uri=true" |
| 48 | + }, |
| 49 | + "session": {"expire_on_commit": False}, |
| 50 | + }, |
| 51 | + }, |
| 52 | + } |
| 53 | + ) |
| 54 | +) |
| 55 | +openapi = QuartSchema(app) |
| 56 | + |
| 57 | + |
| 58 | +class RequestAuth(BaseModel): |
| 59 | + client: t.Optional[t.Any] = None |
| 60 | + user: t.Optional[t.Any] = None |
| 61 | + |
| 62 | + @property |
| 63 | + def has_client(self): |
| 64 | + return self.client is not None |
| 65 | + |
| 66 | + @property |
| 67 | + def has_user(self): |
| 68 | + return self.user is not None |
| 69 | + |
| 70 | + @property |
| 71 | + def is_anonymous(self): |
| 72 | + return all([self.has_client is False, self.has_user is False]) |
| 73 | + |
| 74 | + |
| 75 | +def get_request_client(request: Request): |
| 76 | + api_key = request.headers.get("X-Public-API-Key") |
| 77 | + if not api_key: |
| 78 | + return |
| 79 | + |
| 80 | + with g.bind.Session() as session: |
| 81 | + try: |
| 82 | + magic_client = g.h.MagicClient(session).get_by_public_api_key(api_key) |
| 83 | + except ValueError: |
| 84 | + return |
| 85 | + else: |
| 86 | + return magic_client |
| 87 | + |
| 88 | + |
| 89 | +def get_request_user(request: Request): |
| 90 | + auth_header = request.headers.get("Authorization") |
| 91 | + |
| 92 | + if not auth_header: |
| 93 | + return |
| 94 | + m = AUTHORIZATION_PATTERN.match(auth_header) |
| 95 | + if m is None: |
| 96 | + raise RuntimeError("invalid authorization header") |
| 97 | + |
| 98 | + auth_token = m.group("auth_token") |
| 99 | + |
| 100 | + with g.bind.Session() as session: |
| 101 | + try: |
| 102 | + auth_user = g.h.AuthUser(session).get_by_session_token(auth_token) |
| 103 | + except ValueError: |
| 104 | + return |
| 105 | + else: |
| 106 | + return auth_user |
| 107 | + |
| 108 | + |
| 109 | +@app.before_request |
| 110 | +def set_ethereum_network(): |
| 111 | + g.request_network = request.headers.get("X-Fortmatic-Network", "GOERLI").upper() |
| 112 | + |
| 113 | + |
| 114 | +@app.before_request |
| 115 | +def set_bind_handlers_for_request(): |
| 116 | + from quart_sqlalchemy.sim.handle import Handlers |
| 117 | + |
| 118 | + g.db = db |
| 119 | + |
| 120 | + method = request.method |
| 121 | + if method in ["GET", "OPTIONS", "TRACE", "HEAD"]: |
| 122 | + bind = "read-replica" |
| 123 | + else: |
| 124 | + bind = "default" |
| 125 | + |
| 126 | + g.bind = db.get_bind(bind) |
| 127 | + g.h = Handlers(g.bind) |
| 128 | + |
| 129 | + |
| 130 | +@app.before_request |
| 131 | +def set_request_auth(): |
| 132 | + g.auth = RequestAuth( |
| 133 | + client=get_request_client(request), |
| 134 | + user=get_request_user(request), |
| 135 | + ) |
| 136 | + |
| 137 | + |
| 138 | +@app.after_request |
| 139 | +async def add_json_response_envelope(response: Response) -> Response: |
| 140 | + if response.mimetype != "application/json": |
| 141 | + return response |
| 142 | + data = await response.get_json() |
| 143 | + payload = dict(status="ok", message="", data=data) |
| 144 | + response.set_data(json.dumps(payload)) |
| 145 | + return response |
0 commit comments