Resolves CRAFTY-CONTROLLER-T-81 - error when creating new user

Also cleans up the panel and server code to handle other states better
This commit is contained in:
computergeek125 2021-04-03 12:36:01 -05:00
parent 680cb1885e
commit bd6eed118a
6 changed files with 101 additions and 111 deletions

View File

@ -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,

View File

@ -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

View File

@ -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())

View File

@ -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')

View File

@ -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)

View File

@ -40,11 +40,11 @@
<div class="card-body pt-0">
<ul class="nav nav-tabs col-md-12 tab-simple-styled " role="tablist">
<li class="nav-item">
<a class="nav-link active" href="/panel/edit_user?id={{ data['user']['username'] }}&subpage=config" role="tab" aria-selected="true">
<a class="nav-link active" href="/panel/edit_user?id={{ data['user']['user_id'] }}&subpage=config" role="tab" aria-selected="true">
<i class="fas fa-cogs"></i>Config</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/panel/edit_user?id={{ data['user']['username'] }}&subpage=other" role="tab" aria-selected="false">
<a class="nav-link" href="/panel/edit_user?id={{ data['user']['user_id'] }}&subpage=other" role="tab" aria-selected="false">
<i class="fas fa-folder-tree"></i>Other</a>
</li>
</ul>
@ -120,10 +120,10 @@
<tr>
<td>{{ server['server_name'] }}</td>
<td>
{% if server['server_id'] in data['user']['servers'] %}
<input type="checkbox" class="form-check-input" id="server_{{ server['server_id'] }}_access" name="server_{{ server['server_id'] }}_access" checked="" value="1">
{% if server['server_id'] in data['servers'] %}
<input type="checkbox" class="form-check-input" id="server_{{ server['server_id'] }}_access" name="server_{{ server['server_id'] }}_access" checked="" disabled>
{% else %}
<input type="checkbox" class="form-check-input" id="server_{{ server['server_id'] }}_access" name="server_{{ server['server_id'] }}_access" value="1">
<input type="checkbox" class="form-check-input" id="server_{{ server['server_id'] }}_access" name="server_{{ server['server_id'] }}_access" disabled>
{% end %}
</td>
</tr>