Skip to content
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
194 changes: 172 additions & 22 deletions skore-hub-project/src/skore_hub_project/authentication/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,185 @@
from __future__ import annotations

from contextlib import suppress
from datetime import datetime
from time import sleep
from webbrowser import open as open_webbrowser

from httpx import HTTPError
from httpx import HTTPError, HTTPStatusError, TimeoutException
from rich.align import Align
from rich.panel import Panel

from .. import console
from ..client import api
from . import token as Token
from .logout import logout
from .token import TokenError, access
from .token import persist as persist_token
from .uri import URI, URIError
from .uri import persist as persist_URI


def get_oauth_device_login(success_uri: str | None = None):
"""
Initiate device OAuth flow.

Initiates the OAuth device flow.
Provides the user with a URL and a OTP code to authenticate the device.

Parameters
----------
success_uri : str, optional
The URI to redirect to after successful authentication.
If not provided, defaults to None.

Returns
-------
tuple
A tuple containing:
- authorization_url: str
The URL to which the user needs to navigate
- device_code: str
The device code used for authentication
- user_code: str
The user code that needs to be entered on the authorization page
"""
from skore_hub_project.client.client import HUBClient

url = "identity/oauth/device/login"
params = {"success_uri": success_uri} if success_uri is not None else {}

with HUBClient(authenticated=False) as client:
response = client.get(url, params=params).json()

return (
response["authorization_url"],
response["device_code"],
response["user_code"],
)


def get_oauth_device_code_probe(device_code: str, *, timeout=600):
"""
Ensure authorization code is acknowledged.

Start polling, wait for the authorization code to be acknowledged by the hub.
This is mandatory to be authorize to exchange with a token.

Parameters
----------
device_code : str
The device code to exchange for tokens.
"""
from skore_hub_project.client.client import HUBClient

url = "identity/oauth/device/code-probe"
params = {"device_code": device_code}

with HUBClient(authenticated=False) as client:
start = datetime.now()

while True:
try:
client.get(url, params=params)
except HTTPStatusError as exc:
if exc.response.status_code != 400:
raise

if (datetime.now() - start).total_seconds() >= timeout:
raise TimeoutException("Authentication timeout") from exc

sleep(0.5)
else:
break


def post_oauth_device_callback(state: str, user_code: str):
"""
Validate the user-provided device code.

This endpoint verifies the code entered by the user during the device auth flow.

Parameters
----------
state: str
The unique value identifying the device flow.
user_code: str
The code entered by the user.
"""
from skore_hub_project.client.client import HUBClient

url = "identity/oauth/device/callback"
data = {"state": state, "user_code": user_code}

with HUBClient(authenticated=False) as client:
client.post(url, data=data)


def get_oauth_device_token(device_code: str):
"""
Exchanges the device code for an access token.

This endpoint completes the device authorization flow
by exchanging the validated device code for an access token.

Parameters
----------
device_code : str
The device code to exchange for tokens

Returns
-------
tuple
A tuple containing:
- access_token : str
The OAuth access token
- refresh_token : str
The OAuth refresh token
- expires_at : str
The expiration datetime as ISO 8601 str of the access token
"""
from skore_hub_project.client.client import HUBClient

url = "identity/oauth/device/token"
params = {"device_code": device_code}

with HUBClient(authenticated=False) as client:
response = client.get(url, params=params).json()
tokens = response["token"]

return (
tokens["access_token"],
tokens["refresh_token"],
tokens["expires_at"],
)


