|
"""CLI Key command and sub-commands.""" |
|
|
|
import os |
|
from typing import Annotated |
|
|
|
import requests |
|
import typer |
|
|
|
BACKEND_API_URL = os.getenv( |
|
"BACKEND_API_URL", "https://dev-webapi-service-560808695349.europe-west4.run.app" |
|
) |
|
|
|
app = typer.Typer(help="Handle API key.") |
|
api_key_argument = typer.Argument(help="API Key") |
|
|
|
|
|
@app.command(name="generate") |
|
def generate( |
|
user_id: Annotated[str, typer.Argument(help="User email.")], |
|
master_key: Annotated[str, typer.Argument(help="API Master Key.")], |
|
): |
|
""" |
|
Retrieves an API key for the specified user from a specified API endpoint. |
|
|
|
Args: |
|
user_id: The ID of the user. |
|
master_key: API Master Key. |
|
""" |
|
|
|
url = f"{BACKEND_API_URL}/key" |
|
|
|
headers = {"x-api-master-key": f"{master_key}"} |
|
|
|
data = {"userId": user_id} |
|
|
|
try: |
|
response = requests.post(url, json=data, headers=headers) |
|
response.raise_for_status() |
|
|
|
api_key = response.text |
|
|
|
if api_key: |
|
typer.echo(f"API Key for user [{user_id}] : {api_key}") |
|
else: |
|
typer.echo(f"Unable to generate an API Key for user {user_id}") |
|
|
|
except requests.exceptions.RequestException as e: |
|
typer.echo(f"Error: {e}") |
|
|
|
|
|
@app.command(name="owner") |
|
def owner( |
|
api_key: Annotated[str, api_key_argument], |
|
): |
|
""" |
|
Get the API key owner. |
|
|
|
Args: |
|
api_key: The API Key. |
|
""" |
|
|
|
url = f"{BACKEND_API_URL}/key/owner" |
|
|
|
headers = {"x-api-key": f"{api_key}"} |
|
|
|
try: |
|
response = requests.get(url, headers=headers) |
|
response.raise_for_status() |
|
|
|
data = response.json() |
|
if api_key: |
|
typer.echo(f"API Key owner : {data}") |
|
else: |
|
typer.echo(f"Unable to get owner for {api_key}") |
|
|
|
except requests.exceptions.RequestException as e: |
|
typer.echo(f"Error: {e}") |
|
|
|
|
|
@app.command(name="decode") |
|
def decode( |
|
api_key: Annotated[str, api_key_argument], |
|
): |
|
""" |
|
Decodes an API key. |
|
|
|
Args: |
|
api_key: The API Key. |
|
""" |
|
|
|
url = f"{BACKEND_API_URL}/key/decode" |
|
|
|
headers = {"x-api-key": f"{api_key}"} |
|
|
|
try: |
|
response = requests.get(url, headers=headers) |
|
response.raise_for_status() |
|
|
|
data = response.text |
|
if api_key: |
|
typer.echo(f"API Key decoded : \n{data}") |
|
else: |
|
typer.echo(f"Unable to decode {api_key}") |
|
|
|
except requests.exceptions.RequestException as e: |
|
typer.echo(f"Error: {e}") |
|
|
|
|
|
if __name__ == "__main__": |
|
app() |
|
|