跳至内容

参考资料 hub_sdk/base/auth.py

备注

该文件可在https://github.com/ultralytics/hub-sdk/blob/main/hub_sdk/base/auth.py 上获取。如果您发现问题,请通过提交 Pull Request🛠️ 帮助修复。谢谢🙏!



hub_sdk.base.auth.Auth

代表身份验证管理器。

属性

名称 类型 说明
api_key (str, None)

用于身份验证的 API 密钥。

id_token (str, None)

身份验证令牌。

源代码 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__()

使用默认身份验证设置初始化 Auth 类。

源代码 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()

尝试使用 id_token 或 API 密钥与服务器进行身份验证。

返回:

类型 说明
bool

如果验证成功则为 True,否则为 False。

加薪:

类型 说明
ConnectionError

如果请求响应失败,则引发连接错误异常。

源代码 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)

通过带有电子邮件和密码的 POST 请求获取 idToken,从而对用户进行授权。

参数

名称 类型 说明 默认值
email str

用户电子邮件。

所需
password str

用户密码。

所需

返回:

类型 说明
bool

如果授权成功则为 True,否则为 False。

源代码 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()

获取用于发出 API 请求的验证头信息。

返回:

类型 说明
Optional[dict]

如果设置了 id_token 或 API 密钥,则为身份验证标头,否则为空。

源代码 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()

获取身份验证状态。

返回:

类型 说明
bool

如果设置了 id_token 或 API 密钥,则为 True,否则为 False。

源代码 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)

设置用于身份验证的 API 密钥。

参数

名称 类型 说明 默认值
key str

API 密钥字符串。

所需
源代码 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