─░├žeri─če ge├ž

Referans i├žin hub_sdk/base/auth.py

Not

Bu dosya https://github.com/ultralytics/hub-sdk/blob/main/hub_sdk/base/auth .py adresinde mevcuttur. Bir sorun tespit ederseniz, l├╝tfen bir ├çekme ─░ste─či ­čŤá´ŞĆ ile katk─▒da bulunarak d├╝zeltmeye yard─▒mc─▒ olun. Te┼čekk├╝rler ­čÖĆ!



hub_sdk.base.auth.Auth

Bir kimlik do─črulama y├Âneticisini temsil eder.

Nitelikler:

─░sim Tip A├ž─▒klama
api_key (str, None)

Kimlik do─črulama i├žin kullan─▒lan API anahtar─▒.

id_token (str, None)

Kimlik do─črulama belirteci.

Kaynak kodu 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 s─▒n─▒f─▒n─▒ varsay─▒lan kimlik do─črulama ayarlar─▒yla ba┼člat─▒r.

Kaynak kodu 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 veya API anahtar─▒ kullanarak sunucu ile kimlik do─črulama giri┼čiminde bulunun.

─░ade:

Tip A├ž─▒klama
bool

Kimlik do─črulama ba┼čar─▒l─▒ysa True, aksi takdirde False.

Zamlar:

Tip A├ž─▒klama
ConnectionError

─░stek yan─▒t─▒ ba┼čar─▒s─▒z olursa, ba─člant─▒ hatas─▒ istisnas─▒n─▒ y├╝kseltin.

Kaynak kodu 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)

E-posta ve parola ile bir POST iste─či arac─▒l─▒─č─▒yla bir idToken alarak kullan─▒c─▒y─▒ yetkilendirin.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
email str

Kullan─▒c─▒n─▒n e-postas─▒.

gerekli
password str

Kullan─▒c─▒ ┼čifresi.

gerekli

─░ade:

Tip A├ž─▒klama
bool

Yetkilendirme ba┼čar─▒l─▒ olursa True, aksi takdirde False.

Kaynak kodu 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 istekleri yapmak i├žin kimlik do─črulama ba┼čl─▒─č─▒n─▒ al─▒n.

─░ade:

Tip A├ž─▒klama
Optional[dict]

id_token veya API anahtar─▒ ayarlanm─▒┼čsa kimlik do─črulama ba┼čl─▒─č─▒, aksi takdirde Yok.

Kaynak kodu 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()

Kimlik do─črulama durumunu al─▒n.

─░ade:

Tip A├ž─▒klama
bool

id_token veya API anahtar─▒ ayarlanm─▒┼čsa True, aksi takdirde False.

Kaynak kodu 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)

Kimlik do─črulama i├žin API anahtar─▒n─▒ ayarlay─▒n.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
key str

API anahtar dizesi.

gerekli
Kaynak kodu 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