|
| 1 | +""" |
| 2 | +This module provides async functionality for managing API keys in Typesense. |
| 3 | +
|
| 4 | +It contains the AsyncKeys class, which allows for creating, retrieving, and |
| 5 | +generating scoped search keys asynchronously. |
| 6 | +
|
| 7 | +Classes: |
| 8 | + AsyncKeys: Manages API keys in the Typesense API (async). |
| 9 | +
|
| 10 | +Dependencies: |
| 11 | + - typesense.async_api_call: Provides the AsyncApiCall class for making async API requests. |
| 12 | + - typesense.async_key: Provides the AsyncKey class for individual API key operations. |
| 13 | + - typesense.types.document: Provides GenerateScopedSearchKeyParams type. |
| 14 | + - typesense.types.key: Provides various API key schema types. |
| 15 | +
|
| 16 | +Note: This module uses conditional imports to support both Python 3.11+ and earlier versions. |
| 17 | +""" |
| 18 | + |
| 19 | +import base64 |
| 20 | +import hashlib |
| 21 | +import hmac |
| 22 | +import json |
| 23 | +import sys |
| 24 | + |
| 25 | +from typesense.async_api_call import AsyncApiCall |
| 26 | +from typesense.async_key import AsyncKey |
| 27 | +from typesense.types.document import GenerateScopedSearchKeyParams |
| 28 | +from typesense.types.key import ( |
| 29 | + ApiKeyCreateResponseSchema, |
| 30 | + ApiKeyCreateSchema, |
| 31 | + ApiKeyRetrieveSchema, |
| 32 | + ApiKeySchema, |
| 33 | +) |
| 34 | + |
| 35 | +if sys.version_info >= (3, 11): |
| 36 | + import typing |
| 37 | +else: |
| 38 | + import typing_extensions as typing |
| 39 | + |
| 40 | + |
| 41 | +class AsyncKeys: |
| 42 | + """ |
| 43 | + Manages API keys in the Typesense API (async). |
| 44 | +
|
| 45 | + This class provides async methods to create, retrieve, and generate scoped search keys. |
| 46 | +
|
| 47 | + Attributes: |
| 48 | + resource_path (str): The API endpoint path for key operations. |
| 49 | + api_call (AsyncApiCall): The AsyncApiCall instance for making async API requests. |
| 50 | + keys (Dict[int, AsyncKey]): A dictionary of AsyncKey instances, keyed by key ID. |
| 51 | + """ |
| 52 | + |
| 53 | + resource_path: typing.Final[str] = "/keys" |
| 54 | + |
| 55 | + def __init__(self, api_call: AsyncApiCall) -> None: |
| 56 | + """ |
| 57 | + Initialize the AsyncKeys instance. |
| 58 | +
|
| 59 | + Args: |
| 60 | + api_call (AsyncApiCall): The AsyncApiCall instance for making async API requests. |
| 61 | + """ |
| 62 | + self.api_call = api_call |
| 63 | + self.keys: typing.Dict[int, AsyncKey] = {} |
| 64 | + |
| 65 | + def __getitem__(self, key_id: int) -> AsyncKey: |
| 66 | + """ |
| 67 | + Get or create an AsyncKey instance for a given key ID. |
| 68 | +
|
| 69 | + This method allows accessing API keys using dictionary-like syntax. |
| 70 | + If the AsyncKey instance doesn't exist, it creates a new one. |
| 71 | +
|
| 72 | + Args: |
| 73 | + key_id (int): The ID of the API key. |
| 74 | +
|
| 75 | + Returns: |
| 76 | + AsyncKey: The AsyncKey instance for the specified key ID. |
| 77 | +
|
| 78 | + Example: |
| 79 | + >>> keys = AsyncKeys(async_api_call) |
| 80 | + >>> key = keys[1] |
| 81 | + """ |
| 82 | + if not self.keys.get(key_id): |
| 83 | + self.keys[key_id] = AsyncKey(self.api_call, key_id) |
| 84 | + return self.keys[key_id] |
| 85 | + |
| 86 | + async def create(self, schema: ApiKeyCreateSchema) -> ApiKeyCreateResponseSchema: |
| 87 | + """ |
| 88 | + Create a new API key. |
| 89 | +
|
| 90 | + Args: |
| 91 | + schema (ApiKeyCreateSchema): The schema for creating the API key. |
| 92 | +
|
| 93 | + Returns: |
| 94 | + ApiKeyCreateResponseSchema: The created API key. |
| 95 | +
|
| 96 | + Example: |
| 97 | + >>> keys = AsyncKeys(async_api_call) |
| 98 | + >>> key = await keys.create( |
| 99 | + ... { |
| 100 | + ... "actions": ["documents:search"], |
| 101 | + ... "collections": ["companies"], |
| 102 | + ... "description": "Search-only key", |
| 103 | + ... } |
| 104 | + ... ) |
| 105 | + """ |
| 106 | + response: ApiKeySchema = await self.api_call.post( |
| 107 | + AsyncKeys.resource_path, |
| 108 | + as_json=True, |
| 109 | + body=schema, |
| 110 | + entity_type=ApiKeySchema, |
| 111 | + ) |
| 112 | + return response |
| 113 | + |
| 114 | + def generate_scoped_search_key( |
| 115 | + self, |
| 116 | + search_key: str, |
| 117 | + key_parameters: GenerateScopedSearchKeyParams, |
| 118 | + ) -> bytes: |
| 119 | + """ |
| 120 | + Generate a scoped search key. |
| 121 | +
|
| 122 | + Note: This is a synchronous method as it performs local computation |
| 123 | + and does not make any API calls. Only a key generated with the |
| 124 | + `documents:search` action will be accepted by the server. |
| 125 | +
|
| 126 | + Args: |
| 127 | + search_key (str): The search key to use as a base. |
| 128 | + key_parameters (GenerateScopedSearchKeyParams): Parameters for the scoped key. |
| 129 | +
|
| 130 | + Returns: |
| 131 | + bytes: The generated scoped search key. |
| 132 | +
|
| 133 | + Example: |
| 134 | + >>> keys = AsyncKeys(async_api_call) |
| 135 | + >>> scoped_key = keys.generate_scoped_search_key( |
| 136 | + ... "KmacipDKNqAM3YiigXfw5pZvNOrPQUba", |
| 137 | + ... {"q": "search query", "collection": "companies"}, |
| 138 | + ... ) |
| 139 | + """ |
| 140 | + params_str = json.dumps(key_parameters) |
| 141 | + digest = base64.b64encode( |
| 142 | + hmac.new( |
| 143 | + search_key.encode("utf-8"), |
| 144 | + params_str.encode("utf-8"), |
| 145 | + digestmod=hashlib.sha256, |
| 146 | + ).digest(), |
| 147 | + ) |
| 148 | + key_prefix = search_key[:4] |
| 149 | + raw_scoped_key = f"{digest.decode('utf-8')}{key_prefix}{params_str}" |
| 150 | + return base64.b64encode(raw_scoped_key.encode("utf-8")) |
| 151 | + |
| 152 | + async def retrieve(self) -> ApiKeyRetrieveSchema: |
| 153 | + """ |
| 154 | + Retrieve all API keys. |
| 155 | +
|
| 156 | + Returns: |
| 157 | + ApiKeyRetrieveSchema: The schema containing all API keys. |
| 158 | +
|
| 159 | + Example: |
| 160 | + >>> keys = AsyncKeys(async_api_call) |
| 161 | + >>> all_keys = await keys.retrieve() |
| 162 | + >>> for key in all_keys["keys"]: |
| 163 | + ... print(key["id"]) |
| 164 | + """ |
| 165 | + response: ApiKeyRetrieveSchema = await self.api_call.get( |
| 166 | + AsyncKeys.resource_path, |
| 167 | + entity_type=ApiKeyRetrieveSchema, |
| 168 | + as_json=True, |
| 169 | + ) |
| 170 | + return response |
0 commit comments