initial changes for zip imports selection

This commit is contained in:
Andrew 2022-01-09 18:04:54 -05:00
parent 3e90210f3b
commit 369ac7ad15
7 changed files with 266 additions and 69 deletions

View File

@ -730,6 +730,14 @@ class Helpers:
output += '</ul>\n'
return output
@staticmethod
def unzipServer(zip_path):
tempDir = tempfile.mkdtemp()
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
#extracts archive to temp directory
zip_ref.extractall(tempDir)
return tempDir
@staticmethod
def in_path(parent_path, child_path):
# Smooth out relative path names, note: if you are concerned about symbolic links, you should use os.path.realpath too

View File

@ -295,64 +295,25 @@ class Controller:
server_id = helper.create_uuid()
new_server_dir = os.path.join(helper.servers_dir, server_id)
backup_path = os.path.join(helper.backup_path, server_id)
zip_path = helper.get_os_understandable_path(zip_path)
tempDir = helper.get_os_understandable_path(zip_path)
if helper.check_file_perms(zip_path):
helper.ensure_dir_exists(new_server_dir)
helper.ensure_dir_exists(backup_path)
tempDir = tempfile.mkdtemp()
has_properties = False
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
#extracts archive to temp directory
zip_ref.extractall(tempDir)
if len(zip_ref.filelist) > 1:
for item in os.listdir(tempDir):
if str(item) == 'server.properties':
has_properties = True
try:
shutil.move(os.path.join(tempDir, item), os.path.join(new_server_dir, item))
except Exception as ex:
logger.error('ERROR IN ZIP IMPORT: {}'.format(ex))
if not has_properties:
logger.info("No server.properties found on zip file import. Creating one with port selection of {}".format(str(port)))
with open(os.path.join(new_server_dir, "server.properties"), "w") as f:
f.write("server-port={}".format(port))
f.close()
zip_ref.close()
else:
#iterates list of files
for i in range(len(zip_ref.filelist)):
#checks if the list of files inside of a dir is greater than 1 or if it's not a directory.
if len(zip_ref.filelist) > 1 or not zip_ref.filelist[i].is_dir():
#sets local variable to be that filename and we break out of the loop since we found our root dir.
test = zip_ref.filelist[i-1].filename
break
path_list = test.split('/')
root_path = path_list[0]
if len(path_list) > 1:
for i in range(len(path_list)-1):
try:
root_path = os.path.join(root_path, path_list[i+1])
except:
root_path = root_path
full_root_path = os.path.join(tempDir, root_path)
for item in os.listdir(full_root_path):
if str(item) == 'server.properties':
has_properties = True
try:
shutil.move(os.path.join(full_root_path, item), os.path.join(new_server_dir, item))
except Exception as ex:
logger.error('ERROR IN ZIP IMPORT: {}'.format(ex))
if not has_properties:
logger.info("No server.properties found on zip file import. Creating one with port selection of {}".format(str(port)))
with open(os.path.join(new_server_dir, "server.properties"), "w") as f:
f.write("server-port={}".format(port))
f.close()
zip_ref.close()
#extracts archive to temp directory
for item in os.listdir(tempDir):
if str(item) == 'server.properties':
has_properties = True
try:
shutil.move(os.path.join(tempDir, item), os.path.join(new_server_dir, item))
except Exception as ex:
logger.error('ERROR IN ZIP IMPORT: {}'.format(ex))
if not has_properties:
logger.info("No server.properties found on zip file import. Creating one with port selection of {}".format(str(port)))
with open(os.path.join(new_server_dir, "server.properties"), "w") as f:
f.write("server-port={}".format(port))
f.close()
else:
return "false"

View File

@ -275,6 +275,14 @@ class AjaxHandler(BaseHandler):
self.controller.rename_backup_dir(server_id, new_server_id, new_server['server_uuid'])
self.controller.remove_server(server_id, True)
self.redirect('/panel/dashboard')
elif page == "unzip_server":
print("in unzip server")
path = self.get_argument('path', None)
logger.info(
"Removing server from panel for server: {}".format(self.controller.servers.get_server_friendly_name(server_id)))
self.controller.remove_server(server_id, False)
return "test"
@tornado.web.authenticated

