auth.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. # Copyright 2020 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Contains commands to authenticate to the Hugging Face Hub and interact with your repositories.
  15. Usage:
  16. # login and save token locally.
  17. hf auth login --token=hf_*** --add-to-git-credential
  18. # switch between tokens
  19. hf auth switch
  20. # list all tokens
  21. hf auth list
  22. # logout from all tokens
  23. hf auth logout
  24. # check which account you are logged in as
  25. hf auth whoami
  26. """
  27. from argparse import _SubParsersAction
  28. from typing import List, Optional
  29. from requests.exceptions import HTTPError
  30. from huggingface_hub.commands import BaseHuggingfaceCLICommand
  31. from huggingface_hub.constants import ENDPOINT
  32. from huggingface_hub.hf_api import HfApi
  33. from .._login import auth_list, auth_switch, login, logout
  34. from ..utils import get_stored_tokens, get_token, logging
  35. from ._cli_utils import ANSI
  36. logger = logging.get_logger(__name__)
  37. try:
  38. from InquirerPy import inquirer
  39. from InquirerPy.base.control import Choice
  40. _inquirer_py_available = True
  41. except ImportError:
  42. _inquirer_py_available = False
  43. class AuthCommands(BaseHuggingfaceCLICommand):
  44. @staticmethod
  45. def register_subcommand(parser: _SubParsersAction):
  46. # Create the main 'auth' command
  47. auth_parser = parser.add_parser("auth", help="Manage authentication (login, logout, etc.).")
  48. auth_subparsers = auth_parser.add_subparsers(help="Authentication subcommands")
  49. # Show help if no subcommand is provided
  50. auth_parser.set_defaults(func=lambda args: auth_parser.print_help())
  51. # Add 'login' as a subcommand of 'auth'
  52. login_parser = auth_subparsers.add_parser(
  53. "login", help="Log in using a token from huggingface.co/settings/tokens"
  54. )
  55. login_parser.add_argument(
  56. "--token",
  57. type=str,
  58. help="Token generated from https://huggingface.co/settings/tokens",
  59. )
  60. login_parser.add_argument(
  61. "--add-to-git-credential",
  62. action="store_true",
  63. help="Optional: Save token to git credential helper.",
  64. )
  65. login_parser.set_defaults(func=lambda args: AuthLogin(args))
  66. # Add 'logout' as a subcommand of 'auth'
  67. logout_parser = auth_subparsers.add_parser("logout", help="Log out")
  68. logout_parser.add_argument(
  69. "--token-name",
  70. type=str,
  71. help="Optional: Name of the access token to log out from.",
  72. )
  73. logout_parser.set_defaults(func=lambda args: AuthLogout(args))
  74. # Add 'whoami' as a subcommand of 'auth'
  75. whoami_parser = auth_subparsers.add_parser(
  76. "whoami", help="Find out which huggingface.co account you are logged in as."
  77. )
  78. whoami_parser.set_defaults(func=lambda args: AuthWhoami(args))
  79. # Existing subcommands
  80. auth_switch_parser = auth_subparsers.add_parser("switch", help="Switch between access tokens")
  81. auth_switch_parser.add_argument(
  82. "--token-name",
  83. type=str,
  84. help="Optional: Name of the access token to switch to.",
  85. )
  86. auth_switch_parser.add_argument(
  87. "--add-to-git-credential",
  88. action="store_true",
  89. help="Optional: Save token to git credential helper.",
  90. )
  91. auth_switch_parser.set_defaults(func=lambda args: AuthSwitch(args))
  92. auth_list_parser = auth_subparsers.add_parser("list", help="List all stored access tokens")
  93. auth_list_parser.set_defaults(func=lambda args: AuthList(args))
  94. class BaseAuthCommand:
  95. def __init__(self, args):
  96. self.args = args
  97. self._api = HfApi()
  98. class AuthLogin(BaseAuthCommand):
  99. def run(self):
  100. logging.set_verbosity_info()
  101. login(
  102. token=self.args.token,
  103. add_to_git_credential=self.args.add_to_git_credential,
  104. )
  105. class AuthLogout(BaseAuthCommand):
  106. def run(self):
  107. logging.set_verbosity_info()
  108. logout(token_name=self.args.token_name)
  109. class AuthSwitch(BaseAuthCommand):
  110. def run(self):
  111. logging.set_verbosity_info()
  112. token_name = self.args.token_name
  113. if token_name is None:
  114. token_name = self._select_token_name()
  115. if token_name is None:
  116. print("No token name provided. Aborting.")
  117. exit()
  118. auth_switch(token_name, add_to_git_credential=self.args.add_to_git_credential)
  119. def _select_token_name(self) -> Optional[str]:
  120. token_names = list(get_stored_tokens().keys())
  121. if not token_names:
  122. logger.error("No stored tokens found. Please login first.")
  123. return None
  124. if _inquirer_py_available:
  125. return self._select_token_name_tui(token_names)
  126. # if inquirer is not available, use a simpler terminal UI
  127. print("Available stored tokens:")
  128. for i, token_name in enumerate(token_names, 1):
  129. print(f"{i}. {token_name}")
  130. while True:
  131. try:
  132. choice = input("Enter the number of the token to switch to (or 'q' to quit): ")
  133. if choice.lower() == "q":
  134. return None
  135. index = int(choice) - 1
  136. if 0 <= index < len(token_names):
  137. return token_names[index]
  138. else:
  139. print("Invalid selection. Please try again.")
  140. except ValueError:
  141. print("Invalid input. Please enter a number or 'q' to quit.")
  142. def _select_token_name_tui(self, token_names: List[str]) -> Optional[str]:
  143. choices = [Choice(token_name, name=token_name) for token_name in token_names]
  144. try:
  145. return inquirer.select(
  146. message="Select a token to switch to:",
  147. choices=choices,
  148. default=None,
  149. ).execute()
  150. except KeyboardInterrupt:
  151. logger.info("Token selection cancelled.")
  152. return None
  153. class AuthList(BaseAuthCommand):
  154. def run(self):
  155. logging.set_verbosity_info()
  156. auth_list()
  157. class AuthWhoami(BaseAuthCommand):
  158. def run(self):
  159. token = get_token()
  160. if token is None:
  161. print("Not logged in")
  162. exit()
  163. try:
  164. info = self._api.whoami(token)
  165. print(ANSI.bold("user: "), info["name"])
  166. orgs = [org["name"] for org in info["orgs"]]
  167. if orgs:
  168. print(ANSI.bold("orgs: "), ",".join(orgs))
  169. if ENDPOINT != "https://huggingface.co":
  170. print(f"Authenticated through private endpoint: {ENDPOINT}")
  171. except HTTPError as e:
  172. print(e)
  173. print(ANSI.red(e.response.text))
  174. exit(1)