From ca79af5e38653967267a863b2428e32c87828e7e Mon Sep 17 00:00:00 2001 From: jedi Date: Thu, 15 Jun 2023 21:45:27 +0200 Subject: [PATCH] add skeleton for cli-client --- cli-client/toolshed-client.py | 83 +++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100755 cli-client/toolshed-client.py diff --git a/cli-client/toolshed-client.py b/cli-client/toolshed-client.py new file mode 100755 index 0000000..2c5d434 --- /dev/null +++ b/cli-client/toolshed-client.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +import argparse +import os +import requests +from nacl.signing import SigningKey +from json import dumps + + +class ToolshedApi: + user = None + host = None + signing_key = None + + def __init__(self, user, host, key): + if host is None: + raise ValueError("TOOLSHED_HOST environment variable not set") + + if user is None: + raise ValueError("TOOLSHED_USER environment variable not set") + + if key is None: + raise ValueError("TOOLSHED_KEY environment variable not set") + + if len(key) != 64: + raise ValueError("TOOLSHED_KEY must be 64 hex characters") + + signing_key = SigningKey(bytes.fromhex(key)) + + self.user = user + self.host = host + self.signing_key = signing_key + + def get(self, target): + url = "http://" + self.host + target + signed = self.signing_key.sign(url.encode('utf-8')) + signature = signed.signature.hex() + response = requests.get(url, headers={"Authorization": "Signature " + self.user + ":" + signature}) + return response.json() + + def post(self, target, data): + url = "http://" + self.host + target + json = dumps(data) + signed = self.signing_key.sign(url.encode('utf-8') + json.encode('utf-8')) + signature = signed.signature.hex() + response = requests.post(url, headers={"Authorization": "Signature " + self.user + ":" + signature}, json=data) + return response.json() + + +def main(): + host = os.environ.get('TOOLSHED_HOST') + user = os.environ.get('TOOLSHED_USER') + key = os.environ.get('TOOLSHED_KEY') + + parser = argparse.ArgumentParser(description='Toolshed API client') + parser.add_argument('--host', help='Toolshed host') + parser.add_argument('--user', help='Toolshed user') + parser.add_argument('--key', help='Toolshed key') + parser.add_argument('cmd', help='Command') + args = parser.parse_args() + + if args.host is not None: + host = args.host + + if args.user is not None: + user = args.user + + if args.key is not None: + key = args.key + + api = ToolshedApi(user, host, key) + + if args.cmd == 'getinventory': + inv = api.get("/api/inventory_items/") + print(inv) + elif args.cmd == 'additem': + inv = api.post("/api/inventory_items/", {"name": "test"}) + print(inv) + else: + print("Unknown command: " + args.cmd) + + +if __name__ == '__main__': + main()