-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathenode_auth.py
More file actions
53 lines (43 loc) · 2.21 KB
/
enode_auth.py
File metadata and controls
53 lines (43 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from typing import Optional
import httpx
class EnodeAuth(httpx.Auth):
def __init__(
self, client_id: str, client_secret: str, token_url: str, access_token: Optional[str] = None
):
self._client_id = client_id
self._client_secret = client_secret
self._token_url = token_url
self._access_token = access_token
def sync_auth_flow(self, request: httpx.Request):
# Add the Authorization header to the request using the current access token
request.headers["Authorization"] = f"Bearer {self._access_token}"
response = yield request
if response.status_code == 401:
# The access token is no longer valid, refresh it
token_response = yield self._build_refresh_request()
token_response.read()
self._update_access_token(token_response)
# Update the request's Authorization header with the new access token
request.headers["Authorization"] = f"Bearer {self._access_token}"
# Resend the request with the new access token
yield request
async def async_auth_flow(self, request: httpx.Request):
# Add the Authorization header to the request using the current access token
request.headers["Authorization"] = f"Bearer {self._access_token}"
response = yield request
if response.status_code == 401:
# The access token is no longer valid, refresh it
token_response = yield self._build_refresh_request()
await token_response.aread()
self._update_access_token(token_response)
# Update the request's Authorization header with the new access token
request.headers["Authorization"] = f"Bearer {self._access_token}"
# Resend the request with the new access token
yield request
def _build_refresh_request(self):
basic_auth = httpx.BasicAuth(self._client_id, self._client_secret)
data = {"grant_type": "client_credentials"}
request = next(basic_auth.auth_flow(httpx.Request("POST", self._token_url, data=data)))
return request
def _update_access_token(self, response):
self._access_token = response.json()["access_token"]