import json from urllib import error, request class Auth0Client: def __init__(self, domain: str, client_id: str, client_secret: str): self._domain = domain self._client_id = client_id self._client_secret = client_secret self._token = None def _send_request( self, url: str, data: dict = None, headers: dict = None, method: str = "GET", as_json: bool = True ) -> dict: if method == "POST": data = json.dumps(data).encode() headers = { "Content-Type": "application/json; charset=utf-8", "Content-Length": len(data), **(headers or {}) } req = request.Request( url if url.startswith("http") else f"https://{self._domain}/{url}", method=method, **({"data": data} if data else {}), **({"headers": headers} if headers else {}), ) try: with request.urlopen(req) as resp: content = resp.read() return json.loads(content.decode()) if as_json else content except error.HTTPError as e: body = e.read().decode() print(e, body) raise def send_request(self, url: str, data: dict = None, method: str = "GET") -> dict: if not self._token: self._token = self._send_request( "oauth/token", data={ "client_id": self._client_id, "client_secret": self._client_secret, "audience": "https://{}/api/v2/".format(self._domain), "grant_type": "client_credentials", }, method="POST", )["access_token"] return self._send_request(url=url, data=data, method=method, headers={"Authorization": f"Bearer {self._token}"}) def init_export_job(self, connection_id: str) -> str: result = self.send_request( "api/v2/jobs/users-exports", data={ "connection_id": connection_id, "format": "csv", "fields": [{"name": "user_id"}, {"name": "email"}], }, method="POST", ) return result["id"] def get_job(self, job_id: str) -> str or None: result = self.send_request(f"api/v2/jobs/{job_id}", method="GET") return result.get("location") def get_file(self, location: str): return self._send_request(location, method="GET", as_json=False)