|
8 | 8 |
|
9 | 9 | import requests |
10 | 10 |
|
| 11 | +from .exceptions import AccessTokenInvalid |
| 12 | + |
11 | 13 |
|
12 | 14 | class irDataClient: |
13 | 15 |
|
14 | | - def __init__(self, username=None, password=None, silent=False): |
15 | | - self.authenticated = False |
| 16 | + def __init__(self, username=None, password=None, access_token=None, silent=False): |
16 | 17 | self.session = requests.Session() |
17 | 18 | self.base_url = "https://members-ng.iracing.com" |
18 | 19 | self.silent = silent |
19 | 20 |
|
20 | | - self.username = username |
21 | | - self.encoded_password = self._encode_password(username, password) |
| 21 | + self.access_token = None |
| 22 | + self.username = None |
| 23 | + self.encoded_password = None |
| 24 | + |
| 25 | + if access_token and username and password: |
| 26 | + raise AttributeError( |
| 27 | + "You must supply either access token or account credentials, not both" |
| 28 | + ) |
| 29 | + |
| 30 | + if username and password: |
| 31 | + self.username = username |
| 32 | + self.encoded_password = self._encode_password(username, password) |
| 33 | + |
| 34 | + if access_token: |
| 35 | + self.access_token = access_token |
| 36 | + |
| 37 | + # assume access token is valid, we'll raise later if necessary |
| 38 | + self.authenticated = True if self.access_token else False |
22 | 39 |
|
23 | 40 | def _encode_password(self, username: str, password: str) -> str: |
24 | 41 | initial_hash = hashlib.sha256( |
@@ -65,18 +82,28 @@ def _login(self) -> str: |
65 | 82 | def _build_url(self, endpoint: str) -> str: |
66 | 83 | return self.base_url + endpoint |
67 | 84 |
|
| 85 | + def _build_request_headers(self) -> dict: |
| 86 | + headers = {} |
| 87 | + if self.access_token: |
| 88 | + headers["Authorization"] = f"Bearer {self.access_token}" |
| 89 | + |
| 90 | + return headers |
| 91 | + |
68 | 92 | def _get_resource_or_link( |
69 | 93 | self, url: str, payload: dict = None |
70 | 94 | ) -> list[Union[Dict, str], bool]: |
71 | 95 | if not self.authenticated: |
72 | 96 | self._login() |
73 | 97 | return self._get_resource_or_link(url, payload=payload) |
74 | 98 |
|
75 | | - r = self.session.get(url, params=payload) |
| 99 | + r = self.session.get(url, params=payload, headers=self._build_request_headers()) |
76 | 100 |
|
77 | 101 | if r.status_code == 401 and self.authenticated: |
78 | 102 | # unauthorised, likely due to a timeout, retry after a login |
79 | 103 | self.authenticated = False |
| 104 | + if self.access_token: |
| 105 | + raise AccessTokenInvalid("Access token not valid") |
| 106 | + |
80 | 107 | return self._get_resource_or_link(url, payload=payload) |
81 | 108 |
|
82 | 109 | if r.status_code == 429: |
|
0 commit comments