Fetches a fresh access token for the Auth0 Management API. Uses in-memory cache with 4-hour expiration to reduce API calls.
()
| 20 | _token_expires_at = 0 # epoch timestamp when token expires |
| 21 | |
| 22 | def _get_management_api_token() -> str: |
| 23 | """ |
| 24 | Fetches a fresh access token for the Auth0 Management API. |
| 25 | Uses in-memory cache with 4-hour expiration to reduce API calls. |
| 26 | """ |
| 27 | global _mgmt_token, _token_expires_at |
| 28 | |
| 29 | # Check if cached token is still valid |
| 30 | if _mgmt_token and time.time() < _token_expires_at: |
| 31 | return _mgmt_token |
| 32 | |
| 33 | if not all([AUTH0_DOMAIN, MGMT_API_CLIENT_ID, MGMT_API_CLIENT_SECRET]): |
| 34 | logger.error("Auth0 Management API credentials are not fully configured.") |
| 35 | raise ValueError("Auth0 Management API credentials are not set in environment.") |
| 36 | |
| 37 | payload = { |
| 38 | "client_id": MGMT_API_CLIENT_ID, |
| 39 | "client_secret": MGMT_API_CLIENT_SECRET, |
| 40 | "audience": MGMT_API_AUDIENCE, |
| 41 | "grant_type": "client_credentials" |
| 42 | } |
| 43 | headers = {'content-type': "application/json"} |
| 44 | |
| 45 | try: |
| 46 | response = requests.post(f"https://{AUTH0_DOMAIN}/oauth/token", json=payload, headers=headers) |
| 47 | response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx) |
| 48 | |
| 49 | # Cache the token for 4 hours |
| 50 | _mgmt_token = response.json()["access_token"] |
| 51 | _token_expires_at = time.time() + (4 * 60 * 60) # 4 hours in seconds |
| 52 | |
| 53 | logger.info("Successfully fetched Auth0 Management API token.") |
| 54 | return _mgmt_token |
| 55 | except requests.exceptions.RequestException as e: |
| 56 | logger.error(f"Failed to get Auth0 Management API token: {e}") |
| 57 | raise |
| 58 | |
| 59 | # Sentinel value to indicate a field should be cleared (deleted) from metadata |
| 60 | CLEAR_FIELD = "__CLEAR__" |
no test coverage detected