From 071d6f45797891552bfa46fcba86aba5e032b250 Mon Sep 17 00:00:00 2001 From: Mark Veidemanis Date: Thu, 21 Jul 2022 13:40:13 +0100 Subject: [PATCH] Implement API --- api/views.py | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/api/views.py b/api/views.py index af68c64..317a0d5 100644 --- a/api/views.py +++ b/api/views.py @@ -1,4 +1,34 @@ +import functools +from json import dumps + from klein import Klein +from twisted.web.server import Request + +import main +from modules import userinfo + + +def login_required(func): + @functools.wraps(func) + def wrapper(self, *args, **kwargs): + if isinstance(args[0], Request): + request = args[0] + apikey = request.getHeader("ApiKey") + token = request.getHeader("Token") + if not apikey: + return "No API key provided" + if not token: + return "No token provided" + if apikey not in main.tokens: + return "No such API key" + config_token = main.tokens[apikey] + if not token == config_token["hello"]: + return "Invalid token" + counter = config_token["counter"] + request.setHeader("Counter", counter) + return func(self, *args, **kwargs) + + return wrapper class API(object): @@ -7,6 +37,29 @@ class API(object): """ app = Klein() - @app.route("/test", methods=["GET"]) + + @app.route("/test/", methods=["GET"]) + @login_required def hello(self, request): return "Hello" + + @app.route("/who//", methods=["GET"]) + @login_required + def who(self, request, query): + result = userinfo.getWho(query) + # Expand the generator + return dumps({k: [x for x in v] for k, v in result.items()}) + + @app.route("/chans//", methods=["GET"]) + @login_required + def chans(self, request, query): + query = query.split(",") + result = userinfo.getChans(query) + return dumps({k: [x for x in v] for k, v in result.items()}) + + @app.route("/users//", methods=["GET"]) + @login_required + def users(self, request, query): + query = [f"#{x}" for x in query.split(",")] + result = userinfo.getUsers(query) + return dumps({k: [x for x in v] for k, v in result.items()})