|
| 1 | +"""Connect API integration. |
| 2 | +
|
| 3 | +Connect API key exchange implementation which supports interacting with Posit OAuth integrations on Connect. |
| 4 | +
|
| 5 | +Notes |
| 6 | +----- |
| 7 | +The APIs in this module are provided as a convenience and are subject to breaking changes. |
| 8 | +""" |
| 9 | + |
| 10 | +from typing_extensions import Optional |
| 11 | + |
| 12 | +from ..oauth.oauth import API_KEY_TOKEN_TYPE |
| 13 | + |
| 14 | +from ..client import Client |
| 15 | +from .external import is_local |
| 16 | + |
| 17 | + |
| 18 | +class ConnectAPIKeyProvider: |
| 19 | + """ |
| 20 | + Provider for exchanging Connect User Session Token for Connect API Key that acts on behalf of the user. |
| 21 | + This is an ephemeral API key that adheres to typical ephemeral API key clean up processes. |
| 22 | +
|
| 23 | + Examples |
| 24 | + -------- |
| 25 | + ```python |
| 26 | + from shiny import App, render, ui, reactive, req |
| 27 | + from posit.connect import Client |
| 28 | + from posit.connect.external.connect_api import ConnectAPIKeyProvider |
| 29 | +
|
| 30 | + client = Client() |
| 31 | +
|
| 32 | + app_ui = ui.page_fixed( |
| 33 | + ui.h1("My Shiny App"), |
| 34 | + # ... |
| 35 | + ) |
| 36 | +
|
| 37 | + def server(input, output, session): |
| 38 | + user_session_token = session.http_conn.headers.get("Posit-Connect-User-Session-Token") |
| 39 | + provider = ConnectAPIKeyProvider(client, user_session_token) |
| 40 | + viewer_api_key = provider.viewer_key |
| 41 | +
|
| 42 | + # your app logic... |
| 43 | +
|
| 44 | + app = App(app_ui, server) |
| 45 | + ``` |
| 46 | + """ |
| 47 | + |
| 48 | + def __init__( |
| 49 | + self, |
| 50 | + client: Optional[Client] = None, |
| 51 | + user_session_token: Optional[str] = None, |
| 52 | + ): |
| 53 | + self._client = client |
| 54 | + self._user_session_token = user_session_token |
| 55 | + |
| 56 | + @property |
| 57 | + def viewer_key(self) -> Optional[str]: |
| 58 | + """ |
| 59 | + The viewer key is retrieved through an OAuth exchange process using the user session token. |
| 60 | + The issued API key is associated with the viewer of your app and can be used on their behalf |
| 61 | + to interact with the Connect API. |
| 62 | + """ |
| 63 | + if is_local(): |
| 64 | + return None |
| 65 | + |
| 66 | + # If the user-session-token wasn't provided and we're running on Connect then we raise an exception. |
| 67 | + # user_session_token is required to impersonate the viewer. |
| 68 | + if self._user_session_token is None: |
| 69 | + raise ValueError("The user-session-token is required for viewer API key authorization.") |
| 70 | + |
| 71 | + if self._client is None: |
| 72 | + self._client = Client() |
| 73 | + |
| 74 | + credentials = self._client.oauth.get_credentials( |
| 75 | + user_session_token=self._user_session_token, |
| 76 | + requested_token_type=API_KEY_TOKEN_TYPE, |
| 77 | + ) |
| 78 | + return credentials.get("access_token") |
0 commit comments