|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""``auth`` sub-command group — API key management.""" |
| 3 | +import os |
| 4 | +from http import HTTPStatus |
| 5 | + |
| 6 | +import typer |
| 7 | + |
| 8 | +import dashscope |
| 9 | +from dashscope.cli.common import console, err_console |
| 10 | +from dashscope.common.api_key import get_default_api_key, save_api_key |
| 11 | +from dashscope.common.constants import DEFAULT_DASHSCOPE_API_KEY_FILE_PATH |
| 12 | +from dashscope.common.error import AuthenticationError |
| 13 | + |
| 14 | +app = typer.Typer( |
| 15 | + name="auth", |
| 16 | + help="API key management commands.", |
| 17 | + add_completion=False, |
| 18 | + invoke_without_command=True, |
| 19 | +) |
| 20 | + |
| 21 | + |
| 22 | +@app.callback() |
| 23 | +def callback(ctx: typer.Context): |
| 24 | + """Show help if no subcommand is provided.""" |
| 25 | + if ctx.invoked_subcommand is None: |
| 26 | + typer.echo(ctx.get_help()) |
| 27 | + |
| 28 | + |
| 29 | +@app.command("whoami") |
| 30 | +def whoami(): |
| 31 | + """Verify the current API key and display its source. |
| 32 | +
|
| 33 | + Exit codes: |
| 34 | + 0 key is present and accepted by the API |
| 35 | + 1 no key configured |
| 36 | + 2 key is configured but rejected by the API |
| 37 | + """ |
| 38 | + try: |
| 39 | + key = get_default_api_key() |
| 40 | + except AuthenticationError as exc: |
| 41 | + err_console.print("[red]Error:[/red] No API key configured.") |
| 42 | + err_console.print( |
| 43 | + "Run [bold]dashscope auth login[/bold] or set " |
| 44 | + "DASHSCOPE_API_KEY to configure one.", |
| 45 | + ) |
| 46 | + raise typer.Exit(1) from exc |
| 47 | + |
| 48 | + # Determine where the key came from |
| 49 | + if dashscope.api_key: |
| 50 | + source = "environment / --api-key flag" |
| 51 | + elif dashscope.api_key_file_path: |
| 52 | + source = f"file ({dashscope.api_key_file_path})" |
| 53 | + elif os.path.exists(DEFAULT_DASHSCOPE_API_KEY_FILE_PATH): |
| 54 | + source = f"file ({DEFAULT_DASHSCOPE_API_KEY_FILE_PATH})" |
| 55 | + else: |
| 56 | + source = "unknown" |
| 57 | + |
| 58 | + # Validate the key against the API with a lightweight call |
| 59 | + try: |
| 60 | + dashscope.api_key = key |
| 61 | + rsp = dashscope.Models.list(page=1, page_size=1) |
| 62 | + except Exception as exc: |
| 63 | + err_console.print(f"[red]Error:[/red] API call failed: {exc}") |
| 64 | + raise typer.Exit(2) |
| 65 | + |
| 66 | + if rsp.status_code == HTTPStatus.OK: |
| 67 | + masked = key[:6] + "..." + key[-4:] if len(key) > 10 else "***" |
| 68 | + info = f"key={masked} source={source}" |
| 69 | + console.print(f"[green]Authenticated[/green] {info}") |
| 70 | + raise typer.Exit(0) |
| 71 | + if rsp.status_code in (401, 403): |
| 72 | + err_console.print( |
| 73 | + f"[red]Invalid API key[/red] source={source}\n" |
| 74 | + f"code={rsp.code} message={rsp.message}", |
| 75 | + ) |
| 76 | + raise typer.Exit(2) |
| 77 | + err_console.print( |
| 78 | + f"[red]Unexpected response[/red] status={rsp.status_code} " |
| 79 | + f"message={rsp.message}", |
| 80 | + ) |
| 81 | + raise typer.Exit(2) |
| 82 | + |
| 83 | + |
| 84 | +@app.command("login") |
| 85 | +def login( |
| 86 | + key: str = typer.Option( |
| 87 | + None, |
| 88 | + "--key", |
| 89 | + "-k", |
| 90 | + help="API key to save. Prompted interactively if omitted.", |
| 91 | + ), |
| 92 | +): |
| 93 | + """Save an API key to ~/.dashscope/api_key.""" |
| 94 | + if not key: |
| 95 | + key = typer.prompt("Enter your DashScope API key", hide_input=True) |
| 96 | + |
| 97 | + key = key.strip() |
| 98 | + if not key: |
| 99 | + err_console.print("[red]Error:[/red] API key cannot be empty.") |
| 100 | + raise typer.Exit(1) |
| 101 | + |
| 102 | + save_api_key(key) |
| 103 | + key_path = DEFAULT_DASHSCOPE_API_KEY_FILE_PATH |
| 104 | + console.print(f"[green]Saved[/green] API key to {key_path}") |
| 105 | + |
| 106 | + |
| 107 | +@app.command("logout") |
| 108 | +def logout(): |
| 109 | + """Remove the saved API key from ~/.dashscope/api_key.""" |
| 110 | + path = DEFAULT_DASHSCOPE_API_KEY_FILE_PATH |
| 111 | + if not os.path.exists(path): |
| 112 | + console.print("No saved API key found — nothing to remove.") |
| 113 | + return |
| 114 | + |
| 115 | + os.remove(path) |
| 116 | + console.print(f"[green]Removed[/green] API key file {path}") |
0 commit comments