2022-07-21 12:40:13 +00:00
|
|
|
import functools
|
|
|
|
from json import dumps
|
|
|
|
|
2022-07-21 12:40:11 +00:00
|
|
|
from klein import Klein
|
2022-07-21 12:40:13 +00:00
|
|
|
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
|
2022-07-21 12:40:11 +00:00
|
|
|
|
|
|
|
|
|
|
|
class API(object):
|
|
|
|
"""
|
|
|
|
Our API webapp.
|
|
|
|
"""
|
|
|
|
|
|
|
|
app = Klein()
|
2022-07-21 12:40:13 +00:00
|
|
|
|
|
|
|
@app.route("/test/", methods=["GET"])
|
|
|
|
@login_required
|
2022-07-21 12:40:11 +00:00
|
|
|
def hello(self, request):
|
|
|
|
return "Hello"
|
2022-07-21 12:40:13 +00:00
|
|
|
|
|
|
|
@app.route("/who/<query>/", 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/<query>/", 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/<query>/", 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()})
|