Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/openfoodfacts/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@
request_args["cookies"] = request_args.get("cookies", dict()) | {
"session": api_config.session_cookie,
}
elif api_config.access_token:
request_args["headers"] = request_args.get("headers", dict()) | {

Check warning on line 62 in src/openfoodfacts/api.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace this constructor call with a literal.

See more on https://sonarcloud.io/project/issues?id=openfoodfacts_openfoodfacts-python&issues=AZ3d8QTDQqRoMzptVq1p&open=AZ3d8QTDQqRoMzptVq1p&pullRequest=476
"Authorization": f"Bearer {api_config.access_token}",
}
if "auth" not in request_args:
request_args["auth"] = get_http_auth(api_config.environment)

Expand Down Expand Up @@ -595,6 +599,7 @@
environment: Union[Environment, str] = Environment.org,
session_cookie: Optional[str] = None,
timeout: int = 10,
access_token: Optional[str] = None,
) -> None:
"""Initialize the API instance.

Expand All @@ -615,6 +620,8 @@
:param session_cookie: a session cookie, only used for write requests,
defaults to None
:param timeout: the timeout for HTTP requests, defaults to 10 seconds
:param access_token: a keycloak access token, generated with single sign on,
only used for write requests, defaults to None
"""
if not isinstance(country, Country):
country = Country[country]
Expand All @@ -632,6 +639,7 @@
password=password,
session_cookie=session_cookie,
timeout=timeout,
access_token=access_token,
)
self.password = password
self.country = country
Expand Down
10 changes: 9 additions & 1 deletion src/openfoodfacts/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -861,6 +861,7 @@ class APIConfig(BaseModel):
password: Optional[str] = None
session_cookie: Optional[str] = None
timeout: float = 10.0
access_token: Optional[str] = None

@model_validator(mode="after")
def check_credentials(self):
Expand All @@ -875,7 +876,14 @@ def check_credentials(self):
raise ValueError(
"username/password and session_cookie are mutually exclusive"
)

if self.username and self.access_token:
raise ValueError(
"username/password and access_token are mutually exclusive"
)
if self.session_cookie and self.access_token:
raise ValueError(
"session_cookie and access_token are mutually exclusive"
)
return self

@model_validator(mode="after")
Expand Down
Loading