Saltar al contenido

Referencia para hub_sdk/base/auth.py

Nota

Este archivo est谩 disponible en https://github.com/ultralytics/hub-sdk/blob/main/hub_sdk/base/auth .py. Si detectas alg煤n problema, por favor, ayuda a solucionarlo contribuyendo con una Pull Request 馃洜锔. 隆Gracias 馃檹!



hub_sdk.base.auth.Auth

Representa un gestor de autenticaci贸n.

Atributos:

Nombre Tipo Descripci贸n
api_key (str, None)

La clave API utilizada para la autenticaci贸n.

id_token (str, None)

El token de autenticaci贸n.

C贸digo fuente en hub_sdk/base/auth.py
class Auth:
    """
    Represents an authentication manager.

    Attributes:
        api_key (str, None): The API key used for authentication.
        id_token (str, None): The authentication token.
    """

    def __init__(self):
        """Initializes the Auth class with default authentication settings."""
        self.api_key = None
        self.id_token = None

    def authenticate(self) -> bool:
        """
        Attempt to authenticate with the server using either id_token or API key.

        Returns:
            (bool): True if authentication is successful, False otherwise.

        Raises:
            (ConnectionError): If request response fails, raise connection error exception.
        """
        try:
            header = self.get_auth_header()
            if header:
                r = requests.post(f"{HUB_API_ROOT}/v1/auth", headers=header)
                if not r.json().get("success", False):
                    raise ConnectionError("Unable to authenticate.")
                return True
            raise ConnectionError("User has not authenticated locally.")
        except ConnectionError:
            logger.warning(f"{PREFIX} Invalid API key 鈿狅笍")
        except requests.exceptions.RequestException as e:
            status_code = e.response.status_code if hasattr(e, "response") else None
            error_msg = ErrorHandler(status_code).handle()
            logger.warning(f"{PREFIX} {error_msg}")

        self.id_token = self.api_key = False  # reset invalid
        return False

    def get_auth_header(self) -> Optional[dict]:
        """
        Get the authentication header for making API requests.

        Returns:
            (Optional[dict]): The authentication header if id_token or API key is set, None otherwise.
        """
        if self.id_token:
            return {"authorization": f"Bearer {self.id_token}"}
        elif self.api_key:
            return {"x-api-key": self.api_key}
        else:
            return None

    def get_state(self) -> bool:
        """
        Get the authentication state.

        Returns:
            (bool): True if either id_token or API key is set, False otherwise.
        """
        return self.id_token or self.api_key

    def set_api_key(self, key: str):
        """
        Set the API key for authentication.

        Args:
            key (str): The API key string.
        """
        self.api_key = key

    def authorize(self, email: str, password: str) -> bool:
        """
        Authorize the user by obtaining an idToken through a POST request with email and password.

        Args:
            email (str): User's email.
            password (str): User's password.

        Returns:
            (bool): True if authorization is successful, False otherwise.
        """
        try:
            headers = {"origin": HUB_WEB_ROOT}
            response = requests.post(FIREBASE_AUTH_URL, json={"email": email, "password": password}, headers=headers)
            if response.status_code == 200:
                self.id_token = response.json().get("idToken")
                return True
            else:
                raise ConnectionError("Authorization failed.")
        except ConnectionError:
            logger.warning(f"{PREFIX} Invalid API key 鈿狅笍")
        except requests.exceptions.RequestException as e:
            status_code = e.response.status_code if hasattr(e, "response") else None
            error_msg = ErrorHandler(status_code).handle()
            logger.warning(f"{PREFIX} {error_msg}")

__init__()

Inicializa la clase Auth con la configuraci贸n de autenticaci贸n por defecto.

C贸digo fuente en hub_sdk/base/auth.py
def __init__(self):
    """Initializes the Auth class with default authentication settings."""
    self.api_key = None
    self.id_token = None

authenticate()

Intenta autenticarte con el servidor utilizando el id_token o la clave API.

Devuelve:

Tipo Descripci贸n
bool

Verdadero si la autenticaci贸n se realiza correctamente, Falso en caso contrario.

Aumenta:

