11import os
22
3- from datetime import datetime
43from datetime import timedelta
54from http .cookiejar import DefaultCookiePolicy
65from urllib .parse import urljoin
76from urllib .parse import urlparse
87
98import requests
9+ from requests .auth import AuthBase
1010
1111from requests .adapters import HTTPAdapter
1212from urllib3 .util import Retry
1313
1414import typing as t
1515
16- from flareio .exceptions import TokenError
16+ from flareio .auth import _FlareApiKeyAuth
1717from flareio .models import ScrollEventsResult
1818from flareio .ratelimit import Limiter
1919from flareio .version import __version__ as _flareio_version
2020
2121
2222_API_DOMAIN_DEFAULT : str = "api.flare.io"
23- _ALLOWED_API_DOMAINS : t .Tuple [str , ...] = (
24- _API_DOMAIN_DEFAULT ,
25- "api.eu.flare.io" ,
23+ _ALLOWED_API_DOMAINS : frozenset [str ] = frozenset (
24+ {
25+ _API_DOMAIN_DEFAULT ,
26+ "api.eu.flare.io" ,
27+ }
2628)
2729
2830
@@ -34,7 +36,7 @@ def __init__(
3436 tenant_id : t .Optional [int ] = None ,
3537 session : t .Optional [requests .Session ] = None ,
3638 api_domain : t .Optional [str ] = None ,
37- _disable_auth : bool = False ,
39+ _auth : t . Optional [ AuthBase ] = None ,
3840 _enable_beta_features : bool = False ,
3941 ) -> None :
4042 if not api_key :
@@ -49,14 +51,16 @@ def __init__(
4951 raise Exception ("Custom API domains considered a beta feature." )
5052 self ._api_domain : str = api_domain
5153
52- self ._api_key : str = api_key
53- self ._tenant_id : t .Optional [int ] = tenant_id
54-
55- self ._api_token : t .Optional [str ] = None
56- self ._api_token_exp : t .Optional [datetime ] = None
57- self ._disable_auth : bool = _disable_auth
5854 self ._session = session or self ._create_session ()
5955
56+ _auth = _auth or _FlareApiKeyAuth (
57+ api_key = api_key ,
58+ api_domain = self ._api_domain ,
59+ tenant_id = tenant_id ,
60+ session = self ._session ,
61+ )
62+ self ._session .auth = _auth
63+
6064 @classmethod
6165 def from_env (cls ) -> "FlareApiClient" :
6266 api_key : t .Optional [str ] = os .environ .get ("FLARE_API_KEY" )
@@ -110,41 +114,7 @@ def _create_retry() -> Retry:
110114 return retry
111115
112116 def generate_token (self ) -> str :
113- payload : t .Optional [dict ] = None
114-
115- if self ._tenant_id is not None :
116- payload = {
117- "tenant_id" : self ._tenant_id ,
118- }
119-
120- resp = self ._session .post (
121- f"https://{ self ._api_domain } /tokens/generate" ,
122- json = payload ,
123- headers = {
124- "Authorization" : self ._api_key ,
125- },
126- )
127- try :
128- resp .raise_for_status ()
129- except Exception as ex :
130- raise TokenError ("Failed to fetch API Token" ) from ex
131- token : str = resp .json ()["token" ]
132-
133- self ._api_token = token
134- self ._api_token_exp = datetime .now () + timedelta (minutes = 45 )
135-
136- return token
137-
138- def _auth_headers (self ) -> dict :
139- if self ._disable_auth :
140- return dict ()
141- api_token : t .Optional [str ] = self ._api_token
142- if not api_token or (
143- self ._api_token_exp and self ._api_token_exp < datetime .now ()
144- ):
145- api_token = self .generate_token ()
146-
147- return {"Authorization" : f"Bearer { api_token } " }
117+ return self ._auth .generate_token ()
148118
149119 def _request (
150120 self ,
@@ -163,11 +133,6 @@ def _request(
163133 f"Client was used to access { netloc = } at { url = } . Only the domain { self ._api_domain } is supported."
164134 )
165135
166- headers = {
167- ** (headers or {}),
168- ** self ._auth_headers (),
169- }
170-
171136 return self ._session .request (
172137 method = method ,
173138 url = url ,
0 commit comments