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:
Name
Type
Description
id_token
str | bool
Token used for identity verification, initialized as False.
api_key
str | bool
API key for authentication, initialized as False.
model_key
bool
Placeholder for model key, initialized as False.
Handles API key validation, Google Colab authentication, and new key requests. Updates SETTINGS upon successful
authentication.
def__init__(self,api_key:str="",verbose:bool=False):""" Initialize Auth class and authenticate user. Handles API key validation, Google Colab authentication, and new key requests. Updates SETTINGS upon successful authentication. Args: api_key (str): API key or combined key_id format. verbose (bool): Enable verbose logging. """# Split the input API key in case it contains a combined key_model and keep only the API key partapi_key=api_key.split("_")[0]# Set API key attribute as value passed or SETTINGS API key if none passedself.api_key=api_keyorSETTINGS.get("api_key","")# If an API key is providedifself.api_key:# If the provided API key matches the API key in the SETTINGSifself.api_key==SETTINGS.get("api_key"):# Log that the user is already logged inifverbose:LOGGER.info(f"{PREFIX}Authenticated ✅")returnelse:# Attempt to authenticate with the provided API keysuccess=self.authenticate()# If the API key is not provided and the environment is a Google Colab notebookelifIS_COLAB:# Attempt to authenticate using browser cookiessuccess=self.auth_with_cookies()else:# Request an API keysuccess=self.request_api_key()# Update SETTINGS with the new API key after successful authenticationifsuccess:SETTINGS.update({"api_key":self.api_key})# Log that the new login was successfulifverbose:LOGGER.info(f"{PREFIX}New authentication successful ✅")elifverbose:LOGGER.info(f"{PREFIX}Get API key from {API_KEY_URL} and then run 'yolo login API_KEY'")
auth_with_cookies
auth_with_cookies()->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:
Type
Description
bool
True if authentication is successful, False otherwise.
defauth_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. """ifnotIS_COLAB:returnFalse# Currently only works with Colabtry:authn=request_with_credentials(f"{HUB_API_ROOT}/v1/auth/auto")ifauthn.get("success",False):self.id_token=authn.get("data",{}).get("idToken",None)self.authenticate()returnTrueraiseConnectionError("Unable to fetch browser authentication details.")exceptConnectionError:self.id_token=False# reset invalidreturnFalse
authenticate
authenticate()->bool
Attempt to authenticate with the server using either id_token or API key.
Returns:
Type
Description
bool
True if authentication is successful, False otherwise.
defauthenticate(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:ifheader:=self.get_auth_header():r=requests.post(f"{HUB_API_ROOT}/v1/auth",headers=header)ifnotr.json().get("success",False):raiseConnectionError("Unable to authenticate.")returnTrueraiseConnectionError("User has not authenticated locally.")exceptConnectionError:self.id_token=self.api_key=False# reset invalidLOGGER.warning(f"{PREFIX}Invalid API key ⚠️")returnFalse
get_auth_header
get_auth_header()
Get the authentication header for making API requests.
Returns:
Type
Description
dict | None
The authentication header if id_token or API key is set, None otherwise.
defget_auth_header(self):""" Get the authentication header for making API requests. Returns: (dict | None): The authentication header if id_token or API key is set, None otherwise. """ifself.id_token:return{"authorization":f"Bearer {self.id_token}"}elifself.api_key:return{"x-api-key":self.api_key}
defrequest_api_key(self,max_attempts:int=3)->bool:"""Prompt the user to input their API key."""importgetpassforattemptsinrange(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 presentifself.authenticate():returnTrueraiseConnectionError(emojis(f"{PREFIX}Failed to authenticate ❌"))