"""Simple wrapper module for fetching and storing access tokens for VAPI. Currently only stores and returns the access token, ignoring the other values returned by the Oauth client (e.g. refresh_token, expires_at, etc.) because VAPI does not expire access tokens. If we do need those values in the future, this code can be updated to store and expose them as well. """ import hashlib def get_access_token(oauth_client, cache, cache_timeout=None): """Retrieve the access token, looking in cache first. If no token is found in cache, fetch a token from the client and store it in the cache for posterity. Args: oauth_client (OauthClient): Client for fetching new access tokens. cache (werkzeug.contrib.cache.BaseCache): Cache implementation for persisting an access token after fetching it from the client. cache_timeout (None|int): timeout Returns: string: Access token """ key = cache_key(oauth_client) access_token = cache.get(key) if not access_token: token_data = oauth_client.fetch_token() access_token = token_data.get("access_token") cache.set(key, access_token, cache_timeout) return access_token def cache_key(oauth_client): """Calculate cache key based on values in the Oauth client object. Args: oauth_client (OauthClient) Client which holds relevant config data. """ properties = ("client_id", "client_secret", "base_url", "user_id", "user_type") param_values = [] for prop in properties: param_values.append(str(getattr(oauth_client, prop))) # Construct a unique string from these values. Delimiter is arbitrary. cache_suffix = ",".join(param_values) h = hashlib.sha256(cache_suffix.encode()) return "access-token-" + h.hexdigest()