auth.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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
  28. import typer
  29. from huggingface_hub.constants import ENDPOINT
  30. from huggingface_hub.hf_api import whoami
  31. from .._login import auth_list, auth_switch, login, logout
  32. from ..utils import get_stored_tokens, get_token, logging
  33. from ._cli_utils import FormatWithAutoOpt, OutputFormatWithAuto, TokenOpt, typer_factory
  34. from ._output import out
  35. logger = logging.get_logger(__name__)
  36. auth_cli = typer_factory(help="Manage authentication (login, logout, etc.).")
  37. @auth_cli.command(
  38. "login",
  39. examples=[
  40. "hf auth login",
  41. "hf auth login --token $HF_TOKEN",
  42. "hf auth login --token $HF_TOKEN --add-to-git-credential",
  43. "hf auth login --force",
  44. ],
  45. )
  46. def auth_login(
  47. token: TokenOpt = None,
  48. add_to_git_credential: Annotated[
  49. bool,
  50. typer.Option(
  51. help="Save to git credential helper. Useful only if you plan to run git commands directly.",
  52. ),
  53. ] = False,
  54. force: Annotated[
  55. bool,
  56. typer.Option(
  57. help="Force re-login even if already logged in.",
  58. ),
  59. ] = False,
  60. ) -> None:
  61. """Login using a token from huggingface.co/settings/tokens."""
  62. login(token=token, add_to_git_credential=add_to_git_credential, skip_if_logged_in=not force)
  63. @auth_cli.command(
  64. "logout",
  65. examples=["hf auth logout", "hf auth logout --token-name my-token"],
  66. )
  67. def auth_logout(
  68. token_name: Annotated[
  69. str | None,
  70. typer.Option(help="Name of token to logout"),
  71. ] = None,
  72. ) -> None:
  73. """Logout from a specific token."""
  74. logout(token_name=token_name)
  75. def _select_token_name() -> str | None:
  76. token_names = list(get_stored_tokens().keys())
  77. if not token_names:
  78. logger.error("No stored tokens found. Please login first.")
  79. return None
  80. print("Available stored tokens:")
  81. for i, token_name in enumerate(token_names, 1):
  82. print(f"{i}. {token_name}")
  83. while True:
  84. try:
  85. choice = input("Enter the number of the token to switch to (or 'q' to quit): ")
  86. if choice.lower() == "q":
  87. return None
  88. index = int(choice) - 1
  89. if 0 <= index < len(token_names):
  90. return token_names[index]
  91. else:
  92. print("Invalid selection. Please try again.")
  93. except ValueError:
  94. print("Invalid input. Please enter a number or 'q' to quit.")
  95. @auth_cli.command(
  96. "switch",
  97. examples=["hf auth switch", "hf auth switch --token-name my-token"],
  98. )
  99. def auth_switch_cmd(
  100. token_name: Annotated[
  101. str | None,
  102. typer.Option(
  103. help="Name of the token to switch to",
  104. ),
  105. ] = None,
  106. add_to_git_credential: Annotated[
  107. bool,
  108. typer.Option(
  109. help="Save to git credential helper. Useful only if you plan to run git commands directly.",
  110. ),
  111. ] = False,
  112. ) -> None:
  113. """Switch between access tokens."""
  114. if token_name is None:
  115. token_name = _select_token_name()
  116. if token_name is None:
  117. print("No token name provided. Aborting.")
  118. raise typer.Exit()
  119. auth_switch(token_name, add_to_git_credential=add_to_git_credential)
  120. @auth_cli.command("list | ls", examples=["hf auth list"])
  121. def auth_list_cmd() -> None:
  122. """List all stored access tokens."""
  123. auth_list()
  124. @auth_cli.command("token", examples=["hf auth token", "hf auth token | xargs curl -H 'Authorization: Bearer {}'"])
  125. def auth_token() -> None:
  126. """Print the current access token to stdout."""
  127. token = get_token()
  128. if token is None:
  129. out.error("Not logged in. Run `hf auth login` first.")
  130. raise typer.Exit(code=1)
  131. print(token)
  132. out.hint("Run `hf auth whoami` to see which account this token belongs to.")
  133. @auth_cli.command("whoami", examples=["hf auth whoami", "hf auth whoami --format json"])
  134. def auth_whoami(
  135. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  136. ) -> None:
  137. """Find out which huggingface.co account you are logged in as."""
  138. token = get_token()
  139. if token is None:
  140. out.error("Not logged in")
  141. raise typer.Exit(code=1)
  142. info = whoami(token)
  143. orgs = ",".join(org["name"] for org in info["orgs"]) or None
  144. endpoint = ENDPOINT if ENDPOINT != "https://huggingface.co" else None
  145. out.result("Logged in", user=info["name"], orgs=orgs, endpoint=endpoint)