auth.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import requests
  3. from ultralytics.hub.utils import HUB_API_ROOT, HUB_WEB_ROOT, PREFIX, request_with_credentials
  4. from ultralytics.utils import IS_COLAB, LOGGER, SETTINGS, emojis
  5. API_KEY_URL = f"{HUB_WEB_ROOT}/settings?tab=api+keys"
  6. class Auth:
  7. """
  8. Manages authentication processes including API key handling, cookie-based authentication, and header generation.
  9. The class supports different methods of authentication:
  10. 1. Directly using an API key.
  11. 2. Authenticating using browser cookies (specifically in Google Colab).
  12. 3. Prompting the user to enter an API key.
  13. Attributes:
  14. id_token (str or bool): Token used for identity verification, initialized as False.
  15. api_key (str or bool): API key for authentication, initialized as False.
  16. model_key (bool): Placeholder for model key, initialized as False.
  17. """
  18. id_token = api_key = model_key = False
  19. def __init__(self, api_key="", verbose=False):
  20. """
  21. Initialize the Auth class with an optional API key.
  22. Args:
  23. api_key (str, optional): May be an API key or a combination API key and model ID, i.e. key_id
  24. """
  25. # Split the input API key in case it contains a combined key_model and keep only the API key part
  26. api_key = api_key.split("_")[0]
  27. # Set API key attribute as value passed or SETTINGS API key if none passed
  28. self.api_key = api_key or SETTINGS.get("api_key", "")
  29. # If an API key is provided
  30. if self.api_key:
  31. # If the provided API key matches the API key in the SETTINGS
  32. if self.api_key == SETTINGS.get("api_key"):
  33. # Log that the user is already logged in
  34. if verbose:
  35. LOGGER.info(f"{PREFIX}Authenticated ✅")
  36. return
  37. else:
  38. # Attempt to authenticate with the provided API key
  39. success = self.authenticate()
  40. # If the API key is not provided and the environment is a Google Colab notebook
  41. elif IS_COLAB:
  42. # Attempt to authenticate using browser cookies
  43. success = self.auth_with_cookies()
  44. else:
  45. # Request an API key
  46. success = self.request_api_key()
  47. # Update SETTINGS with the new API key after successful authentication
  48. if success:
  49. SETTINGS.update({"api_key": self.api_key})
  50. # Log that the new login was successful
  51. if verbose:
  52. LOGGER.info(f"{PREFIX}New authentication successful ✅")
  53. elif verbose:
  54. LOGGER.info(f"{PREFIX}Get API key from {API_KEY_URL} and then run 'yolo hub login API_KEY'")
  55. def request_api_key(self, max_attempts=3):
  56. """
  57. Prompt the user to input their API key.
  58. Returns the model ID.
  59. """
  60. import getpass
  61. for attempts in range(max_attempts):
  62. LOGGER.info(f"{PREFIX}Login. Attempt {attempts + 1} of {max_attempts}")
  63. input_key = getpass.getpass(f"Enter API key from {API_KEY_URL} ")
  64. self.api_key = input_key.split("_")[0] # remove model id if present
  65. if self.authenticate():
  66. return True
  67. raise ConnectionError(emojis(f"{PREFIX}Failed to authenticate ❌"))
  68. def authenticate(self) -> bool:
  69. """
  70. Attempt to authenticate with the server using either id_token or API key.
  71. Returns:
  72. (bool): True if authentication is successful, False otherwise.
  73. """
  74. try:
  75. if header := self.get_auth_header():
  76. r = requests.post(f"{HUB_API_ROOT}/v1/auth", headers=header)
  77. if not r.json().get("success", False):
  78. raise ConnectionError("Unable to authenticate.")
  79. return True
  80. raise ConnectionError("User has not authenticated locally.")
  81. except ConnectionError:
  82. self.id_token = self.api_key = False # reset invalid
  83. LOGGER.warning(f"{PREFIX}Invalid API key ⚠️")
  84. return False
  85. def auth_with_cookies(self) -> bool:
  86. """
  87. Attempt to fetch authentication via cookies and set id_token. User must be logged in to HUB and running in a
  88. supported browser.
  89. Returns:
  90. (bool): True if authentication is successful, False otherwise.
  91. """
  92. if not IS_COLAB:
  93. return False # Currently only works with Colab
  94. try:
  95. authn = request_with_credentials(f"{HUB_API_ROOT}/v1/auth/auto")
  96. if authn.get("success", False):
  97. self.id_token = authn.get("data", {}).get("idToken", None)
  98. self.authenticate()
  99. return True
  100. raise ConnectionError("Unable to fetch browser authentication details.")
  101. except ConnectionError:
  102. self.id_token = False # reset invalid
  103. return False
  104. def get_auth_header(self):
  105. """
  106. Get the authentication header for making API requests.
  107. Returns:
  108. (dict): The authentication header if id_token or API key is set, None otherwise.
  109. """
  110. if self.id_token:
  111. return {"authorization": f"Bearer {self.id_token}"}
  112. elif self.api_key:
  113. return {"x-api-key": self.api_key}
  114. # else returns None