From ea3dc64fb9c4c55daf2d1f5ed292c24612d25c0b Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Tue, 27 Feb 2024 21:08:15 -0800 Subject: [PATCH] dclient actor command, closes #26 --- dclient/cli.py | 42 +++++++++++++++++++++++++++++++++++++++++- docs/authentication.md | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 1 deletion(-) diff --git a/dclient/cli.py b/dclient/cli.py index aae4910..a8b3376 100644 --- a/dclient/cli.py +++ b/dclient/cli.py @@ -130,7 +130,12 @@ def query(url_or_alias, sql, token, verbose): ) @click.option("--token", "-t", help="API token") @click.option("--silent", is_flag=True, help="Don't output progress") -@click.option("-v", "--verbose", is_flag=True, help="Verbose output: show HTTP request and response") +@click.option( + "-v", + "--verbose", + is_flag=True, + help="Verbose output: show HTTP request and response", +) def insert( url_or_alias, table, @@ -259,6 +264,41 @@ def insert( ) +@cli.command() +@click.argument("url_or_alias") +@click.option("--token", help="API token") +def actor(url_or_alias, token): + """ + Show the actor represented by an API token + + Example usage: + + \b + dclient actor https://latest.datasette.io/fixtures + """ + aliases_file = get_config_dir() / "aliases.json" + aliases = _load_aliases(aliases_file) + if url_or_alias in aliases: + url = aliases[url_or_alias] + else: + url = url_or_alias + + if not (url.startswith("http://") or url.startswith("https://")): + raise click.ClickException("Invalid URL: " + url) + + if token is None: + token = token_for_url(url, _load_auths(get_config_dir() / "auth.json")) + + url_bits = url.split("/") + url_bits[-1] = "-/actor.json" + actor_url = "/".join(url_bits) + response = httpx.get( + actor_url, headers={"Authorization": "Bearer {}".format(token)}, timeout=40.0 + ) + response.raise_for_status() + click.echo(json.dumps(response.json(), indent=4)) + + @cli.group() def alias(): "Manage aliases for different instances" diff --git a/docs/authentication.md b/docs/authentication.md index e360fa0..4e5f22f 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -28,7 +28,21 @@ To delete the token for a specific URL, run `auth remove`: ```bash dclient auth remove https://latest.datasette.io/ ``` +## Testing a token +The `dclient actor` command can be used to test a token, retrieving the actor that the token represents. +```bash +dclient actor https://latest.datasette.io/content +``` +The output looks like this: +```json +{ + "actor": { + "id": "root", + "token": "dstok" + } +} +``` ## dclient auth --help + +## dclient actor --help + + +``` +Usage: dclient actor [OPTIONS] URL_OR_ALIAS + + Show the actor represented by an API token + + Example usage: + + dclient actor https://latest.datasette.io/fixtures + +Options: + --token TEXT API token + --help Show this message and exit. + +``` + \ No newline at end of file