์ฝ˜ํ…์ธ ๋กœ ๊ฑด๋„ˆ๋›ฐ๊ธฐ

์ฐธ์กฐ ultralytics/hub/auth.py

์ฐธ๊ณ 

์ด ํŒŒ์ผ์€ https://github.com/ultralytics/ ultralytics/blob/main/ ultralytics/hub/auth .py์—์„œ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ฌธ์ œ๋ฅผ ๋ฐœ๊ฒฌํ•˜๋ฉด ํ’€ ๋ฆฌํ€˜์ŠคํŠธ (๐Ÿ› ๏ธ)๋ฅผ ์ œ๊ณตํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๋„๋ก ๋„์™€์ฃผ์„ธ์š”. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ™!



ultralytics.hub.auth.Auth

API ํ‚ค ์ฒ˜๋ฆฌ, ์ฟ ํ‚ค ๊ธฐ๋ฐ˜ ์ธ์ฆ, ํ—ค๋” ์ƒ์„ฑ์„ ํฌํ•จํ•œ ์ธ์ฆ ํ”„๋กœ์„ธ์Šค๋ฅผ ๊ด€๋ฆฌํ•ฉ๋‹ˆ๋‹ค.

์ด ํด๋ž˜์Šค๋Š” ๋‹ค์–‘ํ•œ ์ธ์ฆ ๋ฐฉ๋ฒ•์„ ์ง€์›ํ•ฉ๋‹ˆ๋‹ค: 1. API ํ‚ค๋ฅผ ์ง์ ‘ ์‚ฌ์šฉ. 2. ๋ธŒ๋ผ์šฐ์ € ์ฟ ํ‚ค๋ฅผ ์‚ฌ์šฉํ•œ ์ธ์ฆ(ํŠนํžˆ Google Colab์—์„œ). 3. ์‚ฌ์šฉ์ž์—๊ฒŒ API ํ‚ค๋ฅผ ์ž…๋ ฅํ•˜๋ผ๋Š” ๋ฉ”์‹œ์ง€ ํ‘œ์‹œ.

์†์„ฑ:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช…
id_token str or bool

์‹ ์› ํ™•์ธ์— ์‚ฌ์šฉ๋˜๋Š” ํ† ํฐ์œผ๋กœ, ์ดˆ๊ธฐํ™” ์‹œ False๋กœ ์„ค์ •๋ฉ๋‹ˆ๋‹ค.

api_key str or bool

์ธ์ฆ์šฉ API ํ‚ค๋กœ, ์ดˆ๊ธฐํ™” ์‹œ False๋กœ ์„ค์ •๋ฉ๋‹ˆ๋‹ค.

model_key bool

