Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: add warning to Client.login #378

Merged
merged 4 commits into from
Aug 9, 2023
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- `wait_completion` param on `get_performances`, `list_task_output_assets` and `get_task_output_asset` to block execution until execution is over ([#368](https://github.com/Substra/substra/pull/368))
- `list_task_output_assets` and `get_task_output_asset` wait that the compute task is over before getting assets ([#369](https://github.com/Substra/substra/pull/369))
- warning and help message when logging in with username/password rather than token ([#378](https://github.com/Substra/substra/pull/378))

## [0.46.0](https://github.com/Substra/substra/releases/tag/0.46.0) - 2023-07-25

Expand Down
35 changes: 34 additions & 1 deletion substra/sdk/backends/remote/rest_client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import json
import logging
import time
from datetime import datetime
from datetime import timedelta
from datetime import timezone
from typing import Dict
from typing import List
from typing import Union
Expand All @@ -15,6 +18,22 @@
logger = logging.getLogger(__name__)


def _warn_of_session_expiration(expiration: str) -> None:
log_level = logging.INFO
try:
duration = datetime.fromisoformat(expiration) - datetime.now(timezone.utc)
if duration.days:
duration_msg = f"{duration.days} days"
else:
duration_msg = f"{duration.seconds//3600} hours"
expires_at = f"in {duration_msg} ({expiration})"
if duration < timedelta(hours=4):
log_level = logging.WARNING
except ValueError: # Python 3.11 parses more formats than previous versions
expires_at = expiration
logger.log(log_level, f"Your session will expire {expires_at}")


class Client:
"""REST Client to communicate with Substra server."""

Expand Down Expand Up @@ -60,17 +79,31 @@ def login(self, username, password):
if e.response.status_code in (400, 401):
raise exceptions.BadLoginException.from_request_exception(e)

if (
e.response.status_code == 403
and getattr(e.response, "substra_identifier", None) == "implicit_login_disabled"
):
raise exceptions.UsernamePasswordLoginDisabledException.from_request_exception(e)

raise exceptions.HTTPError.from_request_exception(e)

try:
token = r.json()["token"]
rj = r.json()
token = rj["token"]
except json.decoder.JSONDecodeError:
# sometimes requests seem to be fine, but the json is not being found
# this might be if the url seems to be correct (in the syntax)
# but it's not the right one
raise exceptions.BadConfiguration(
"Unable to get token from json response. " f"Make sure that given url: {self._base_url} is correct"
)

logger.info(
"Logging in with username/password is discouraged; "
"you should generate a token on the web UI instead: "
"https://docs.substra.org/en/stable/documentation/api_tokens_generation.html"
)
_warn_of_session_expiration(rj["expires_at"])
self._headers["Authorization"] = f"Token {token}"

return token
Expand Down
18 changes: 18 additions & 0 deletions substra/sdk/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,24 @@ class BadLoginException(RequestException):
pass


class UsernamePasswordLoginDisabledException(RequestException):
"""The server disabled the endpoint, preventing the use of Client.login"""

@classmethod
def from_request_exception(cls, request_exception):
base = super().from_request_exception(request_exception)
return cls(
base.msg
+ (
"\n\nAuthenticating with username/password is disabled.\n"
"Log onto the frontend for your instance and generate a token there, "
'then use it in the Client(token="...") constructor: '
"https://docs.substra.org/en/stable/documentation/api_tokens_generation.html"
),
base.status_code,
)


class ConfigurationInfoError(SDKException):
"""ConfigurationInfoError"""

Expand Down
Loading