View File

@ -402,19 +402,22 @@ class PanelHandler(BaseHandler):
page_data['role-servers'] = auth_role_servers
page_data['user-roles'] = user_roles
if exec_user['superuser'] == 1:
super_auth_servers = []
super_auth_servers.append("Access To All Servers")
page_data['users'] = self.controller.users.get_all_users()
page_data['roles'] = self.controller.roles.get_all_roles()
page_data['auth-servers'][exec_user['user_id']] = super_auth_servers
else:
page_data['users'] = self.controller.users.user_query(exec_user['user_id'])
page_data['roles'] = self.controller.users.user_role_query(exec_user['user_id'])
page_data['users'] = self.controller.users.user_query(exec_user['user_id'])
page_data['roles'] = self.controller.users.user_role_query(exec_user['user_id'])
for user in page_data['users']:
if user.user_id != exec_user['user_id']:
user.api_token = "********"
if exec_user['superuser']:
for user in self.controller.users.get_all_users():
if user.superuser == 1:
super_auth_servers = []
super_auth_servers.append("Super User Access To All Servers")
page_data['users'] = self.controller.users.get_all_users()
page_data['roles'] = self.controller.roles.get_all_roles()
page_data['auth-servers'][user.user_id] = super_auth_servers
template = "panel/panel_config.html"
elif page == "add_user":
@ -470,6 +473,12 @@ class PanelHandler(BaseHandler):
page_data['quantity_server'] = self.controller.crafty_perms.list_crafty_permissions_quantity_limits(user_id)
page_data['languages'] = []
page_data['languages'].append(self.controller.users.get_user_lang_by_id(user_id))
#checks if super user. If not we disable the button.
if exec_user['superuser'] and str(exec_user['user_id']) != str(user_id):
page_data['super-disabled'] = ''
else:
page_data['super-disabled'] = 'disabled'
for file in sorted(os.listdir(os.path.join(helper.root_dir, 'app', 'translations'))):
if file.endswith('.json'):
if file != str(page_data['languages'][0] + '.json'):
@ -832,6 +841,18 @@ class PanelHandler(BaseHandler):
enabled = int(float(self.get_argument('enabled', '0')))
regen_api = int(float(self.get_argument('regen_api', '0')))
lang = bleach.clean(self.get_argument('language'), 'en_EN')
if exec_user['superuser']:
#Checks if user is trying to change super user status of self. We don't want that. Automatically make them stay super user since we know they are.
if str(exec_user['user_id']) != str(user_id):
superuser = bleach.clean(self.get_argument('superuser', '0'))
else:
superuser = '1'
else:
superuser = '0'
if superuser == '1':
superuser = True
else:
superuser = False
if Enum_Permissions_Crafty.User_Config not in exec_user_crafty_permissions:
if str(user_id) != str(exec_user_id):
@ -910,6 +931,7 @@ class PanelHandler(BaseHandler):
"regen_api": regen_api,
"roles": roles,
"lang": lang,
"superuser": superuser,
}
user_crafty_data = {
"permissions_mask": permissions_mask,
@ -934,6 +956,14 @@ class PanelHandler(BaseHandler):
email = bleach.clean(self.get_argument('email', "default@example.com"))
enabled = int(float(self.get_argument('enabled', '0'))),
lang = bleach.clean(self.get_argument('lang', 'en_EN'))
if exec_user['superuser']:
superuser = bleach.clean(self.get_argument('superuser', '0'))
else:
superuser = '0'
if superuser == '1':
superuser = True
else:
superuser = False
if Enum_Permissions_Crafty.User_Config not in exec_user_crafty_permissions:
self.redirect("/panel/error?error=Unauthorized access: not a user editor")

View File

@ -187,9 +187,9 @@
<label for="superuser" class="form-check-label ml-4 mb-4">
{% if data['user']['superuser'] %}
<input type="checkbox" class="form-check-input" id="superuser" name="superuser" checked="" value="1" disabled >Super User
<input type="checkbox" onclick="superConfirm()" class="form-check-input" id="superuser" name="superuser" checked="" value="1" {{ data['super-disabled'] }} >Super User
{% else %}
<input type="checkbox" class="form-check-input" id="superuser" name="superuser" value="1" disabled >Super User
<input type="checkbox" onclick="superConfirm()" class="form-check-input" id="superuser" name="superuser" {{ data['super-disabled'] }} value="1" >Super User
{% end %}
</label>
@ -251,6 +251,32 @@
{% block js %}
<script>
function superConfirm() {
if (document.getElementById('superuser').checked){
bootbox.confirm({
title: "{{ translate('panelConfig', 'superConfirmTitle', data['lang']) }}",
message: "{{ translate('panelConfig', 'superConfirm', data['lang']) }}",
buttons: {
cancel: {
label: '<i class="fa fa-times"></i> {{ translate('panelConfig', 'cancel', data['lang']) }}'
},
confirm: {
label: '<i class="fa fa-check"></i> {{ translate('serverBackups', 'confirm', data['lang']) }}'
}
},
callback: function (result) {
if (result == true){
return;
}else{
document.getElementById('superuser').checked = false;
}
}
});
}else{
return
}
}
//used to get cookies from browser - this is part of tornados xsrf protection - it's for extra security
function getCookie(name) {

View File

@ -209,7 +209,7 @@
<br />
<p class="card-description">
<form method="post" class="server-wizard" onSubmit="wait_msg(true)">
<form name="zip" method="post" class="server-wizard" onSubmit="wait_msg(true)">
{% raw xsrf_form_html() %}
<input type="hidden" value="import_zip" name="create_type">
@ -229,6 +229,15 @@
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label for="server">{{ translate('serverWizard', 'zipPath', data['lang']) }} Select Root Dir <small>{{ translate('serverWizard', 'absoluteZipPath', data['lang']) }}</small></label>
<br>
<button class="btn btn-primary mr-2" id="root_files_button" type="button">Click here to select Root Dir</button>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label for="server_jar">{{ translate('serverWizard', 'serverJar', data['lang']) }}</label>
@ -288,9 +297,13 @@
</div>
</div>
</div>
<div class="col-sm-12" style="visibility: hidden;">
<div class="form-group">
<input type="text" class="form-control" id="zip_root_path" name="zip_root_path">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary mr-2">{{ translate('serverWizard', 'importServerButton', data['lang']) }}</button>
<button id="zip_submit" type="submit" title="You must select server root dir first" disabled class="btn btn-primary mr-2">{{ translate('serverWizard', 'importServerButton', data['lang']) }}</button>
<button type="reset" class="btn btn-danger mr-2">{{ translate('serverWizard', 'resetForm', data['lang']) }}</button>
</div>
</div>
@ -300,6 +313,31 @@
</div>
</div>
</div>
<div class="modal fade" id="dir_select" tabindex="-1" role="dialog" aria-labelledby="dir_select" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="tree-ctx-item" data-path="">
<span id="main-tree" class="files-tree-title tree-caret-down root-dir" data-path="">
<i class="far fa-folder"></i>
<i class="far fa-folder-open"></i>
{{ translate('serverFiles', 'files', data['lang']) }}
</span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" onclick="" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<style>
.scroll {
max-height: 12em;
@ -333,6 +371,26 @@
{% end %}
{% block js%}
<script>
document.getElementById("root_files_button").addEventListener("click", function(){
if(document.forms["zip"]["server_path"].value != ""){
path = document.getElementById('server_path')
var token = getCookie("_xsrf")
$.ajax({
type: "POST",
headers: {'X-XSRFToken': token},
url: '/ajax/unzip_server',
data: {
path: path,
server_id: '-1'
},
});
}else{
bootbox.alert("You must input a path before selecting this button");
}
});
</script>
<script>
function dropDown(event) {
@ -366,10 +424,15 @@ function hide(event) {
function wait_msg(importing){
bootbox.alert({
title: importing ? '{% raw translate("serverWizard", "importing", data['lang']) %}' : '{% raw translate("serverWizard", "downloading", data['lang']) %}',
message: '<i class="fas fa-cloud-download"></i> {% raw translate("serverWizard", "bePatient", data['lang']) %}'
message: '<i class="fas fa-cloud-download"></i> {% raw translate("serverWizard", "bePatient", data['lang']) %}',
});
}
function show_file_tree(){
$("#dir_select").modal();
}
function check_sizes(a, b, changed){
max_mem = parseFloat(a.val());
min_mem = parseFloat(b.val());
@ -381,6 +444,104 @@ function hide(event) {
}
}
var fileList = document.getElementById("files");
fileList.addEventListener("change", function (e) {
var list = "";
for (var i = 0; i < this.files.length; i++) {
list += "<li class='col-xs-12 file-list'>" + this.files[i].name + "</li>"
}
document.getElementById("fileList").innerHTML = list;
}, false);
});
}
function getTreeView(event) {
path = '/'
$.ajax({
type: "GET",
url: '/ajax/get_tree?id=1&path='+path,
dataType: 'text',
success: function(data){
console.log("got response:");
console.log(data);
dataArr = data.split('\n');
serverDir = dataArr.shift(); // Remove & return first element (server directory)
text = dataArr.join('\n');
try{
document.getElementById(path).innerHTML += text;
event.target.parentElement.classList.add("clicked");
}catch{
document.getElementById('files-tree').innerHTML = text;
}
document.getElementsByClassName('files-tree-title')[0].setAttribute('data-path', serverDir);
document.getElementsByClassName('files-tree-title')[0].setAttribute('data-name', 'Files');
setTimeout(function () {setTreeViewContext()}, 1000);
},
});
}
function getToggleMain(event) {
path = event.target.parentElement.getAttribute('data-path');
document.getElementById("files-tree").classList.toggle("d-block");
document.getElementById(path+"span").classList.toggle("tree-caret-down");
document.getElementById(path+"span").classList.toggle("tree-caret");
}
function getDirView(event) {
path = event.target.parentElement.getAttribute('data-path');
if (document.getElementById(path).classList.contains('clicked')){
var toggler = document.getElementById(path+"span");
if (toggler.classList.contains('files-tree-title')){
document.getElementById(path+"ul").classList.toggle("d-block");
document.getElementById(path+"span").classList.toggle("tree-caret-down");
}
return;
}else{
$.ajax({
type: "GET",
url: '/ajax/get_dir?id=1&path='+path,
dataType: 'text',
success: function(data){
console.log("got response:");
dataArr = data.split('\n');
serverDir = dataArr.shift(); // Remove & return first element (server directory)
text = dataArr.join('\n');
try{
document.getElementById(path+"span").classList.add('tree-caret-down');
document.getElementById(path).innerHTML += text;
document.getElementById(path).classList.add("clicked");
}catch{
console.log("Bad")
}
setTimeout(function () {setTreeViewContext()}, 1000);
var toggler = document.getElementById(path);
if (toggler.classList.contains('files-tree-title')){
document.getElementById(path+"span").addEventListener("click", function caretListener() {
document.getElementById(path+"ul").classList.toggle("d-block");
document.getElementById(path+"span").classList.toggle("tree-caret-down");
});
}
},
});
}
}
</script>
<script type="text/javascript">
//<![CDATA[

View File

@ -279,7 +279,10 @@
"panelConfig": {
"save": "Save",
"cancel": "Cancel",
"delete": "Delete"
"delete": "Delete",
"superConfirmTitle": "Enable Super User? Are you sure?",
"superConfirm": "Proceed only if you want this user to have access to EVERYTHING (all user accounts, servers, panel configs, etc). They can even remove your super user access."
},
"datatables": {
"i18n": {