Tipo Descripci贸n
ConnectionError

Si la respuesta a la solicitud falla, lanza una excepci贸n de error de conexi贸n.

C贸digo fuente en hub_sdk/base/auth.py
def authenticate(self) -> bool:
    """
    Attempt to authenticate with the server using either id_token or API key.

    Returns:
        (bool): True if authentication is successful, False otherwise.

    Raises:
        (ConnectionError): If request response fails, raise connection error exception.
    """
    try:
        header = self.get_auth_header()
        if header:
            r = requests.post(f"{HUB_API_ROOT}/v1/auth", headers=header)
            if not r.json().get("success", False):
                raise ConnectionError("Unable to authenticate.")
            return True
        raise ConnectionError("User has not authenticated locally.")
    except ConnectionError:
        logger.warning(f"{PREFIX} Invalid API key 鈿狅笍")
    except requests.exceptions.RequestException as e:
        status_code = e.response.status_code if hasattr(e, "response") else None
        error_msg = ErrorHandler(status_code).handle()
        logger.warning(f"{PREFIX} {error_msg}")

    self.id_token = self.api_key = False  # reset invalid
    return False

authorize(email, password)

Autoriza al usuario obteniendo un idToken mediante una petici贸n POST con email y contrase帽a.

Par谩metros:

Nombre Tipo Descripci贸n Por defecto
email str

Correo electr贸nico del usuario.

necesario
password str

Contrase帽a del usuario.

necesario

Devuelve:

Tipo Descripci贸n
bool

Verdadero si la autorizaci贸n se realiza correctamente, Falso en caso contrario.

C贸digo fuente en hub_sdk/base/auth.py
def authorize(self, email: str, password: str) -> bool:
    """
    Authorize the user by obtaining an idToken through a POST request with email and password.

    Args:
        email (str): User's email.
        password (str): User's password.

    Returns:
        (bool): True if authorization is successful, False otherwise.
    """
    try:
        headers = {"origin": HUB_WEB_ROOT}
        response = requests.post(FIREBASE_AUTH_URL, json={"email": email, "password": password}, headers=headers)
        if response.status_code == 200:
            self.id_token = response.json().get("idToken")
            return True
        else:
            raise ConnectionError("Authorization failed.")
    except ConnectionError:
        logger.warning(f"{PREFIX} Invalid API key 鈿狅笍")
    except requests.exceptions.RequestException as e:
        status_code = e.response.status_code if hasattr(e, "response") else None
        error_msg = ErrorHandler(status_code).handle()
        logger.warning(f"{PREFIX} {error_msg}")

get_auth_header()

Obt茅n la cabecera de autenticaci贸n para hacer peticiones a la API.

Devuelve:

Tipo Descripci贸n
Optional[dict]

La cabecera de autenticaci贸n si se establece id_token o clave API, Ninguna en caso contrario.

C贸digo fuente en hub_sdk/base/auth.py
def get_auth_header(self) -> Optional[dict]:
    """
    Get the authentication header for making API requests.

    Returns:
        (Optional[dict]): The authentication header if id_token or API key is set, None otherwise.
    """
    if self.id_token:
        return {"authorization": f"Bearer {self.id_token}"}
    elif self.api_key:
        return {"x-api-key": self.api_key}
    else:
        return None

get_state()

Obt茅n el estado de autenticaci贸n.

Devuelve:

Tipo Descripci贸n
bool

True si se ha establecido id_token o clave API, False en caso contrario.

C贸digo fuente en hub_sdk/base/auth.py
def get_state(self) -> bool:
    """
    Get the authentication state.

    Returns:
        (bool): True if either id_token or API key is set, False otherwise.
    """
    return self.id_token or self.api_key

set_api_key(key)

Establece la clave API para la autenticaci贸n.

Par谩metros:

Nombre Tipo Descripci贸n Por defecto
key str

La cadena de la clave API.

necesario
C贸digo fuente en hub_sdk/base/auth.py
def set_api_key(self, key: str):
    """
    Set the API key for authentication.

    Args:
        key (str): The API key string.
    """
    self.api_key = key