Skip to content

Commit

Permalink
Merge pull request #471 from City-of-Helsinki/HP-2247-requests-timeout
Browse files Browse the repository at this point in the history
HP-2247 | feat(keycloak): add timeout to API calls
  • Loading branch information
charn authored Feb 15, 2024
2 parents 84b62e2 + f505b24 commit dc3ecb4
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions utils/keycloak.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ def __init__(self, server_url, realm_name, client_id, client_secret):

self._session = requests.Session()
self._auth = None
self._timeout = 10

def _handle_request_common_errors(self, requester):
try:
Expand All @@ -52,7 +53,7 @@ def _well_known(self):
well_known_url = f"{self._server_url}/realms/{self._realm_name}/.well-known/openid-configuration"

result = self._handle_request_common_errors(
lambda: self._session.get(well_known_url)
lambda: self._session.get(well_known_url, timeout=self._timeout)
)

if not result.ok:
Expand All @@ -73,7 +74,9 @@ def _get_auth(self, force_renew=False):
}

result = self._handle_request_common_errors(
lambda: self._session.post(token_endpoint_url, data=credentials_request)
lambda: self._session.post(
token_endpoint_url, data=credentials_request, timeout=self._timeout
)
)

if not result.ok:
Expand Down Expand Up @@ -118,7 +121,7 @@ def get_user(self, user_id):
url = self._single_user_url(user_id)

response = self._handle_user_request(
lambda auth: self._session.get(url, auth=auth)
lambda auth: self._session.get(url, auth=auth, timeout=self._timeout)
)

return response.json()
Expand All @@ -127,20 +130,27 @@ def update_user(self, user_id, update_data: dict):
url = self._single_user_url(user_id)

self._handle_user_request(
lambda auth: self._session.put(url, auth=auth, json=update_data)
lambda auth: self._session.put(
url, auth=auth, json=update_data, timeout=self._timeout
)
)

def delete_user(self, user_id):
url = self._single_user_url(user_id)

self._handle_user_request(lambda auth: self._session.delete(url, auth=auth))
self._handle_user_request(
lambda auth: self._session.delete(url, auth=auth, timeout=self._timeout)
)

def send_verify_email(self, user_id):
url = self._single_user_url(user_id)
url += "/send-verify-email"

return self._handle_user_request(
lambda auth: self._session.put(
url, auth=auth, params={"client_id": self._client_id}
url,
auth=auth,
timeout=self._timeout,
params={"client_id": self._client_id},
)
)

0 comments on commit dc3ecb4

Please sign in to comment.