diff --git a/IncBackups/IncBackupPath.py b/IncBackups/IncBackupPath.py new file mode 100644 index 000000000..10cc418b1 --- /dev/null +++ b/IncBackups/IncBackupPath.py @@ -0,0 +1,7 @@ +from enum import Enum + + +class IncBackupPath(Enum): + SFTP = "/home/cyberpanel/sftp" + AWS = "/home/cyberpanel/aws" + # WASABI = "/home/cyberpanel/wasabi" diff --git a/IncBackups/IncBackupProvider.py b/IncBackups/IncBackupProvider.py new file mode 100644 index 000000000..9645be3d5 --- /dev/null +++ b/IncBackups/IncBackupProvider.py @@ -0,0 +1,8 @@ +from enum import Enum, auto + + +class IncBackupProvider(Enum): + LOCAL = auto() + SFTP = auto() + AWS = auto() + # WASABI = auto() diff --git a/IncBackups/IncBackupsControl.py b/IncBackups/IncBackupsControl.py index c8e17ef83..c62152edc 100644 --- a/IncBackups/IncBackupsControl.py +++ b/IncBackups/IncBackupsControl.py @@ -83,9 +83,7 @@ class IncJobs(multi.Thread): result = self.getRemoteBackups() activator = 0 - json_data = "[" - checker = 0 - + json_data = [] if result[0].find('unable to open config file') == -1: for items in reversed(result): @@ -98,20 +96,11 @@ class IncJobs(multi.Thread): if activator: entry = items.split(' ') - - dic = {'id': entry[0], - 'date': "%s %s" % (entry[2], entry[3]), - 'host': entry[5], - 'path': entry[-1] - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' + json_data.append({'id': entry[0], + 'date': "%s %s" % (entry[2], entry[3]), + 'host': entry[5], + 'path': entry[-1] + }) final_json = json.dumps({'status': 1, 'error_message': "None", "data": json_data}) return HttpResponse(final_json) diff --git a/IncBackups/static/IncBackups/IncBackups.js b/IncBackups/static/IncBackups/IncBackups.js index 32b01ef70..9031c393d 100644 --- a/IncBackups/static/IncBackups/IncBackups.js +++ b/IncBackups/static/IncBackups/IncBackups.js @@ -101,7 +101,7 @@ app.controller('createIncrementalBackups', function ($scope, $http, $timeout) { function ListInitialDatas(response) { if (response.data.status === 1) { - $scope.records = JSON.parse(response.data.data); + $scope.records = response.data.data; } else { new PNotify({ title: 'Error!', @@ -240,7 +240,7 @@ app.controller('createIncrementalBackups', function ($scope, $http, $timeout) { function ListInitialDatas(response) { $scope.cyberpanelLoading = true; if (response.data.status === 1) { - $scope.jobs = JSON.parse(response.data.data); + $scope.jobs = response.data.data; } else { new PNotify({ title: 'Operation Failed!', @@ -358,7 +358,7 @@ app.controller('incrementalDestinations', function ($scope, $http) { function ListInitialDatas(response) { $scope.cyberpanelLoading = true; if (response.data.status === 1) { - $scope.records = JSON.parse(response.data.data); + $scope.records = response.data.data; } else { new PNotify({ title: 'Operation Failed!', @@ -621,7 +621,7 @@ app.controller('scheduleBackupInc', function ($scope, $http) { if (response.data.status === 1) { new PNotify({ title: 'Success!', - text: 'Destination successfully removed.', + text: 'Operation successful.', type: 'success' }); } else { @@ -668,12 +668,11 @@ app.controller('scheduleBackupInc', function ($scope, $http) { function ListInitialDatas(response) { $scope.cyberpanelLoading = true; if (response.data.status === 1) { - $scope.records = JSON.parse(response.data.data); - var parsed = JSON.parse(response.data.data); - - for (var j = 0; j < parsed.length; j++) { - websitesToBeBackedTemp.push(parsed[j].website); - } + let data = response.data.data; + $scope.records = data; + data.forEach(item => { + websitesToBeBackedTemp.push(item.website) + }) } else { new PNotify({ title: 'Operation Failed!', @@ -766,7 +765,7 @@ app.controller('scheduleBackupInc', function ($scope, $http) { function ListInitialDatas(response) { $scope.cyberpanelLoading = true; if (response.data.status === 1) { - $scope.websites = JSON.parse(response.data.data); + $scope.websites = response.data.data; if(response.data.websiteData === 1){ $scope.websiteData = true; @@ -1074,7 +1073,7 @@ app.controller('restoreRemoteBackupsInc', function ($scope, $http, $timeout) { function ListInitialDatas(response) { $scope.cyberpanelLoading = true; if (response.data.status === 1) { - $scope.records = JSON.parse(response.data.data); + $scope.records = response.data.data; } else { new PNotify({ title: 'Error!', diff --git a/IncBackups/templates/IncBackups/restoreRemoteBackups.html b/IncBackups/templates/IncBackups/restoreRemoteBackups.html index b9e6b9228..7c2b38caa 100755 --- a/IncBackups/templates/IncBackups/restoreRemoteBackups.html +++ b/IncBackups/templates/IncBackups/restoreRemoteBackups.html @@ -55,7 +55,7 @@
- +
diff --git a/IncBackups/urls.py b/IncBackups/urls.py index 2cb3e7928..a8862cf04 100644 --- a/IncBackups/urls.py +++ b/IncBackups/urls.py @@ -2,24 +2,24 @@ from django.conf.urls import url from . import views urlpatterns = [ - url(r'^createBackup$', views.createBackup, name='createBackupInc'), - url(r'^restoreRemoteBackups$', views.restoreRemoteBackups, name='restoreRemoteBackupsInc'), - url(r'^backupDestinations$', views.backupDestinations, name='backupDestinationsInc'), - url(r'^addDestination$', views.addDestination, name='addDestinationInc'), - url(r'^populateCurrentRecords$', views.populateCurrentRecords, name='populateCurrentRecordsInc'), - url(r'^removeDestination$', views.removeDestination, name='removeDestinationInc'), - url(r'^fetchCurrentBackups$', views.fetchCurrentBackups, name='fetchCurrentBackupsInc'), - url(r'^submitBackupCreation$', views.submitBackupCreation, name='submitBackupCreationInc'), - url(r'^getBackupStatus$', views.getBackupStatus, name='getBackupStatusInc'), - url(r'^deleteBackup$', views.deleteBackup, name='deleteBackupInc'), - url(r'^fetchRestorePoints$', views.fetchRestorePoints, name='fetchRestorePointsInc'), - url(r'^restorePoint$', views.restorePoint, name='restorePointInc'), - url(r'^scheduleBackups$', views.scheduleBackups, name='scheduleBackupsInc'), - url(r'^submitBackupSchedule$', views.submitBackupSchedule, name='submitBackupScheduleInc'), - url(r'^scheduleDelete$', views.scheduleDelete, name='scheduleDeleteInc'), - url(r'^getCurrentBackupSchedules$', views.getCurrentBackupSchedules, name='getCurrentBackupSchedulesInc'), - url(r'^fetchSites$', views.fetchSites, name='fetchSites'), - url(r'^saveChanges$', views.saveChanges, name='saveChanges'), - url(r'^removeSite$', views.removeSite, name='removeSite'), - url(r'^addWebsite$', views.addWebsite, name='addWebsite'), + url(r'^createBackup$', views.create_backup, name='createBackupInc'), + url(r'^restoreRemoteBackups$', views.restore_remote_backups, name='restoreRemoteBackupsInc'), + url(r'^backupDestinations$', views.backup_destinations, name='backupDestinationsInc'), + url(r'^addDestination$', views.add_destination, name='addDestinationInc'), + url(r'^populateCurrentRecords$', views.populate_current_records, name='populateCurrentRecordsInc'), + url(r'^removeDestination$', views.remove_destination, name='removeDestinationInc'), + url(r'^fetchCurrentBackups$', views.fetch_current_backups, name='fetchCurrentBackupsInc'), + url(r'^submitBackupCreation$', views.submit_backup_creation, name='submitBackupCreationInc'), + url(r'^getBackupStatus$', views.get_backup_status, name='getBackupStatusInc'), + url(r'^deleteBackup$', views.delete_backup, name='deleteBackupInc'), + url(r'^fetchRestorePoints$', views.fetch_restore_points, name='fetchRestorePointsInc'), + url(r'^restorePoint$', views.restore_point, name='restorePointInc'), + url(r'^scheduleBackups$', views.schedule_backups, name='scheduleBackupsInc'), + url(r'^submitBackupSchedule$', views.submit_backup_schedule, name='submitBackupScheduleInc'), + url(r'^scheduleDelete$', views.schedule_delete, name='scheduleDeleteInc'), + url(r'^getCurrentBackupSchedules$', views.get_current_backup_schedules, name='getCurrentBackupSchedulesInc'), + url(r'^fetchSites$', views.fetch_sites, name='fetchSites'), + url(r'^saveChanges$', views.save_changes, name='saveChanges'), + url(r'^removeSite$', views.remove_site, name='removeSite'), + url(r'^addWebsite$', views.add_website, name='addWebsite'), ] \ No newline at end of file diff --git a/IncBackups/views.py b/IncBackups/views.py index fe229f0c9..bd8630d95 100644 --- a/IncBackups/views.py +++ b/IncBackups/views.py @@ -1,425 +1,339 @@ -# -*- coding: utf-8 -*- - -from django.shortcuts import render -from plogical.acl import ACLManager -from django.shortcuts import HttpResponse, redirect -from plogical.processUtilities import ProcessUtilities -from plogical.virtualHostUtilities import virtualHostUtilities import json import os -from loginSystem.models import Administrator -from websiteFunctions.models import Websites -from .models import IncJob, BackupJob, JobSites -from .IncBackupsControl import IncJobs -from random import randint -import time -from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging -from loginSystem.views import loadLoginPage import stat -# Create your views here. +import time +from pathlib import Path +from random import randint + +from django.shortcuts import HttpResponse, redirect +from django.shortcuts import render + +from loginSystem.models import Administrator +from loginSystem.views import loadLoginPage +from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging +from plogical.acl import ACLManager +from plogical.processUtilities import ProcessUtilities as pu +from plogical.virtualHostUtilities import virtualHostUtilities as vhu +from websiteFunctions.models import Websites +from .IncBackupProvider import IncBackupProvider +from .IncBackupPath import IncBackupPath +from .IncBackupsControl import IncJobs +from .models import IncJob, BackupJob, JobSites -def defRenderer(request, templateName, args): +def def_renderer(request, templateName, args): return render(request, templateName, args) -def createBackup(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'createBackup') == 0: - return ACLManager.loadError() - - websitesName = ACLManager.findAllSites(currentACL, userID) - - destinations = [] +def _get_destinations(local: bool = False): + destinations = [] + if local: destinations.append('local') + path = Path(IncBackupPath.SFTP.value) + if path.exists(): + for item in path.iterdir(): + destinations.append('sftp:%s' % item.name) - path = '/home/cyberpanel/sftp' + path = Path(IncBackupPath.AWS.value) + if path.exists(): + for item in path.iterdir(): + destinations.append('s3:s3.amazonaws.com/%s' % item.name) + return destinations - if os.path.exists(path): - for items in os.listdir(path): - destinations.append('sftp:%s' % (items)) - path = '/home/cyberpanel/aws' - if os.path.exists(path): - for items in os.listdir(path): - destinations.append('s3:s3.amazonaws.com/%s' % (items)) +def _get_user_acl(request): + user_id = request.session['userID'] + current_acl = ACLManager.loadedACL(user_id) + return user_id, current_acl - return defRenderer(request, 'IncBackups/createBackup.html', {'websiteList': websitesName, 'destinations': destinations}) - except BaseException as msg: - logging.writeToFile(str(msg)) - return redirect(loadLoginPage) -def backupDestinations(request): +def create_backup(request): try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0: + user_id, current_acl = _get_user_acl(request) + if ACLManager.currentContextPermission(current_acl, 'createBackup') == 0: return ACLManager.loadError() - return defRenderer(request, 'IncBackups/incrementalDestinations.html', {}) + websites = ACLManager.findAllSites(current_acl, user_id) + + destinations = _get_destinations(local=True) + + return def_renderer(request, 'IncBackups/createBackup.html', + {'websiteList': websites, 'destinations': destinations}) except BaseException as msg: logging.writeToFile(str(msg)) return redirect(loadLoginPage) -def addDestination(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0: +def backup_destinations(request): + try: + user_id, current_acl = _get_user_acl(request) + if ACLManager.currentContextPermission(current_acl, 'addDeleteDestinations') == 0: + return ACLManager.loadError() + + return def_renderer(request, 'IncBackups/incrementalDestinations.html', {}) + except BaseException as msg: + logging.writeToFile(str(msg)) + return redirect(loadLoginPage) + + +def add_destination(request): + try: + user_id, current_acl = _get_user_acl(request) + if ACLManager.currentContextPermission(current_acl, 'addDeleteDestinations') == 0: return ACLManager.loadErrorJson('destStatus', 0) data = json.loads(request.body) - if data['type'] == 'SFTP': + if data['type'].lower() == IncBackupProvider.SFTP.name.lower(): + path = Path(IncBackupPath.SFTP.value) + path.mkdir(exist_ok=True) - ipAddress = data['IPAddress'] + ip_address = data['IPAddress'] password = data['password'] - ipFile = '/home/cyberpanel/sftp/%s' % (ipAddress) + address_file = path / ip_address + port = data.get('backupSSHPort', '22') - try: - port = data['backupSSHPort'] - except: - port = "22" - - if os.path.exists(ipFile): + if address_file.exists(): final_dic = {'status': 0, 'error_message': 'This destination already exists.'} final_json = json.dumps(final_dic) return HttpResponse(final_json) + python_path = Path('/usr/local/CyberCP/bin/python') + backup_utils = Path(vhu.cyberPanel) / "plogical/backupUtilities.py" - try: - os.mkdir('/home/cyberpanel/sftp') - except: - pass + exec_args = "submitDestinationCreation --ipAddress %s --password %s --port %s --user %s" % \ + (ip_address, password, port, 'root') + exec_cmd = "%s %s %s" % (python_path, backup_utils, exec_args) - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" - execPath = execPath + " submitDestinationCreation --ipAddress " + ipAddress + " --password " \ - + password + " --port " + port + ' --user %s' % ('root') + if Path(pu.debugPath).exists(): + logging.writeToFile(exec_cmd) - if os.path.exists(ProcessUtilities.debugPath): - logging.writeToFile(execPath) + output = pu.outputExecutioner(exec_cmd) - output = ProcessUtilities.outputExecutioner(execPath) - - if os.path.exists(ProcessUtilities.debugPath): + if Path(pu.debugPath).exists(): logging.writeToFile(output) if output.find('1,') > -1: - - content = '%s\n%s' % (ipAddress, port) - writeToFile = open(ipFile, 'w') - writeToFile.write(content) - writeToFile.close() + content = '%s\n%s' % (ip_address, port) + with open(address_file, 'w') as outfile: + outfile.write(content) command = 'cat /root/.ssh/config' - currentConfig = ProcessUtilities.outputExecutioner(command) + current_config = pu.outputExecutioner(command) - tmpFile = '/home/cyberpanel/sshconfig' + tmp_file = '/home/cyberpanel/sshconfig' + with open(tmp_file, 'w') as outfile: + if current_config.find('cat') == -1: + outfile.write(current_config) - writeToFile = open(tmpFile, 'w') - if currentConfig.find('cat') == -1: - writeToFile.write(currentConfig) + content = "Host %s\n" \ + " IdentityFile ~/.ssh/cyberpanel\n" \ + " Port %s\n" % (ip_address, port) + if current_config.find(ip_address) == -1: + outfile.write(content) - content = """Host %s - IdentityFile ~/.ssh/cyberpanel - Port %s -""" % (ipAddress, port) - if currentConfig.find(ipAddress) == -1: - writeToFile.write(content) - writeToFile.close() - - - command = 'mv %s /root/.ssh/config' % (tmpFile) - ProcessUtilities.executioner(command) + command = 'mv %s /root/.ssh/config' % tmp_file + pu.executioner(command) command = 'chown root:root /root/.ssh/config' - ProcessUtilities.executioner(command) + pu.executioner(command) final_dic = {'status': 1, 'error_message': 'None'} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - else: final_dic = {'status': 0, 'error_message': output} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - else: - aws = '/home/cyberpanel/aws' + final_json = json.dumps(final_dic) + return HttpResponse(final_json) - try: - os.mkdir(aws) - except: - pass + if data['type'].lower() == IncBackupProvider.AWS.name.lower(): + path = Path(IncBackupPath.AWS.value) + path.mkdir(exist_ok=True) - AWS_ACCESS_KEY_ID = data['AWS_ACCESS_KEY_ID'] - AWS_SECRET_ACCESS_KEY = data['AWS_SECRET_ACCESS_KEY'] + access_key = data['AWS_ACCESS_KEY_ID'] + secret_key = data['AWS_SECRET_ACCESS_KEY'] - awsFile = '/home/cyberpanel/aws/%s' % (AWS_ACCESS_KEY_ID) + aws_file = path / access_key - writeToFile = open(awsFile, 'w') - writeToFile.write(AWS_SECRET_ACCESS_KEY) - writeToFile.close() + with open(aws_file, 'w') as outfile: + outfile.write(secret_key) - os.chmod(awsFile, stat.S_IRUSR | stat.S_IWUSR) + aws_file.chmod(stat.S_IRUSR | stat.S_IWUSR) final_dic = {'status': 1} final_json = json.dumps(final_dic) return HttpResponse(final_json) - except BaseException as msg: final_dic = {'status': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json) -def populateCurrentRecords(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0: +def populate_current_records(request): + try: + user_id, current_acl = _get_user_acl(request) + if ACLManager.currentContextPermission(current_acl, 'addDeleteDestinations') == 0: return ACLManager.loadErrorJson('fetchStatus', 0) data = json.loads(request.body) - if data['type'] == 'SFTP': + json_data = [] + if data['type'].lower() == IncBackupProvider.SFTP.name.lower(): + path = Path(IncBackupPath.SFTP.value) - path = '/home/cyberpanel/sftp' - - if os.path.exists(path): - - json_data = "[" - checker = 0 - - for items in os.listdir(path): - fullPath = '/home/cyberpanel/sftp/%s' % (items) - - data = open(fullPath, 'r').readlines() - dic = { - 'ip': data[0].strip('\n'), - 'port': data[1], - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - else: - final_json = json.dumps({'status': 1, 'error_message': "None", "data": ''}) - return HttpResponse(final_json) - else: - path = '/home/cyberpanel/aws' - - if os.path.exists(path): - - json_data = "[" - checker = 0 - - for items in os.listdir(path): - dic = { - 'AWS_ACCESS_KEY_ID': items - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) + if path.exists(): + for item in path.iterdir(): + with open(item, 'r') as infile: + _file = infile.readlines() + json_data.append({ + 'ip': _file[0].strip('\n'), + 'port': _file[1], + }) + else: + final_json = json.dumps({'status': 1, 'error_message': "None", "data": ''}) + return HttpResponse(final_json) + + if data['type'].lower() == IncBackupProvider.AWS.name.lower(): + path = Path(IncBackupPath.AWS.value) + + if path.exists(): + for item in path.iterdir(): + json_data.append({'AWS_ACCESS_KEY_ID': item.name}) else: final_json = json.dumps({'status': 1, 'error_message': "None", "data": ''}) return HttpResponse(final_json) - json_data = json_data + ']' final_json = json.dumps({'status': 1, 'error_message': "None", "data": json_data}) return HttpResponse(final_json) - except BaseException as msg: final_dic = {'status': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json) -def removeDestination(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0: +def remove_destination(request): + try: + user_id, current_acl = _get_user_acl(request) + if ACLManager.currentContextPermission(current_acl, 'addDeleteDestinations') == 0: return ACLManager.loadErrorJson('destStatus', 0) data = json.loads(request.body) - ipAddress = data['IPAddress'] + if 'IPAddress' in data: + file_name = data['IPAddress'] - if data['type'] == 'SFTP': - ipFile = '/home/cyberpanel/sftp/%s' % (ipAddress) - else: - ipFile = '/home/cyberpanel/aws/%s' % (ipAddress) + if data['type'].lower() == IncBackupProvider.SFTP.name.lower(): + dest_file = Path(IncBackupPath.SFTP.value) / file_name + dest_file.unlink() - - os.remove(ipFile) + if data['type'].lower() == IncBackupProvider.AWS.name.lower(): + dest_file = Path(IncBackupPath.AWS.value) / file_name + dest_file.unlink() final_dic = {'status': 1, 'error_message': 'None'} final_json = json.dumps(final_dic) return HttpResponse(final_json) - except BaseException as msg: final_dic = {'destStatus': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json) -def fetchCurrentBackups(request): + +def fetch_current_backups(request): try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) + user_id, current_acl = _get_user_acl(request) + admin = Administrator.objects.get(pk=user_id) data = json.loads(request.body) - backupDomain = data['websiteToBeBacked'] + backup_domain = data['websiteToBeBacked'] - if ACLManager.checkOwnership(backupDomain, admin, currentACL) == 1: + if ACLManager.checkOwnership(backup_domain, admin, current_acl) == 1: pass else: return ACLManager.loadErrorJson('fetchStatus', 0) - if ACLManager.checkOwnership(backupDomain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() + if 'backupDestinations' in data: + backup_destinations = data['backupDestinations'] + extra_args = {'website': backup_domain, 'backupDestinations': backup_destinations} - try: - backupDestinations = data['backupDestinations'] - - extraArgs = {} - extraArgs['website'] = backupDomain - extraArgs['backupDestinations'] = backupDestinations - try: - extraArgs['password'] = data['password'] - except: + if 'password' in data: + extra_args['password'] = data['password'] + else: final_json = json.dumps({'status': 0, 'error_message': "Please supply the password."}) return HttpResponse(final_json) - startJob = IncJobs('Dummpy', extraArgs) - return startJob.fetchCurrentBackups() - - except: - - website = Websites.objects.get(domain=backupDomain) - + start_job = IncJobs('Dummy', extra_args) + return start_job.fetchCurrentBackups() + else: + website = Websites.objects.get(domain=backup_domain) backups = website.incjob_set.all() - - json_data = "[" - checker = 0 - - for items in reversed(backups): - - includes = "" - - jobs = items.jobsnapshots_set.all() - + json_data = [] + for backup in reversed(backups): + snapshots = [] + jobs = backup.jobsnapshots_set.all() for job in jobs: - includes = '%s,%s:%s' % (includes, job.type, job.snapshotid) - - dic = {'id': items.id, - 'date': str(items.date), - 'includes': includes - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' + snapshots.append({'type': job.type, 'snapshotid': job.snapshotid, 'destination': job.destination}) + json_data.append({'id': backup.id, + 'date': str(backup.date), + 'snapshots': snapshots + }) final_json = json.dumps({'status': 1, 'error_message': "None", "data": json_data}) return HttpResponse(final_json) - - except BaseException as msg: final_dic = {'status': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json) -def submitBackupCreation(request): + +def submit_backup_creation(request): try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) + user_id, current_acl = _get_user_acl(request) + admin = Administrator.objects.get(pk=user_id) data = json.loads(request.body) - backupDomain = data['websiteToBeBacked'] - backupDestinations = data['backupDestinations'] + backup_domain = data['websiteToBeBacked'] + backup_destinations = data['backupDestinations'] - if ACLManager.checkOwnership(backupDomain, admin, currentACL) == 1: + if ACLManager.checkOwnership(backup_domain, admin, current_acl) == 1: pass else: return ACLManager.loadErrorJson('metaStatus', 0) - tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + temp_path = Path("/home/cyberpanel/") / str(randint(1000, 9999)) - try: - websiteData = data['websiteData'] - except: - websiteData = False + extra_args = {} + extra_args['website'] = backup_domain + extra_args['tempPath'] = str(temp_path) + extra_args['backupDestinations'] = backup_destinations + extra_args['websiteData'] = data['websiteData'] if 'websiteData' in data else False + extra_args['websiteEmails'] = data['websiteEmails'] if 'websiteEmails' in data else False + extra_args['websiteSSLs'] = data['websiteSSLs'] if 'websiteSSLs' in data else False + extra_args['websiteDatabases'] = data['websiteDatabases'] if 'websiteDatabases' in data else False - try: - websiteEmails = data['websiteEmails'] - except: - websiteEmails = False - - try: - websiteSSLs = data['websiteSSLs'] - except: - websiteSSLs = False - - - try: - websiteDatabases = data['websiteDatabases'] - except: - websiteDatabases = False - - extraArgs = {} - extraArgs['website'] = backupDomain - extraArgs['tempPath'] = tempPath - extraArgs['backupDestinations'] = backupDestinations - extraArgs['websiteData'] = websiteData - extraArgs['websiteEmails'] = websiteEmails - extraArgs['websiteSSLs'] = websiteSSLs - extraArgs['websiteDatabases'] = websiteDatabases - - startJob = IncJobs('createBackup', extraArgs) - startJob.start() + start_job = IncJobs('createBackup', extra_args) + start_job.start() time.sleep(2) - final_json = json.dumps({'status': 1, 'error_message': "None", 'tempPath': tempPath}) + final_json = json.dumps({'status': 1, 'error_message': "None", 'tempPath': str(temp_path)}) return HttpResponse(final_json) - except BaseException as msg: logging.writeToFile(str(msg)) final_dic = {'status': 0, 'metaStatus': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json) -def getBackupStatus(request): + +def get_backup_status(request): try: data = json.loads(request.body) status = data['tempPath'] - backupDomain = data['websiteToBeBacked'] + backup_domain = data['websiteToBeBacked'] - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(backupDomain, admin, currentACL) == 1: + user_id, current_acl = _get_user_acl(request) + admin = Administrator.objects.get(pk=user_id) + if ACLManager.checkOwnership(backup_domain, admin, current_acl) == 1: pass else: return ACLManager.loadErrorJson('fetchStatus', 0) @@ -437,7 +351,7 @@ def getBackupStatus(request): if os.path.exists(status): command = "cat " + status - result = ProcessUtilities.outputExecutioner(command, 'cyberpanel') + result = pu.outputExecutioner(command, 'cyberpanel') if result.find("Completed") > -1: @@ -468,77 +382,65 @@ def getBackupStatus(request): else: final_json = json.dumps({'backupStatus': 1, 'error_message': "None", "status": 1, "abort": 0}) return HttpResponse(final_json) - except BaseException as msg: final_dic = {'backupStatus': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) logging.writeToFile(str(msg) + " [backupStatus]") return HttpResponse(final_json) -def deleteBackup(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - data = json.loads(request.body) - backupDomain = data['websiteToBeBacked'] - if ACLManager.checkOwnership(backupDomain, admin, currentACL) == 1: +def delete_backup(request): + try: + user_id, current_acl = _get_user_acl(request) + admin = Administrator.objects.get(pk=user_id) + data = json.loads(request.body) + backup_domain = data['websiteToBeBacked'] + + if ACLManager.checkOwnership(backup_domain, admin, current_acl) == 1: pass else: return ACLManager.loadErrorJson('fetchStatus', 0) - id = data['backupID'] + backup_id = data['backupID'] - IncJob.objects.get(id=id).delete() + IncJob.objects.get(id=backup_id).delete() final_dic = {'status': 1, 'error_message': 'None'} final_json = json.dumps(final_dic) return HttpResponse(final_json) - except BaseException as msg: final_dic = {'destStatus': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json) -def fetchRestorePoints(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - data = json.loads(request.body) - backupDomain = data['websiteToBeBacked'] - if ACLManager.checkOwnership(backupDomain, admin, currentACL) == 1: +def fetch_restore_points(request): + try: + user_id, current_acl = _get_user_acl(request) + admin = Administrator.objects.get(pk=user_id) + data = json.loads(request.body) + backup_domain = data['websiteToBeBacked'] + + if ACLManager.checkOwnership(backup_domain, admin, current_acl) == 1: pass else: return ACLManager.loadErrorJson('fetchStatus', 0) data = json.loads(request.body) - id = data['id'] + job_id = data['id'] - incJob = IncJob.objects.get(id=id) + inc_job = IncJob.objects.get(id=job_id) - backups = incJob.jobsnapshots_set.all() - - json_data = "[" - checker = 0 + backups = inc_job.jobsnapshots_set.all() + json_data = [] for items in backups: + json_data.append({'id': items.id, + 'snapshotid': items.snapshotid, + 'type': items.type, + 'destination': items.destination, + }) - dic = {'id': items.id, - 'snapshotid': items.snapshotid, - 'type': items.type, - 'destination': items.destination, - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' final_json = json.dumps({'status': 1, 'error_message': "None", "data": json_data}) return HttpResponse(final_json) except BaseException as msg: @@ -546,350 +448,256 @@ def fetchRestorePoints(request): final_json = json.dumps(final_dic) return HttpResponse(final_json) -def restorePoint(request): + +def restore_point(request): try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) + user_id, current_acl = _get_user_acl(request) + admin = Administrator.objects.get(pk=user_id) data = json.loads(request.body) - backupDomain = data['websiteToBeBacked'] - jobid = data['jobid'] + backup_domain = data['websiteToBeBacked'] + job_id = data['jobid'] - if ACLManager.checkOwnership(backupDomain, admin, currentACL) == 1: + if ACLManager.checkOwnership(backup_domain, admin, current_acl) == 1: pass else: return ACLManager.loadErrorJson('metaStatus', 0) - tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + temp_path = Path("/home/cyberpanel/") / str(randint(1000, 9999)) if data['reconstruct'] == 'remote': extraArgs = {} - extraArgs['website'] = backupDomain - extraArgs['jobid'] = jobid - extraArgs['tempPath'] = tempPath + extraArgs['website'] = backup_domain + extraArgs['jobid'] = job_id + extraArgs['tempPath'] = str(temp_path) extraArgs['reconstruct'] = data['reconstruct'] extraArgs['backupDestinations'] = data['backupDestinations'] extraArgs['password'] = data['password'] extraArgs['path'] = data['path'] else: extraArgs = {} - extraArgs['website'] = backupDomain - extraArgs['jobid'] = jobid - extraArgs['tempPath'] = tempPath + extraArgs['website'] = backup_domain + extraArgs['jobid'] = job_id + extraArgs['tempPath'] = str(temp_path) extraArgs['reconstruct'] = data['reconstruct'] - - startJob = IncJobs('restorePoint', extraArgs) - startJob.start() - + start_job = IncJobs('restorePoint', extraArgs) + start_job.start() time.sleep(2) - final_json = json.dumps({'status': 1, 'error_message': "None", 'tempPath': tempPath}) + final_json = json.dumps({'status': 1, 'error_message': "None", 'tempPath': str(temp_path)}) return HttpResponse(final_json) - except BaseException as msg: logging.writeToFile(str(msg)) final_dic = {'status': 0, 'metaStatus': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json) -def scheduleBackups(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: +def schedule_backups(request): + try: + user_id, current_acl = _get_user_acl(request) + if ACLManager.currentContextPermission(current_acl, 'scheDuleBackups') == 0: return ACLManager.loadError() - websitesName = ACLManager.findAllSites(currentACL, userID) + websites = ACLManager.findAllSites(current_acl, user_id) - destinations = [] - destinations.append('local') + destinations = _get_destinations(local=True) - path = '/home/cyberpanel/sftp' - - if os.path.exists(path): - for items in os.listdir(path): - destinations.append('sftp:%s' % (items)) - - path = '/home/cyberpanel/aws' - if os.path.exists(path): - for items in os.listdir(path): - destinations.append('s3:s3.amazonaws.com/%s' % (items)) - - websitesName = ACLManager.findAllSites(currentACL, userID) - - return defRenderer(request, 'IncBackups/backupSchedule.html', {'websiteList': websitesName, 'destinations': destinations}) + return def_renderer(request, 'IncBackups/backupSchedule.html', + {'websiteList': websites, 'destinations': destinations}) except BaseException as msg: logging.writeToFile(str(msg)) return redirect(loadLoginPage) -def submitBackupSchedule(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: +def submit_backup_schedule(request): + try: + user_id, current_acl = _get_user_acl(request) + if ACLManager.currentContextPermission(current_acl, 'scheDuleBackups') == 0: return ACLManager.loadErrorJson('scheduleStatus', 0) data = json.loads(request.body) - backupDest = data['backupDestinations'] - backupFreq = data['backupFreq'] - websitesToBeBacked = data['websitesToBeBacked'] + backup_dest = data['backupDestinations'] + backup_freq = data['backupFreq'] + backup_sites = data['websitesToBeBacked'] - try: - websiteData = data['websiteData'] - websiteData = 1 - except: - websiteData = False - websiteData = 0 + backup_data = 1 if 'websiteData' in data else 0 + backup_emails = 1 if 'websiteEmails' in data else 0 + backup_databases = 1 if 'websiteDatabases' in data else 0 - try: - websiteEmails = data['websiteEmails'] - websiteEmails = 1 - except: - websiteEmails = False - websiteEmails = 0 + backup_job = BackupJob(websiteData=backup_data, websiteDataEmails=backup_emails, + websiteDatabases=backup_databases, destination=backup_dest, frequency=backup_freq) + backup_job.save() - try: - websiteDatabases = data['websiteDatabases'] - websiteDatabases = 1 - except: - websiteDatabases = False - websiteDatabases = 0 - - newJob = BackupJob(websiteData=websiteData, websiteDataEmails=websiteEmails, websiteDatabases=websiteDatabases, destination=backupDest, frequency=backupFreq) - newJob.save() - - for items in websitesToBeBacked: - jobsite = JobSites(job=newJob, website=items) - jobsite.save() + for site in backup_sites: + backup_site_job = JobSites(job=backup_job, website=site) + backup_site_job.save() final_json = json.dumps({'status': 1, 'error_message': "None"}) return HttpResponse(final_json) - - except BaseException as msg: final_json = json.dumps({'status': 0, 'error_message': str(msg)}) return HttpResponse(final_json) -def getCurrentBackupSchedules(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: +def get_current_backup_schedules(request): + try: + user_id, current_acl = _get_user_acl(request) + if ACLManager.currentContextPermission(current_acl, 'scheDuleBackups') == 0: return ACLManager.loadErrorJson('fetchStatus', 0) records = BackupJob.objects.all() - json_data = "[" - checker = 0 - + json_data = [] for items in records: - dic = {'id': items.id, - 'destination': items.destination, - 'frequency': items.frequency, - 'numberOfSites': items.jobsites_set.all().count() - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' + json_data.append({'id': items.id, + 'destination': items.destination, + 'frequency': items.frequency, + 'numberOfSites': items.jobsites_set.all().count() + }) final_json = json.dumps({'status': 1, 'error_message': "None", "data": json_data}) return HttpResponse(final_json) - except BaseException as msg: final_dic = {'status': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json) -def fetchSites(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: +def fetch_sites(request): + try: + user_id, current_acl = _get_user_acl(request) + if ACLManager.currentContextPermission(current_acl, 'scheDuleBackups') == 0: return ACLManager.loadErrorJson('fetchStatus', 0) data = json.loads(request.body) job = BackupJob.objects.get(pk=data['id']) - json_data = "[" - checker = 0 - - for items in job.jobsites_set.all(): - dic = {'id': items.id, - 'website': items.website, - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' + json_data = [] + for jobsite in job.jobsites_set.all(): + json_data.append({'id': jobsite.id, + 'website': jobsite.website, + }) final_json = json.dumps({'status': 1, 'error_message': "None", "data": json_data, 'websiteData': job.websiteData, 'websiteDatabases': job.websiteDatabases, 'websiteEmails': job.websiteDataEmails}) return HttpResponse(final_json) - except BaseException as msg: final_dic = {'status': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json) -def scheduleDelete(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: +def schedule_delete(request): + try: + user_id, current_acl = _get_user_acl(request) + if ACLManager.currentContextPermission(current_acl, 'scheDuleBackups') == 0: return ACLManager.loadErrorJson('scheduleStatus', 0) data = json.loads(request.body) - id = data['id'] + job_id = data['id'] - backupJob = BackupJob.objects.get(id=id) - backupJob.delete() + backup_job = BackupJob.objects.get(id=job_id) + backup_job.delete() final_json = json.dumps({'status': 1, 'error_message': "None"}) return HttpResponse(final_json) - except BaseException as msg: final_json = json.dumps({'status': 0, 'error_message': str(msg)}) return HttpResponse(final_json) -def restoreRemoteBackups(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'createBackup') == 0: +def restore_remote_backups(request): + try: + user_id, current_acl = _get_user_acl(request) + if ACLManager.currentContextPermission(current_acl, 'createBackup') == 0: return ACLManager.loadError() - websitesName = ACLManager.findAllSites(currentACL, userID) + websites = ACLManager.findAllSites(current_acl, user_id) - destinations = [] + destinations = _get_destinations() - path = '/home/cyberpanel/sftp' - - if os.path.exists(path): - for items in os.listdir(path): - destinations.append('sftp:%s' % (items)) - - path = '/home/cyberpanel/aws' - if os.path.exists(path): - for items in os.listdir(path): - destinations.append('s3:s3.amazonaws.com/%s' % (items)) - - return defRenderer(request, 'IncBackups/restoreRemoteBackups.html', {'websiteList': websitesName, 'destinations': destinations}) + return def_renderer(request, 'IncBackups/restoreRemoteBackups.html', + {'websiteList': websites, 'destinations': destinations}) except BaseException as msg: logging.writeToFile(str(msg)) return redirect(loadLoginPage) -def saveChanges(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: +def save_changes(request): + try: + user_id, current_acl = _get_user_acl(request) + if ACLManager.currentContextPermission(current_acl, 'scheDuleBackups') == 0: return ACLManager.loadErrorJson('scheduleStatus', 0) data = json.loads(request.body) - id = data['id'] - try: - websiteData = data['websiteData'] - except: - websiteData = 0 - try: - websiteDatabases = data['websiteDatabases'] - except: - websiteDatabases = 0 - try: - websiteEmails = data['websiteEmails'] - except: - websiteEmails = 0 + job_id = data['id'] - job = BackupJob.objects.get(pk=id) + backup_data = data['websiteData'] if 'websiteData' in data else 0 + backup_emails = data['websiteEmails'] if 'websiteEmails' in data else 0 + backup_databases = data['websiteDatabases'] if 'websiteDatabases' in data else 0 - job.websiteData = int(websiteData) - job.websiteDatabases = int(websiteDatabases) - job.websiteDataEmails = int(websiteEmails) + job = BackupJob.objects.get(pk=job_id) + + job.websiteData = int(backup_data) + job.websiteDatabases = int(backup_databases) + job.websiteDataEmails = int(backup_emails) job.save() final_json = json.dumps({'status': 1, 'error_message': "None"}) return HttpResponse(final_json) - - except BaseException as msg: final_json = json.dumps({'status': 0, 'error_message': str(msg)}) return HttpResponse(final_json) -def removeSite(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: +def remove_site(request): + try: + _, current_acl = _get_user_acl(request) + if ACLManager.currentContextPermission(current_acl, 'scheDuleBackups') == 0: return ACLManager.loadErrorJson('scheduleStatus', 0) data = json.loads(request.body) - id = data['id'] + job_id = data['id'] website = data['website'] - - - job = BackupJob.objects.get(pk=id) - + job = BackupJob.objects.get(pk=job_id) site = JobSites.objects.get(job=job, website=website) site.delete() final_json = json.dumps({'status': 1, 'error_message': "None"}) return HttpResponse(final_json) - - except BaseException as msg: final_json = json.dumps({'status': 0, 'error_message': str(msg)}) return HttpResponse(final_json) -def addWebsite(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: +def add_website(request): + try: + _, current_acl = _get_user_acl(request) + if ACLManager.currentContextPermission(current_acl, 'scheDuleBackups') == 0: return ACLManager.loadErrorJson('scheduleStatus', 0) data = json.loads(request.body) - id = data['id'] + job_id = data['id'] website = data['website'] - - job = BackupJob.objects.get(pk=id) + job = BackupJob.objects.get(pk=job_id) try: JobSites.objects.get(job=job, website=website) - except: + except BaseException: site = JobSites(job=job, website=website) site.save() final_json = json.dumps({'status': 1, 'error_message': "None"}) return HttpResponse(final_json) - - except BaseException as msg: final_json = json.dumps({'status': 0, 'error_message': str(msg)}) - return HttpResponse(final_json) \ No newline at end of file + return HttpResponse(final_json) diff --git a/static/IncBackups/IncBackups.js b/static/IncBackups/IncBackups.js index 32b01ef70..9031c393d 100644 --- a/static/IncBackups/IncBackups.js +++ b/static/IncBackups/IncBackups.js @@ -101,7 +101,7 @@ app.controller('createIncrementalBackups', function ($scope, $http, $timeout) { function ListInitialDatas(response) { if (response.data.status === 1) { - $scope.records = JSON.parse(response.data.data); + $scope.records = response.data.data; } else { new PNotify({ title: 'Error!', @@ -240,7 +240,7 @@ app.controller('createIncrementalBackups', function ($scope, $http, $timeout) { function ListInitialDatas(response) { $scope.cyberpanelLoading = true; if (response.data.status === 1) { - $scope.jobs = JSON.parse(response.data.data); + $scope.jobs = response.data.data; } else { new PNotify({ title: 'Operation Failed!', @@ -358,7 +358,7 @@ app.controller('incrementalDestinations', function ($scope, $http) { function ListInitialDatas(response) { $scope.cyberpanelLoading = true; if (response.data.status === 1) { - $scope.records = JSON.parse(response.data.data); + $scope.records = response.data.data; } else { new PNotify({ title: 'Operation Failed!', @@ -621,7 +621,7 @@ app.controller('scheduleBackupInc', function ($scope, $http) { if (response.data.status === 1) { new PNotify({ title: 'Success!', - text: 'Destination successfully removed.', + text: 'Operation successful.', type: 'success' }); } else { @@ -668,12 +668,11 @@ app.controller('scheduleBackupInc', function ($scope, $http) { function ListInitialDatas(response) { $scope.cyberpanelLoading = true; if (response.data.status === 1) { - $scope.records = JSON.parse(response.data.data); - var parsed = JSON.parse(response.data.data); - - for (var j = 0; j < parsed.length; j++) { - websitesToBeBackedTemp.push(parsed[j].website); - } + let data = response.data.data; + $scope.records = data; + data.forEach(item => { + websitesToBeBackedTemp.push(item.website) + }) } else { new PNotify({ title: 'Operation Failed!', @@ -766,7 +765,7 @@ app.controller('scheduleBackupInc', function ($scope, $http) { function ListInitialDatas(response) { $scope.cyberpanelLoading = true; if (response.data.status === 1) { - $scope.websites = JSON.parse(response.data.data); + $scope.websites = response.data.data; if(response.data.websiteData === 1){ $scope.websiteData = true; @@ -1074,7 +1073,7 @@ app.controller('restoreRemoteBackupsInc', function ($scope, $http, $timeout) { function ListInitialDatas(response) { $scope.cyberpanelLoading = true; if (response.data.status === 1) { - $scope.records = JSON.parse(response.data.data); + $scope.records = response.data.data; } else { new PNotify({ title: 'Error!',