Skip to content

Commit 9d96d4a

Browse files
Add logic around access_token use
1 parent bc7c245 commit 9d96d4a

File tree

2 files changed

+34
-5
lines changed

2 files changed

+34
-5
lines changed

src/iracingdataapi/client.py

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,34 @@
88

99
import requests
1010

11+
from .exceptions import AccessTokenInvalid
12+
1113

1214
class irDataClient:
1315

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):
1617
self.session = requests.Session()
1718
self.base_url = "https://members-ng.iracing.com"
1819
self.silent = silent
1920

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
2239

2340
def _encode_password(self, username: str, password: str) -> str:
2441
initial_hash = hashlib.sha256(
@@ -65,18 +82,28 @@ def _login(self) -> str:
6582
def _build_url(self, endpoint: str) -> str:
6683
return self.base_url + endpoint
6784

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+
6892
def _get_resource_or_link(
6993
self, url: str, payload: dict = None
7094
) -> list[Union[Dict, str], bool]:
7195
if not self.authenticated:
7296
self._login()
7397
return self._get_resource_or_link(url, payload=payload)
7498

75-
r = self.session.get(url, params=payload)
99+
r = self.session.get(url, params=payload, headers=self._build_request_headers())
76100

77101
if r.status_code == 401 and self.authenticated:
78102
# unauthorised, likely due to a timeout, retry after a login
79103
self.authenticated = False
104+
if self.access_token:
105+
raise AccessTokenInvalid("Access token not valid")
106+
80107
return self._get_resource_or_link(url, payload=payload)
81108

82109
if r.status_code == 429:

src/iracingdataapi/exceptions.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
class AccessTokenInvalid(Exception):
2+
pass

0 commit comments

Comments
 (0)