๋ชจ๋ธ ํ‚ค์˜ ํ”Œ๋ ˆ์ด์Šคํ™€๋”๋กœ, ์ดˆ๊ธฐํ™” ์‹œ False๋กœ ์„ค์ •๋ฉ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/hub/auth.py
class Auth:
    """
    Manages authentication processes including API key handling, cookie-based authentication, and header generation.

    The class supports different methods of authentication:
    1. Directly using an API key.
    2. Authenticating using browser cookies (specifically in Google Colab).
    3. Prompting the user to enter an API key.

    Attributes:
        id_token (str or bool): Token used for identity verification, initialized as False.
        api_key (str or bool): API key for authentication, initialized as False.
        model_key (bool): Placeholder for model key, initialized as False.
    """

    id_token = api_key = model_key = False

    def __init__(self, api_key="", verbose=False):
        """
        Initialize the Auth class with an optional API key.

        Args:
            api_key (str, optional): May be an API key or a combination API key and model ID, i.e. key_id
        """
        # Split the input API key in case it contains a combined key_model and keep only the API key part
        api_key = api_key.split("_")[0]

        # Set API key attribute as value passed or SETTINGS API key if none passed
        self.api_key = api_key or SETTINGS.get("api_key", "")

        # If an API key is provided
        if self.api_key:
            # If the provided API key matches the API key in the SETTINGS
            if self.api_key == SETTINGS.get("api_key"):
                # Log that the user is already logged in
                if verbose:
                    LOGGER.info(f"{PREFIX}Authenticated โœ…")
                return
            else:
                # Attempt to authenticate with the provided API key
                success = self.authenticate()
        # If the API key is not provided and the environment is a Google Colab notebook
        elif IS_COLAB:
            # Attempt to authenticate using browser cookies
            success = self.auth_with_cookies()
        else:
            # Request an API key
            success = self.request_api_key()

        # Update SETTINGS with the new API key after successful authentication
        if success:
            SETTINGS.update({"api_key": self.api_key})
            # Log that the new login was successful
            if verbose:
                LOGGER.info(f"{PREFIX}New authentication successful โœ…")
        elif verbose:
            LOGGER.info(f"{PREFIX}Get API key from {API_KEY_URL} and then run 'yolo hub login API_KEY'")

    def request_api_key(self, max_attempts=3):
        """
        Prompt the user to input their API key.

        Returns the model ID.
        """
        import getpass

        for attempts in range(max_attempts):
            LOGGER.info(f"{PREFIX}Login. Attempt {attempts + 1} of {max_attempts}")
            input_key = getpass.getpass(f"Enter API key from {API_KEY_URL} ")
            self.api_key = input_key.split("_")[0]  # remove model id if present
            if self.authenticate():
                return True
        raise ConnectionError(emojis(f"{PREFIX}Failed to authenticate โŒ"))

    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.
        """
        try:
            if header := self.get_auth_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:
            self.id_token = self.api_key = False  # reset invalid
            LOGGER.warning(f"{PREFIX}Invalid API key โš ๏ธ")
            return False

    def auth_with_cookies(self) -> bool:
        """
        Attempt to fetch authentication via cookies and set id_token. User must be logged in to HUB and running in a
        supported browser.

        Returns:
            (bool): True if authentication is successful, False otherwise.
        """
        if not IS_COLAB:
            return False  # Currently only works with Colab
        try:
            authn = request_with_credentials(f"{HUB_API_ROOT}/v1/auth/auto")
            if authn.get("success", False):
                self.id_token = authn.get("data", {}).get("idToken", None)
                self.authenticate()
                return True
            raise ConnectionError("Unable to fetch browser authentication details.")
        except ConnectionError:
            self.id_token = False  # reset invalid
            return False

    def get_auth_header(self):
        """
        Get the authentication header for making API requests.

        Returns:
            (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}

__init__(api_key='', verbose=False)

์„ ํƒ์  API ํ‚ค๋กœ Auth ํด๋ž˜์Šค๋ฅผ ์ดˆ๊ธฐํ™”ํ•ฉ๋‹ˆ๋‹ค.

๋งค๊ฐœ๋ณ€์ˆ˜:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช… ๊ธฐ๋ณธ๊ฐ’
api_key str

API ํ‚ค ๋˜๋Š” API ํ‚ค์™€ ๋ชจ๋ธ ID์˜ ์กฐํ•ฉ(์˜ˆ: key_id)์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

''
์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/hub/auth.py
def __init__(self, api_key="", verbose=False):
    """
    Initialize the Auth class with an optional API key.

    Args:
        api_key (str, optional): May be an API key or a combination API key and model ID, i.e. key_id
    """
    # Split the input API key in case it contains a combined key_model and keep only the API key part
    api_key = api_key.split("_")[0]

    # Set API key attribute as value passed or SETTINGS API key if none passed
    self.api_key = api_key or SETTINGS.get("api_key", "")

    # If an API key is provided
    if self.api_key:
        # If the provided API key matches the API key in the SETTINGS
        if self.api_key == SETTINGS.get("api_key"):
            # Log that the user is already logged in
            if verbose:
                LOGGER.info(f"{PREFIX}Authenticated โœ…")
            return
        else:
            # Attempt to authenticate with the provided API key
            success = self.authenticate()
    # If the API key is not provided and the environment is a Google Colab notebook
    elif IS_COLAB:
        # Attempt to authenticate using browser cookies
        success = self.auth_with_cookies()
    else:
        # Request an API key
        success = self.request_api_key()

    # Update SETTINGS with the new API key after successful authentication
    if success:
        SETTINGS.update({"api_key": self.api_key})
        # Log that the new login was successful
        if verbose:
            LOGGER.info(f"{PREFIX}New authentication successful โœ…")
    elif verbose:
        LOGGER.info(f"{PREFIX}Get API key from {API_KEY_URL} and then run 'yolo hub login API_KEY'")

