Skip to content

Commit

Permalink
feat: add possibility to use an existing bearer token (w/o client+sec…
Browse files Browse the repository at this point in the history
…ret) (#27)

* feat: add possibility to use an existing bearer token (w/o client+secret)

* linter
  • Loading branch information
hf-kklein authored Mar 20, 2024
1 parent 8ee7bb9 commit 92f8775
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
2 changes: 1 addition & 1 deletion src/bssclient/client/bssclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ def __init__(self, config: OAuthBssConfig):
oauth_token_url=str(config.token_url),
)
self._oauth_config = config
self._bearer_token: str | None = None
self._bearer_token: str | None = config.bearer_token if config.bearer_token else None

async def _get_session(self) -> ClientSession:
"""
Expand Down
32 changes: 23 additions & 9 deletions src/bssclient/client/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
contains a class with which the BSS client is instantiated/configured
"""

from pydantic import BaseModel, ConfigDict, HttpUrl, field_validator
from pydantic import BaseModel, ConfigDict, HttpUrl, field_validator, model_validator
from yarl import URL


Expand Down Expand Up @@ -78,13 +78,27 @@ class OAuthBssConfig(BssConfig):
Url of the token endpoint; e.g. 'https://lynqtech-dev-auth-server.auth.eu-central-1.amazoncognito.com/oauth2/token'
"""

# pylint:disable=no-self-argument
@field_validator("client_id", "client_secret")
def validate_string_is_not_empty(cls, value):
bearer_token: str | None = None
"""
You may optionally provide a 'hardcoded' bearer token here. As long as its valid, it's used for requests and the
client id and secret are not used.
This is useful when you have ways to get a token but not a client id and secret.
"""

@model_validator(mode="after")
def check_secret_or_token_is_present(cls, values): # pylint:disable=no-self-argument
"""
Check that no one tries to bypass validation with empty strings.
If we had wanted that you can omit values, we had used Optional[str] instead of str.
Ensures that either (id+secret) or a bare token are present
"""
if not value.strip():
raise ValueError("my_string cannot be empty")
return value
token_is_present = values.bearer_token is not None and values.bearer_token.strip()
client_id_and_secret_are_present = (
values.client_id is not None
and values.client_id.strip()
and values.client_secret is not None
and values.client_secret.strip()
)
if not token_is_present and not client_id_and_secret_are_present:
raise ValueError(
# pylint:disable=line-too-long
"You must provide either client id and secret or a bearer token, but not None of both"
)

0 comments on commit 92f8775

Please sign in to comment.