auth.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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 typing import Annotated, Optional
  28. import typer
  29. from huggingface_hub.constants import ENDPOINT
  30. from huggingface_hub.errors import HfHubHTTPError
  31. from huggingface_hub.hf_api import whoami
  32. from .._login import auth_list, auth_switch, login, logout
  33. from ..utils import ANSI, get_stored_tokens, get_token, logging
  34. from ._cli_utils import TokenOpt, typer_factory
  35. logger = logging.get_logger(__name__)
  36. auth_cli = typer_factory(help="Manage authentication (login, logout, etc.).")
  37. @auth_cli.command("login", help="Login using a token from huggingface.co/settings/tokens")
  38. def auth_login(
  39. token: TokenOpt = None,
  40. add_to_git_credential: Annotated[
  41. bool,
  42. typer.Option(
  43. help="Save to git credential helper. Useful only if you plan to run git commands directly.",
  44. ),
  45. ] = False,
  46. ) -> None:
  47. login(token=token, add_to_git_credential=add_to_git_credential)
  48. @auth_cli.command("logout", help="Logout from a specific token")
  49. def auth_logout(
  50. token_name: Annotated[
  51. Optional[str],
  52. typer.Option(
  53. help="Name of token to logout",
  54. ),
  55. ] = None,
  56. ) -> None:
  57. logout(token_name=token_name)
  58. def _select_token_name() -> Optional[str]:
  59. token_names = list(get_stored_tokens().keys())
  60. if not token_names:
  61. logger.error("No stored tokens found. Please login first.")
  62. return None
  63. print("Available stored tokens:")
  64. for i, token_name in enumerate(token_names, 1):
  65. print(f"{i}. {token_name}")
  66. while True:
  67. try:
  68. choice = input("Enter the number of the token to switch to (or 'q' to quit): ")
  69. if choice.lower() == "q":
  70. return None
  71. index = int(choice) - 1
  72. if 0 <= index < len(token_names):
  73. return token_names[index]
  74. else:
  75. print("Invalid selection. Please try again.")
  76. except ValueError:
  77. print("Invalid input. Please enter a number or 'q' to quit.")
  78. @auth_cli.command("switch", help="Switch between access tokens")
  79. def auth_switch_cmd(
  80. token_name: Annotated[
  81. Optional[str],
  82. typer.Option(
  83. help="Name of the token to switch to",
  84. ),
  85. ] = None,
  86. add_to_git_credential: Annotated[
  87. bool,
  88. typer.Option(
  89. help="Save to git credential helper. Useful only if you plan to run git commands directly.",
  90. ),
  91. ] = False,
  92. ) -> None:
  93. if token_name is None:
  94. token_name = _select_token_name()
  95. if token_name is None:
  96. print("No token name provided. Aborting.")
  97. raise typer.Exit()
  98. auth_switch(token_name, add_to_git_credential=add_to_git_credential)
  99. @auth_cli.command("list", help="List all stored access tokens")
  100. def auth_list_cmd() -> None:
  101. auth_list()
  102. @auth_cli.command("whoami", help="Find out which huggingface.co account you are logged in as.")
  103. def auth_whoami() -> None:
  104. token = get_token()
  105. if token is None:
  106. print("Not logged in")
  107. raise typer.Exit()
  108. try:
  109. info = whoami(token)
  110. print(ANSI.bold("user: "), info["name"])
  111. orgs = [org["name"] for org in info["orgs"]]
  112. if orgs:
  113. print(ANSI.bold("orgs: "), ",".join(orgs))
  114. if ENDPOINT != "https://huggingface.co":
  115. print(f"Authenticated through private endpoint: {ENDPOINT}")
  116. except HfHubHTTPError as e:
  117. print(e)
  118. print(ANSI.red(e.response.text))
  119. raise typer.Exit(code=1)