auth_with_cookies()

์ฟ ํ‚ค๋ฅผ ํ†ตํ•œ ์ธ์ฆ ๊ฐ€์ ธ์˜ค๊ธฐ๋ฅผ ์‹œ๋„ํ•˜๊ณ  id_token์„ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค. ์‚ฌ์šฉ์ž๋Š” HUB์— ๋กœ๊ทธ์ธํ•˜๊ณ  ์ง€์›๋˜๋Š” ๋ธŒ๋ผ์šฐ์ €์—์„œ ์ง€์›๋˜๋Š” ๋ธŒ๋ผ์šฐ์ €์—์„œ ์‹คํ–‰ ์ค‘์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค:

์œ ํ˜• ์„ค๋ช…
bool

์ธ์ฆ์— ์„ฑ๊ณตํ•˜๋ฉด ์ฐธ์ด๊ณ , ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ๊ฑฐ์ง“์ž…๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/hub/auth.py
def auth_with_cookies(self) -> bool:
    """
    Attempt to fetch authentication via cookies and set id_token. User must be logged in to HUB and running in a
    supported browser.

    Returns:
        (bool): True if authentication is successful, False otherwise.
    """
    if not IS_COLAB:
        return False  # Currently only works with Colab
    try:
        authn = request_with_credentials(f"{HUB_API_ROOT}/v1/auth/auto")
        if authn.get("success", False):
            self.id_token = authn.get("data", {}).get("idToken", None)
            self.authenticate()
            return True
        raise ConnectionError("Unable to fetch browser authentication details.")
    except ConnectionError:
        self.id_token = False  # reset invalid
        return False

authenticate()

id_token ๋˜๋Š” API ํ‚ค๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์„œ๋ฒ„์— ์ธ์ฆ์„ ์‹œ๋„ํ•ฉ๋‹ˆ๋‹ค.

๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค:

์œ ํ˜• ์„ค๋ช…
bool

์ธ์ฆ์— ์„ฑ๊ณตํ•˜๋ฉด ์ฐธ์ด๊ณ , ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ๊ฑฐ์ง“์ž…๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/hub/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.
    """
    try:
        if header := self.get_auth_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:
        self.id_token = self.api_key = False  # reset invalid
        LOGGER.warning(f"{PREFIX}Invalid API key โš ๏ธ")
        return False

get_auth_header()

API ์š”์ฒญ์„ ์œ„ํ•œ ์ธ์ฆ ํ—ค๋”๋ฅผ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค.

๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค:

์œ ํ˜• ์„ค๋ช…
dict

id_token ๋˜๋Š” API ํ‚ค๊ฐ€ ์„ค์ •๋œ ๊ฒฝ์šฐ ์ธ์ฆ ํ—ค๋”, ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ์—†์Œ์ž…๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/hub/auth.py
def get_auth_header(self):
    """
    Get the authentication header for making API requests.

    Returns:
        (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}

request_api_key(max_attempts=3)

์‚ฌ์šฉ์ž์—๊ฒŒ API ํ‚ค๋ฅผ ์ž…๋ ฅํ•˜๋ผ๋Š” ๋ฉ”์‹œ์ง€๋ฅผ ํ‘œ์‹œํ•ฉ๋‹ˆ๋‹ค.

๋ชจ๋ธ ID๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/hub/auth.py
def request_api_key(self, max_attempts=3):
    """
    Prompt the user to input their API key.

    Returns the model ID.
    """
    import getpass

    for attempts in range(max_attempts):
        LOGGER.info(f"{PREFIX}Login. Attempt {attempts + 1} of {max_attempts}")
        input_key = getpass.getpass(f"Enter API key from {API_KEY_URL} ")
        self.api_key = input_key.split("_")[0]  # remove model id if present
        if self.authenticate():
            return True
    raise ConnectionError(emojis(f"{PREFIX}Failed to authenticate โŒ"))





์ƒ์„ฑ 2023-11-12, ์—…๋ฐ์ดํŠธ 2023-11-25
์ž‘์„ฑ์ž: glenn-jocher (3)