def login(*, timeout=600):
"""Login to ``skore hub``."""
with suppress(HTTPError):
if Token.exists() and (Token.access() is not None):
console.print(
Panel(
Align(
"Already logged in!",
align="center",
),
title="[cyan]Skore Hub[/cyan]",
border_style="orange1",
expand=False,
padding=1,
title_align="center",
)
with suppress(URIError, TokenError, HTTPError):
# Avoid re-login when
# - the persisted URI is not conflicting with the envar
# - the persisted token is valid or can be refreshed
URI()
access(refresh=True)

console.print(
Panel(
Align(
"Already logged in!",
align="center",
),
title="[cyan]Skore Hub[/cyan]",
border_style="orange1",
expand=False,
padding=1,
title_align="center",
)
return
)

return

url, device_code, user_code = api.get_oauth_device_login()
logout()

url, device_code, user_code = get_oauth_device_login()

console.rule("[cyan]Skore Hub[/cyan]")
console.print(
Expand All @@ -43,6 +191,8 @@ def login(*, timeout=600):

open_webbrowser(url)

api.get_oauth_device_code_probe(device_code, timeout=timeout)
api.post_oauth_device_callback(device_code, user_code)
Token.save(*api.get_oauth_device_token(device_code))
get_oauth_device_code_probe(device_code, timeout=timeout)
post_oauth_device_callback(device_code, user_code)

persist_token(*get_oauth_device_token(device_code))
persist_URI(URI())
10 changes: 4 additions & 6 deletions skore-hub-project/src/skore_hub_project/authentication/logout.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
"""Logout from ``skore hub``."""

from __future__ import annotations

from . import token as Token
from . import token, uri


def logout():
"""Logout from ``skore hub`` by deleting tokens."""
if Token.exists():
Token.filepath().unlink()
"""Logout from ``skore hub`` by deleting the persisted token."""
token.Filepath().unlink(missing_ok=True)
uri.Filepath().unlink(missing_ok=True)
84 changes: 60 additions & 24 deletions skore-hub-project/src/skore_hub_project/authentication/token.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,76 @@
"""Token used for ``skore hub`` authentication."""

from __future__ import annotations

import json
import pathlib
import tempfile
from datetime import datetime, timezone
from json import dumps, loads
from pathlib import Path
from tempfile import gettempdir


from ..client.api import post_oauth_refresh_token
class TokenError(Exception):
"""An exception dedicated to ``Token``."""


def filepath():
"""Filepath used to save the tokens on disk."""
return pathlib.Path(tempfile.gettempdir(), "skore.token")
def post_oauth_refresh_token(refresh_token: str):
"""
Refresh an access token using a provided refresh token.

This endpoint allows a client to obtain a new access token
by providing a valid refresh token.

def save(access: str, refreshment: str, expires_at: str):
Parameters
----------
refresh_token : str
A valid refresh token

Returns
-------
tuple
A tuple containing:
- access_token : str
The OAuth access token
- refresh_token : str
The OAuth refresh token
- expires_at : str
The expiration datetime as ISO 8601 str of the access token
"""
Save the token.
from skore_hub_project.client.client import HUBClient

url = "identity/oauth/token/refresh"
json = {"refresh_token": refresh_token}

with HUBClient(authenticated=False) as client:
response = client.post(url, json=json).json()

return (
response["access_token"],
response["refresh_token"],
response["expires_at"],
)

Save the tokens to the disk to prevent user to login more than once, as long as

def Filepath() -> Path:
"""Filepath used to persist the token on disk."""
return Path(gettempdir(), "skore.token")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that we have a opportunity here to manage multiple environments by using SKORE_HUB_URI value to generate this file name, what do you think ?



def persist(access: str, refreshment: str, expiration: str):
"""
Persist the token.

Persist the token on disk to prevent user to login more than once, as long as
the access token is valid or can be refreshed.
"""
filepath().write_text(
json.dumps(
(
Filepath().write_text(
dumps(
[
access,
refreshment,
expires_at,
)
expiration,
]
)
)


def exists() -> bool:
"""Existence of the token."""
return filepath().exists()


def access(*, refresh=True) -> str:
"""
Access token.
Expand All @@ -47,13 +80,16 @@ def access(*, refresh=True) -> str:
refresh : bool, optional
Refresh the token on-the-fly if necessary, default True.
"""
access, refreshment, expiration = json.loads(filepath().read_text())
if not Filepath().exists():
raise TokenError("You are not logged in. Please run `skore-hub-login`.")

access, refreshment, expiration = loads(Filepath().read_text())

if refresh and datetime.fromisoformat(expiration) <= datetime.now(timezone.utc):
# Retrieve freshly updated tokens
access, refreshment, expiration = post_oauth_refresh_token(refreshment)

# Re-save the refreshed tokens
save(access, refreshment, expiration)
persist(access, refreshment, expiration)

return access
44 changes: 44 additions & 0 deletions skore-hub-project/src/skore_hub_project/authentication/uri.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""URI used for ``skore hub`` authentication."""

from os import environ
from pathlib import Path
from tempfile import gettempdir
from typing import Final

DEFAULT: Final[str] = "https://api.skore.probabl.ai"
ENVARNAME: Final[str] = "SKORE_HUB_URI"


class URIError(RuntimeError):
"""An exception dedicated to ``URI``."""


def Filepath() -> Path:
"""Filepath used to save the URI on disk."""
return Path(gettempdir(), "skore.uri")


def persist(uri: str):
"""Persist the URI."""
Filepath().write_text(uri)


def URI() -> str:
"""URI used for ``skore hub`` authentication."""
filepath = Filepath()
uri_from_persistence = filepath.read_text() if filepath.exists() else None
uri_from_environment = environ.get(ENVARNAME)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my opinion env var should override previous choices of the user. As I stated above it could be really nice to handle multiple env transparently for the users.
I fou switched env you probably want to be authenticated directly instead of having to manually log out.


if (
uri_from_persistence
and uri_from_environment
and (uri_from_persistence != uri_from_environment)
):
raise URIError(
f"\nBad condition: the persisted URI is conflicting with the environment:\n"
f"\tFrom {filepath}: '{uri_from_persistence}'\n"
f"\tFrom ${ENVARNAME}: '{uri_from_environment}'\n"
f"\nPlease run `skore-hub-logout`."
)

return uri_from_persistence or uri_from_environment or DEFAULT
Loading