From bd6eed118af4cb20e834198f94e46f2ea9b15998 Mon Sep 17 00:00:00 2001 From: computergeek125 Date: Sat, 3 Apr 2021 12:36:01 -0500 Subject: [PATCH] Resolves CRAFTY-CONTROLLER-T-81 - error when creating new user Also cleans up the panel and server code to handle other states better --- app/classes/shared/models.py | 32 ++--- app/classes/web/panel_handler.py | 127 ++++++++---------- app/classes/web/server_handler.py | 27 ++-- app/classes/web/websocket_handler.py | 11 +- app/classes/web/websocket_helper.py | 5 +- .../templates/panel/panel_edit_user.html | 10 +- 6 files changed, 101 insertions(+), 111 deletions(-) diff --git a/app/classes/shared/models.py b/app/classes/shared/models.py index 4cdfece8..a072b6a4 100644 --- a/app/classes/shared/models.py +++ b/app/classes/shared/models.py @@ -402,7 +402,7 @@ class db_shortcuts: for s in authorizedServers: latest = Server_Stats.select().where(Server_Stats.server_id == s.get('server_id')).order_by(Server_Stats.created.desc()).limit(1) - server_data.append({'server_data': s, "stats": db_helper.return_rows(latest)}) + server_data.append({'server_data': s, "stats": db_helper.return_rows(latest)[0]}) return server_data @staticmethod @@ -512,10 +512,10 @@ class db_shortcuts: # servers.add(s.server_id.server_id) user['roles'] = roles #user['servers'] = servers - logger.debug("user: ({}) {}".format(user_id, user)) + #logger.debug("user: ({}) {}".format(user_id, user)) return user else: - logger.debug("user: ({}) {}".format(user_id, {})) + #logger.debug("user: ({}) {}".format(user_id, {})) return {} @staticmethod @@ -532,9 +532,9 @@ class db_shortcuts: elif key == "roles": added_roles = user_data['roles'].difference(base_data['roles']) removed_roles = base_data['roles'].difference(user_data['roles']) - elif key == "servers": - added_servers = user_data['servers'].difference(base_data['servers']) - removed_servers = base_data['servers'].difference(user_data['servers']) + #elif key == "servers": + # added_servers = user_data['servers'].difference(base_data['servers']) + # removed_servers = base_data['servers'].difference(user_data['servers']) elif key == "regen_api": if user_data['regen_api']: up_data['api_token'] = db_shortcuts.new_api_token() @@ -581,9 +581,10 @@ class db_shortcuts: @staticmethod def remove_user(user_id): - User_Servers.delete().where(User_Servers.user_id == user_id).execute() - user = Users.get(Users.user_id == user_id) - return user.delete_instance() + with database.atomic(): + User_Roles.delete().where(User_Servers.user_id == user_id).execute() + user = Users.get(Users.user_id == user_id) + return user.delete_instance() @staticmethod def user_id_exists(user_id): @@ -609,10 +610,10 @@ class db_shortcuts: for s in servers_query: servers.add(s.server_id.server_id) role['servers'] = servers - logger.debug("role: ({}) {}".format(role_id, role)) + #logger.debug("role: ({}) {}".format(role_id, role)) return role else: - logger.debug("role: ({}) {}".format(role_id, {})) + #logger.debug("role: ({}) {}".format(role_id, {})) return {} @staticmethod @@ -704,17 +705,16 @@ class db_shortcuts: Commands.executed: True }).where(Commands.command_id == command_id).execute() - @staticmethod - def add_to_audit_log(user_id, log_msg, server_id=None, source_ip=None): + def add_to_audit_log(self, user_id, log_msg, server_id=None, source_ip=None): logger.debug("Adding to audit log User:{} - Message: {} ".format(user_id, log_msg)) - user_data = Users.get_by_id(user_id) + user_data = self.get_user(user_id) - audit_msg = "{} {}".format(str(user_data.username).capitalize(), log_msg) + audit_msg = "{} {}".format(str(user_data['username']).capitalize(), log_msg) websocket_helper.broadcast('notification', audit_msg) Audit_Log.insert({ - Audit_Log.user_name: user_data.username, + Audit_Log.user_name: user_data['username'], Audit_Log.user_id: user_id, Audit_Log.server_id: server_id, Audit_Log.log_msg: audit_msg, diff --git a/app/classes/web/panel_handler.py b/app/classes/web/panel_handler.py index 0a004fe7..d95da0f4 100644 --- a/app/classes/web/panel_handler.py +++ b/app/classes/web/panel_handler.py @@ -20,7 +20,6 @@ class PanelHandler(BaseHandler): @tornado.web.authenticated def get(self, page): - user_data = json.loads(self.get_secure_cookie("user_data")) error = bleach.clean(self.get_argument('error', "WTF Error!")) template = "panel/denied.html" @@ -28,25 +27,27 @@ class PanelHandler(BaseHandler): now = time.time() formatted_time = str(datetime.datetime.fromtimestamp(now).strftime('%Y-%m-%d %H:%M:%S')) - userId = user_data['user_id'] - user = db_helper.get_user(userId) + exec_user_data = json.loads(self.get_secure_cookie("user_data")) + exec_user_id = exec_user_data['user_id'] + exec_user = db_helper.get_user(exec_user_id) - user_role = [] - if user['superuser'] == 1: + exec_user_role = set() + if exec_user['superuser'] == 1: defined_servers = self.controller.list_defined_servers() - user_role = {"Super User"} + exec_user_role.add("Super User") else: - defined_servers = self.controller.list_authorized_servers(userId) - for r in user['roles']: + defined_servers = self.controller.list_authorized_servers(exec_user_id) + logger.debug(exec_user['roles']) + for r in exec_user['roles']: role = db_helper.get_role(r) - user_role.append(role['role_name']) + exec_user_role.add(role['role_name']) page_data = { # todo: make this actually pull and compare version data 'update_available': False, 'version_data': helper.get_version_string(), - 'user_data': user_data, - 'user_role' : user_role, + 'user_data': exec_user_data, + 'user_role' : exec_user_role, 'server_stats': { 'total': len(defined_servers), 'running': len(self.controller.list_running_servers()), @@ -84,10 +85,18 @@ class PanelHandler(BaseHandler): elif page == "remove_server": server_id = self.get_argument('id', None) + + if not exec_user['superuser']: + self.redirect("/panel/error?error=Unauthorized access: not superuser") + return + elif server_id is None: + self.redirect("/panel/error?error=Invalid Server ID") + return + server_data = self.controller.get_server_data(server_id) server_name = server_data['server_name'] - db_helper.add_to_audit_log(user_data['user_id'], + db_helper.add_to_audit_log(exec_user_data['user_id'], "Deleted server {} named {}".format(server_id, server_name), server_id, self.get_remote_ip()) @@ -97,11 +106,13 @@ class PanelHandler(BaseHandler): return elif page == 'dashboard': - if user['superuser'] == 1: + if exec_user['superuser'] == 1: page_data['servers'] = db_helper.get_all_servers_stats() else: - #page_data['servers'] = db_helper.get_authorized_servers_stats(userId) - page_data['servers'] = db_helper.get_authorized_servers_stats_from_roles(userId) + #page_data['servers'] = db_helper.get_authorized_servers_stats(exec_user_id) + ras = db_helper.get_authorized_servers_stats_from_roles(exec_user_id) + logger.debug("ASFR: {}".format(ras)) + page_data['servers'] = ras for s in page_data['servers']: try: @@ -125,9 +136,9 @@ class PanelHandler(BaseHandler): self.redirect("/panel/error?error=Invalid Server ID") return - if user['superuser'] != 1: - #if not db_helper.server_id_authorized(server_id, userId): - if not db_helper.server_id_authorized_from_roles(int(server_id), userId): + if exec_user['superuser'] != 1: + #if not db_helper.server_id_authorized(server_id, exec_user_id): + if not db_helper.server_id_authorized_from_roles(int(server_id), exec_user_id): self.redirect("/panel/error?error=Invalid Server ID") return False @@ -185,9 +196,9 @@ class PanelHandler(BaseHandler): self.redirect("/panel/error?error=Invalid Server ID") return - if user['superuser'] != 1: - #if not db_helper.server_id_authorized(server_id, userId): - if not db_helper.server_id_authorized_from_roles(int(server_id), userId): + if exec_user['superuser'] != 1: + #if not db_helper.server_id_authorized(server_id, exec_user_id): + if not db_helper.server_id_authorized_from_roles(int(server_id), exec_user_id): self.redirect("/panel/error?error=Invalid Server ID") return False @@ -234,9 +245,9 @@ class PanelHandler(BaseHandler): self.redirect("/panel/error?error=Invalid Server ID") return - if user['superuser'] != 1: - #if not db_helper.server_id_authorized(server_id, userId): - if not db_helper.server_id_authorized_from_roles(int(server_id), userId): + if exec_user['superuser'] != 1: + #if not db_helper.server_id_authorized(server_id, exec_user_id): + if not db_helper.server_id_authorized_from_roles(int(server_id), exec_user_id): self.redirect("/panel/error?error=Invalid Server ID") return False @@ -246,7 +257,6 @@ class PanelHandler(BaseHandler): elif page == 'panel_config': page_data['users'] = db_helper.get_all_users() page_data['roles'] = db_helper.get_all_roles() - exec_user = db_helper.get_user(user_data['user_id']) for user in page_data['users']: if user.user_id != exec_user['user_id']: user.api_token = "********" @@ -265,15 +275,13 @@ class PanelHandler(BaseHandler): page_data['user']['last_ip'] = "N/A" page_data['user']['last_update'] = "N/A" page_data['user']['roles'] = set() - page_data['user']['servers'] = set() - - exec_user = db_helper.get_user(user_data['user_id']) if not exec_user['superuser']: self.redirect("/panel/error?error=Unauthorized access: not superuser") return page_data['roles_all'] = db_helper.get_all_roles() + page_data['servers'] = [] page_data['servers_all'] = self.controller.list_defined_servers() template = "panel/panel_edit_user.html" @@ -281,11 +289,10 @@ class PanelHandler(BaseHandler): page_data['new_user'] = False user_id = self.get_argument('id', None) page_data['user'] = db_helper.get_user(user_id) + page_data['servers'] = db_helper.get_authorized_servers_stats_from_roles(user_id) page_data['roles_all'] = db_helper.get_all_roles() page_data['servers_all'] = self.controller.list_defined_servers() - exec_user = db_helper.get_user(user_data['user_id']) - if not exec_user['superuser']: self.redirect("/panel/error?error=Unauthorized access: not superuser") return @@ -300,9 +307,6 @@ class PanelHandler(BaseHandler): elif page == "remove_user": user_id = bleach.clean(self.get_argument('id', None)) - user_data = json.loads(self.get_secure_cookie("user_data")) - exec_user = db_helper.get_user(user_data['user_id']) - if not exec_user['superuser']: self.redirect("/panel/error?error=Unauthorized access: not superuser") return @@ -336,8 +340,6 @@ class PanelHandler(BaseHandler): page_data['role']['last_update'] = "N/A" page_data['role']['servers'] = set() - exec_user = db_helper.get_user(user_data['user_id']) - if not exec_user['superuser']: self.redirect("/panel/error?error=Unauthorized access: not superuser") return @@ -351,8 +353,6 @@ class PanelHandler(BaseHandler): page_data['role'] = db_helper.get_role(role_id) page_data['servers_all'] = self.controller.list_defined_servers() - exec_user = db_helper.get_user(user_data['user_id']) - if not exec_user['superuser']: self.redirect("/panel/error?error=Unauthorized access: not superuser") return @@ -365,9 +365,6 @@ class PanelHandler(BaseHandler): elif page == "remove_role": role_id = bleach.clean(self.get_argument('id', None)) - user_data = json.loads(self.get_secure_cookie("user_data")) - exec_user = db_helper.get_user(user_data['user_id']) - if not exec_user['superuser']: self.redirect("/panel/error?error=Unauthorized access: not superuser") return @@ -403,6 +400,19 @@ class PanelHandler(BaseHandler): @tornado.web.authenticated def post(self, page): + exec_user_data = json.loads(self.get_secure_cookie("user_data")) + exec_user_id = exec_user_data['user_id'] + exec_user = db_helper.get_user(exec_user_id) + + exec_user_role = set() + if exec_user['superuser'] == 1: + defined_servers = self.controller.list_defined_servers() + exec_user_role.add("Super User") + else: + defined_servers = self.controller.list_authorized_servers(exec_user_id) + for r in exec_user['roles']: + role = db_helper.get_role(r) + exec_user_role.add(role['role_name']) if page == 'server_detail': server_id = self.get_argument('id', None) @@ -420,9 +430,6 @@ class PanelHandler(BaseHandler): logs_delete_after = int(float(self.get_argument('logs_delete_after', '0'))) subpage = self.get_argument('subpage', None) - user_data = json.loads(self.get_secure_cookie("user_data")) - exec_user = db_helper.get_user(user_data['user_id']) - if not exec_user['superuser']: self.redirect("/panel/error?error=Unauthorized access: not superuser") return @@ -452,7 +459,7 @@ class PanelHandler(BaseHandler): self.controller.refresh_server_settings(server_id) - db_helper.add_to_audit_log(user_data['user_id'], + db_helper.add_to_audit_log(exec_user['user_id'], "Edited server {} named {}".format(server_id, server_name), server_id, self.get_remote_ip()) @@ -466,9 +473,6 @@ class PanelHandler(BaseHandler): max_backups = bleach.clean(self.get_argument('max_backups', None)) enabled = int(float(bleach.clean(self.get_argument('auto_enabled'), '0'))) - user_data = json.loads(self.get_secure_cookie("user_data")) - exec_user = db_helper.get_user(user_data['user_id']) - if not exec_user['superuser']: self.redirect("/panel/error?error=Unauthorized access: not superuser") return @@ -487,7 +491,7 @@ class PanelHandler(BaseHandler): }).where(Servers.server_id == server_id).execute() db_helper.set_backup_config(server_id, max_backups=max_backups) - db_helper.add_to_audit_log(user_data['user_id'], + db_helper.add_to_audit_log(exec_user['user_id'], "Edited server {}: updated backups".format(server_id), server_id, self.get_remote_ip()) @@ -502,9 +506,6 @@ class PanelHandler(BaseHandler): enabled = int(float(bleach.clean(self.get_argument('enabled'), '0'))) regen_api = int(float(bleach.clean(self.get_argument('regen_api', '0')))) - user_data = json.loads(self.get_secure_cookie("user_data")) - exec_user = db_helper.get_user(user_data['user_id']) - if not exec_user['superuser']: self.redirect("/panel/error?error=Unauthorized access: not superuser") return @@ -534,28 +535,17 @@ class PanelHandler(BaseHandler): if argument: roles.add(role.role_id) - servers = set() - for server in self.controller.list_defined_servers(): - argument = int(float( - bleach.clean( - self.get_argument('server_{}_access'.format(server['server_id']), '0') - ) - )) - if argument: - servers.add(server['server_id']) - user_data = { "username": username, "password": password0, "enabled": enabled, "regen_api": regen_api, "roles": roles, - "servers": servers } db_helper.update_user(user_id, user_data=user_data) db_helper.add_to_audit_log(exec_user['user_id'], - "Edited user {} (UID:{}) with roles {} and servers {}".format(username, user_id, roles, servers), + "Edited user {} (UID:{}) with roles {}".format(username, user_id, roles), server_id=0, source_ip=self.get_remote_ip()) self.redirect("/panel/panel_config") @@ -567,8 +557,6 @@ class PanelHandler(BaseHandler): password1 = bleach.clean(self.get_argument('password1', None)) enabled = int(float(bleach.clean(self.get_argument('enabled'), '0'))) - user_data = json.loads(self.get_secure_cookie("user_data")) - exec_user = db_helper.get_user(user_data['user_id']) if not exec_user['superuser']: self.redirect("/panel/error?error=Unauthorized access: not superuser") return @@ -606,14 +594,14 @@ class PanelHandler(BaseHandler): servers.add(server['server_id']) user_id = db_helper.add_user(username, password=password0, enabled=enabled) - db_helper.update_user(user_id, {"roles":roles, "servers": servers}) + db_helper.update_user(user_id, {"roles":roles}) db_helper.add_to_audit_log(exec_user['user_id'], "Added user {} (UID:{})".format(username, user_id), server_id=0, source_ip=self.get_remote_ip()) db_helper.add_to_audit_log(exec_user['user_id'], - "Edited user {} (UID:{}) with roles {} and servers {}".format(username, user_id, roles, servers), + "Edited user {} (UID:{}) with roles {}".format(username, user_id, roles), server_id=0, source_ip=self.get_remote_ip()) self.redirect("/panel/panel_config") @@ -622,9 +610,6 @@ class PanelHandler(BaseHandler): role_id = bleach.clean(self.get_argument('id', None)) role_name = bleach.clean(self.get_argument('role_name', None)) - user_data = json.loads(self.get_secure_cookie("user_data")) - exec_user = db_helper.get_user(user_data['user_id']) - if not exec_user['superuser']: self.redirect("/panel/error?error=Unauthorized access: not superuser") return @@ -666,8 +651,6 @@ class PanelHandler(BaseHandler): elif page == "add_role": role_name = bleach.clean(self.get_argument('role_name', None)) - user_data = json.loads(self.get_secure_cookie("user_data")) - exec_user = db_helper.get_user(user_data['user_id']) if not exec_user['superuser']: self.redirect("/panel/error?error=Unauthorized access: not superuser") return diff --git a/app/classes/web/server_handler.py b/app/classes/web/server_handler.py index 641fdfa9..ef151f00 100644 --- a/app/classes/web/server_handler.py +++ b/app/classes/web/server_handler.py @@ -29,18 +29,17 @@ class ServerHandler(BaseHandler): @tornado.web.authenticated def get(self, page): # name = tornado.escape.json_decode(self.current_user) - user_data = json.loads(self.get_secure_cookie("user_data")) - - userId = user_data['user_id'] - user = db_helper.get_user(userId) + exec_user_data = json.loads(self.get_secure_cookie("user_data")) + exec_user_id = exec_user_data['user_id'] + exec_user = db_helper.get_user(exec_user_id) user_role = [] - if user['superuser'] == 1: - defined_servers = controller.list_defined_servers() + if exec_user['superuser'] == 1: + defined_servers = self.controller.list_defined_servers() user_role = "Super User" else: - defined_servers = controller.list_authorized_servers(userId) - for r in user['roles']: + defined_servers = self.controller.list_authorized_servers(exec_user_id) + for r in exec_user['roles']: role = db_helper.get_role(r) user_role.append(role['role_name']) @@ -50,7 +49,7 @@ class ServerHandler(BaseHandler): page_data = { 'version_data': helper.get_version_string(), - 'user_data': user_data, + 'user_data': exec_user_data, 'user_role' : user_role, 'server_stats': { 'total': len(self.controller.list_defined_servers()), @@ -75,12 +74,14 @@ class ServerHandler(BaseHandler): @tornado.web.authenticated def post(self, page): - user_data = json.loads(self.get_secure_cookie("user_data")) + exec_user_data = json.loads(self.get_secure_cookie("user_data")) + exec_user_id = exec_user_data['user_id'] + exec_user = db_helper.get_user(exec_user_id) template = "public/404.html" page_data = { 'version_data': "version_data_here", - 'user_data': user_data, + 'user_data': exec_user_data, 'show_contribute': helper.get_setting("show_contribute_link", True) } @@ -147,7 +148,7 @@ class ServerHandler(BaseHandler): return - db_helper.send_command(user_data['user_id'], server_id, self.get_remote_ip(), command) + db_helper.send_command(exec_user_data['user_id'], server_id, self.get_remote_ip(), command) if page == "step1": @@ -184,7 +185,7 @@ class ServerHandler(BaseHandler): new_server_id = self.controller.create_jar_server(server_parts[0], server_parts[1], server_name, min_mem, max_mem, port) if new_server_id: - db_helper.add_to_audit_log(user_data['user_id'], + db_helper.add_to_audit_log(exec_user_data['user_id'], "created a {} {} server named \"{}\"".format(server_parts[1], str(server_parts[0]).capitalize(), server_name), # Example: Admin created a 1.16.5 Bukkit server named "survival" new_server_id, self.get_remote_ip()) diff --git a/app/classes/web/websocket_handler.py b/app/classes/web/websocket_handler.py index a33707f6..11916b64 100644 --- a/app/classes/web/websocket_handler.py +++ b/app/classes/web/websocket_handler.py @@ -1,10 +1,13 @@ import json +import logging import tornado.websocket from app.classes.shared.console import console from app.classes.shared.models import Users, db_helper from app.classes.web.websocket_helper import websocket_helper +logger = logging.getLogger(__name__) + class SocketHandler(tornado.websocket.WebSocketHandler): @@ -42,17 +45,17 @@ class SocketHandler(tornado.websocket.WebSocketHandler): def handle(self): websocket_helper.addClient(self) - console.debug('Opened WebSocket connection') + logger.debug('Opened WebSocket connection') # websocket_helper.broadcast('notification', 'New client connected') def on_message(self, rawMessage): - console.debug('Got message from WebSocket connection {}'.format(rawMessage)) + logger.debug('Got message from WebSocket connection {}'.format(rawMessage)) message = json.loads(rawMessage) - console.debug('Event Type: {}, Data: {}'.format(message['event'], message['data'])) + logger.debug('Event Type: {}, Data: {}'.format(message['event'], message['data'])) def on_close(self): websocket_helper.removeClient(self) - console.debug('Closed WebSocket connection') + logger.debug('Closed WebSocket connection') # websocket_helper.broadcast('notification', 'Client disconnected') diff --git a/app/classes/web/websocket_helper.py b/app/classes/web/websocket_helper.py index 077ea180..37a85cb4 100644 --- a/app/classes/web/websocket_helper.py +++ b/app/classes/web/websocket_helper.py @@ -1,7 +1,10 @@ import json +import logging from app.classes.shared.console import console +logger = logging.getLogger(__name__) + class WebSocketHelper: clients = set() @@ -17,7 +20,7 @@ class WebSocketHelper: client.write_message(message) def broadcast(self, event_type, data): - console.debug('Sending: ' + str(json.dumps({'event': event_type, 'data': data}))) + logger.debug('Sending: ' + str(json.dumps({'event': event_type, 'data': data}))) for client in self.clients: try: self.send_message(client, event_type, data) diff --git a/app/frontend/templates/panel/panel_edit_user.html b/app/frontend/templates/panel/panel_edit_user.html index a23cbed6..17730ccf 100644 --- a/app/frontend/templates/panel/panel_edit_user.html +++ b/app/frontend/templates/panel/panel_edit_user.html @@ -40,11 +40,11 @@
@@ -120,10 +120,10 @@ {{ server['server_name'] }} - {% if server['server_id'] in data['user']['servers'] %} - + {% if server['server_id'] in data['servers'] %} + {% else %} - + {% end %}