crafty-4/app/classes/web/api_handler.py

59 lines
1.8 KiB
Python
Raw Normal View History

2020-09-06 12:13:42 +08:00
import os
import secrets
import threading
import tornado.web
import tornado.escape
import logging
from app.classes.shared.models import Users
2020-09-06 12:58:17 +08:00
from app.classes.minecraft.stats import stats
2020-09-06 12:13:42 +08:00
log = logging.getLogger(__name__)
class BaseHandler(tornado.web.RequestHandler):
def return_response(self, data: dict):
# Define a standardized response
self.write(data)
def access_denied(self, user):
log.info("User %s was denied access to API route", user)
self.set_status(403)
self.finish(self.return_response(403, {'error':'ACCESS_DENIED', 'info':'You were denied access to the requested resource'}))
2020-09-06 12:58:17 +08:00
def authenticate_user(self):
2020-09-06 12:13:42 +08:00
try:
log.debug("Searching for specified token")
2020-09-06 12:58:17 +08:00
user_data = Users.get(api_token=self.get_argument('token'))
2020-09-06 12:13:42 +08:00
log.debug("Checking results")
if user_data:
2020-09-06 12:58:17 +08:00
# Login successful! Check perms
2020-09-06 12:13:42 +08:00
log.info("User {} has authenticated to API".format(user_data.username))
2020-09-06 12:58:17 +08:00
# TODO: Role check
2020-09-06 12:13:42 +08:00
else:
logging.debug("Auth unsuccessful")
2020-09-06 12:58:17 +08:00
return self.access_denied("unknown")
2020-09-06 12:13:42 +08:00
except:
log.warning("Traceback occurred when authenticating user to API. Most likely wrong token")
2020-09-06 12:58:17 +08:00
return self.access_denied("unknown")
2020-09-06 12:13:42 +08:00
pass
2020-09-06 12:58:17 +08:00
class ServersStats(BaseHandler):
def get(self):
"""Get details about all servers"""
self.authenticate_user()
# Get server stats
self.finish(self.write({"servers": stats.get_servers_stats()}))
class NodeStats(BaseHandler):
def get(self):
"""Get stats for particular node"""
self.authenticate_user()
# Get node stats
node_stats = stats.get_node_stats()
node_stats.pop("servers")
self.finish(self.write(node_stats))