From 8526769f40ec6b2c30ab9707d1f09ee2e41ee286 Mon Sep 17 00:00:00 2001 From: Panos Vagenas <35837085+vagenas@users.noreply.github.com> Date: Mon, 28 Nov 2022 13:48:30 +0100 Subject: [PATCH] feat: add token refresh (#50) Signed-off-by: Panos Vagenas <35837085+vagenas@users.noreply.github.com> --- MAINTAINERS.md | 1 + deepsearch/cps/client/api.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/MAINTAINERS.md b/MAINTAINERS.md index 958c81ea..12d23454 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -2,6 +2,7 @@ - Michele Dolfi - [@dolfim-ibm](https://github.com/dolfim-ibm) - Christoph Auer - [@cau-git](https://github.com/cau-git) +- Panos Vagenas - [@vagenas](https://github.com/vagenas) - Peter Staar - [@PeterStaar-IBM](https://github.com/PeterStaar-IBM) Maintainers can be contacted at [deepsearch-core@zurich.ibm.com](mailto:deepsearch-core@zurich.ibm.com). diff --git a/deepsearch/cps/client/api.py b/deepsearch/cps/client/api.py index 251ef1af..83cceb7a 100644 --- a/deepsearch/cps/client/api.py +++ b/deepsearch/cps/client/api.py @@ -107,6 +107,40 @@ def __init__(self, client: CpsApiClient) -> None: self.elastic = CpsApiElastic(self) self.data_indices = CpsApiDataIndices(self) + def refresh_token(self, admin: bool = False): + """Refresh access token + + Args: + admin (bool, optional): controls whether an admin token should be requested. Defaults to False. + + Raises: + RuntimeError: raised in case API Key or User is invalid + """ + auth_header_val = f"Bearer {self.client.bearer_token_auth.bearer_token}" + user_api_conf = deepsearch.cps.apis.user.Configuration( + host=f"{self.client.config.host}/api/cps/user/v1", + api_key={"Authorization": auth_header_val}, + ) + user_api_conf.verify_ssl = self.client.config.verify_ssl + user_api_conf.client_side_validation = False + + api = deepsearch.cps.apis.user.UsersApi( + api_client=deepsearch.cps.apis.user.ApiClient(configuration=user_api_conf) + ) + + try: + access_token = api.get_access_token(options={"admin": admin}).access_token + except deepsearch.cps.apis.user.exceptions.ApiException as e: + raise RuntimeError("The API Key or User is invalid.") from e + + bearer_token_auth = DeepSearchBearerTokenAuth(bearer_token=access_token) + ds_config = DeepSearchConfig( + host=self.client.config.host, + auth=bearer_token_auth, + verify_ssl=self.client.config.verify_ssl, + ) + self.client = CpsApiClient(ds_config) + @classmethod def default_from_env(cls) -> "CpsApi": """