| 23 | |
| 24 | |
| 25 | class _AsyncHTTP: |
| 26 | def __init__( |
| 27 | self, |
| 28 | *, |
| 29 | app_id: str, |
| 30 | admin_token: str | None, |
| 31 | api_uri: str = DEFAULT_API_URI, |
| 32 | impersonation: dict[str, str] | None = None, |
| 33 | transport: httpx.AsyncBaseTransport | None = None, |
| 34 | shared_client: httpx.AsyncClient | None = None, |
| 35 | ) -> None: |
| 36 | self._app_id = app_id |
| 37 | self._admin_token = admin_token |
| 38 | self._api_uri = api_uri.rstrip("/") |
| 39 | self._impersonation = impersonation or {} |
| 40 | if shared_client is not None: |
| 41 | self._client = shared_client |
| 42 | self._owns_client = False |
| 43 | else: |
| 44 | self._client = httpx.AsyncClient( |
| 45 | base_url=self._api_uri, |
| 46 | timeout=DEFAULT_TIMEOUT, |
| 47 | transport=transport, |
| 48 | ) |
| 49 | self._owns_client = True |
| 50 | |
| 51 | def _headers( |
| 52 | self, *, unauthenticated: bool = False, admin_only: bool = False |
| 53 | ) -> dict[str, str]: |
| 54 | if unauthenticated: |
| 55 | return {"content-type": "application/json"} |
| 56 | self._validate_auth() |
| 57 | h: dict[str, str] = { |
| 58 | "content-type": "application/json", |
| 59 | "app-id": self._app_id, |
| 60 | "Instant-Admin-Version": __version__, |
| 61 | "Instant-Core-Version": __version__, |
| 62 | } |
| 63 | if self._admin_token: |
| 64 | h["authorization"] = f"Bearer {self._admin_token}" |
| 65 | # admin_only skips impersonation so the request uses admin auth. |
| 66 | if not admin_only: |
| 67 | h.update(self._impersonation) |
| 68 | return h |
| 69 | |
| 70 | def _validate_auth(self) -> None: |
| 71 | if self._admin_token: |
| 72 | return |
| 73 | if "as-token" in self._impersonation or "as-guest" in self._impersonation: |
| 74 | return |
| 75 | if "as-email" in self._impersonation: |
| 76 | raise InstantError( |
| 77 | "admin_token is required to impersonate a user by email: " |
| 78 | "pass admin_token=... or set INSTANT_APP_ADMIN_TOKEN" |
| 79 | ) |
| 80 | raise InstantError( |
| 81 | "admin_token is required for this operation: " |
| 82 | "pass admin_token=..., set INSTANT_APP_ADMIN_TOKEN, or use as_user(...)" |
no outgoing calls