diff --git a/CLManager/CLManagerMain.py b/CLManager/CLManagerMain.py index 2a02fd91c..a2809033f 100644 --- a/CLManager/CLManagerMain.py +++ b/CLManager/CLManagerMain.py @@ -10,7 +10,7 @@ from django.shortcuts import HttpResponse from math import ceil from websiteFunctions.models import Websites from CLManager.models import CLPackages - +from plogical.httpProc import httpProc class CLManagerMain(multi.Thread): @@ -27,29 +27,14 @@ class CLManagerMain(multi.Thread): self.submitCageFSInstall() elif self.function == 'enableOrDisable': self.enableOrDisable() - except BaseException as msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + ' [ContainerManager.run]') def renderC(self): - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - data = {} data['CL'] = 0 data['activatedPath'] = 0 - data['ipAddress'] = ipAddress CLPath = '/etc/sysconfig/cloudlinux' activatedPath = '/home/cyberpanel/cloudlinux' @@ -60,11 +45,14 @@ class CLManagerMain(multi.Thread): data['activatedPath'] = 1 if data['CL'] == 0: - return render(self.request, 'CLManager/notAvailable.html', data) + proc = httpProc(self.request, 'CLManager/notAvailable.html', data, 'admin') + return proc.render() elif data['activatedPath'] == 0: - return render(self.request, 'CLManager/notAvailable.html', data) + proc = httpProc(self.request, 'CLManager/notAvailable.html', data, 'admin') + return proc.render() else: - return render(self.request, 'CLManager/cloudLinux.html', data) + proc = httpProc(self.request, 'CLManager/cloudLinux.html', data, 'admin') + return proc.render() def submitCageFSInstall(self): try: diff --git a/CLScript/CLMain.py b/CLScript/CLMain.py index c6f730ba4..0d09cec9b 100644 --- a/CLScript/CLMain.py +++ b/CLScript/CLMain.py @@ -4,8 +4,8 @@ class CLMain(): def __init__(self): self.path = '/usr/local/CyberCP/version.txt' #versionInfo = json.loads(open(self.path, 'r').read()) - self.version = '2.0' - self.build = '3' + self.version = '2.1' + self.build = '1' ipFile = "/etc/cyberpanel/machineIP" f = open(ipFile) diff --git a/CLScript/CloudLinuxResellers.py b/CLScript/CloudLinuxResellers.py index 0f93d04a6..c64509b33 100755 --- a/CLScript/CloudLinuxResellers.py +++ b/CLScript/CloudLinuxResellers.py @@ -14,7 +14,6 @@ import argparse import json from CLScript.CLMain import CLMain - class CloudLinuxResellers(CLMain): def __init__(self, id, name): @@ -23,17 +22,26 @@ class CloudLinuxResellers(CLMain): self.name = name def listAll(self, owner=None): + import pwd users = [] acl = ACL.objects.get(name='reseller') + from plogical.vhost import vhost for items in Administrator.objects.filter(acl=acl): if self.name != None: if self.name != items.userName: continue + + try: + uid = pwd.getpwnam(items.userName).pw_uid + except: + vhost.addUser(items.userName, '/home/%s' % (items.userName)) + uid = pwd.getpwnam(items.userName).pw_uid + user = {'name': items.userName, "locale_code": "EN_us", "email": items.email, - "id": None + "id": uid } users.append(user) diff --git a/CLScript/CloudLinuxUsers.py b/CLScript/CloudLinuxUsers.py index bdc984655..a26d2e9e5 100755 --- a/CLScript/CloudLinuxUsers.py +++ b/CLScript/CloudLinuxUsers.py @@ -81,7 +81,7 @@ class CloudLinuxUsers(CLMain): for webs in websites: try: itemPackage = webs.package - package = {'name': itemPackage.packageName, 'owner': webs.externalApp} + package = {'name': itemPackage.packageName, 'owner': webs.admin.userName} user = {} @@ -92,7 +92,12 @@ class CloudLinuxUsers(CLMain): user['username'] = webs.externalApp if self.ow: - user['owner'] = webs.externalApp + if webs.admin.owner == 1: + user['owner'] = webs.admin.userName + else: + from loginSystem.models import Administrator + oAdmin = Administrator.objects.get(pk=webs.admin.owner) + user['owner'] = oAdmin.userName if self.domain: user['domain'] = webs.domain @@ -133,7 +138,11 @@ class CloudLinuxUsers(CLMain): if self.owner == None: websites = Websites.objects.all() else: - websites = Websites.objects.filter(externalApp=self.owner) + from loginSystem.models import Administrator + from plogical.acl import ACLManager + oAdmin = Administrator.objects.get(userName=self.owner) + currentACL = ACLManager.loadedACL(oAdmin.pk) + websites = ACLManager.findWebsiteObjects(currentACL, oAdmin.pk) if self.username != None: websites = websites.filter(externalApp=self.username) diff --git a/CLScript/UserInfo.py b/CLScript/UserInfo.py index 472b614f3..55b266be9 100755 --- a/CLScript/UserInfo.py +++ b/CLScript/UserInfo.py @@ -2,10 +2,15 @@ import getpass def main(): + import pwd if getpass.getuser() == 'root': userType = "admin" else: - userType = "user" + try: + uid = pwd.getpwnam(getpass.getuser()).pw_uid + userType = 'reseller' + except: + userType = 'user' data = """{ "userName": "%s", diff --git a/CyberCP/secMiddleware.py b/CyberCP/secMiddleware.py index 8f0271330..064b6e905 100755 --- a/CyberCP/secMiddleware.py +++ b/CyberCP/secMiddleware.py @@ -1,7 +1,7 @@ # coding=utf-8 from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging import json -from django.shortcuts import HttpResponse +from django.shortcuts import HttpResponse, render import re from loginSystem.models import Administrator @@ -96,17 +96,24 @@ class secMiddleware: logging.writeToFile(str(msg)) response = self.get_response(request) return response - + # else: + # try: + # if request.path.find('cloudAPI/') > -1 or request.path.find('api/') > -1: + # pass + # else: + # uID = request.session['userID'] + # except: + # return render(request, 'loginSystem/login.html', {}) response = self.get_response(request) response['X-XSS-Protection'] = "1; mode=block" - #response['Strict-Transport-Security'] = "max-age=31536000; includeSubDomains; preload" response['X-Frame-Options'] = "sameorigin" response['Content-Security-Policy'] = "script-src 'self' https://www.jsdelivr.com" response['Content-Security-Policy'] = "connect-src *;" response['Content-Security-Policy'] = "font-src 'self' 'unsafe-inline' https://www.jsdelivr.com https://fonts.googleapis.com" response['Content-Security-Policy'] = "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://www.jsdelivr.com https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://cdn.jsdelivr.net" + #response['Content-Security-Policy'] = "default-src 'self' cyberpanel.cloud *.cyberpanel.cloud" response['X-Content-Type-Options'] = "nosniff" response['Referrer-Policy'] = "same-origin" 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..399cd0bfd 100644 --- a/IncBackups/views.py +++ b/IncBackups/views.py @@ -1,425 +1,341 @@ -# -*- 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 loginSystem.models import Administrator +from loginSystem.views import loadLoginPage +from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging +from plogical.acl import ACLManager +from plogical.httpProc import httpProc +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): - return render(request, templateName, args) +def def_renderer(request, templateName, args, context=None): + proc = httpProc(request, templateName, + args, context) + return proc.render() -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}, 'createBackup') 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', {}, 'addDeleteDestinations') + 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 +353,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 +384,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 +450,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}, 'scheDuleBackups') 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}, 'createBackup') 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/README.md b/README.md index fa624628a..5ec273ceb 100755 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ Webhosting control panel that uses OpenLiteSpeed as web server. * PHP 7.2 * PHP 7.3 * PHP 7.4 +* PHP 8.0 # Installation Instructions diff --git a/WebTerminal/views.py b/WebTerminal/views.py index 145cfc3bf..17d8ff718 100644 --- a/WebTerminal/views.py +++ b/WebTerminal/views.py @@ -7,6 +7,8 @@ from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging from loginSystem.views import loadLoginPage from random import randint import os + +from plogical.httpProc import httpProc from plogical.processUtilities import ProcessUtilities from plogical.firewallUtilities import FirewallUtilities from firewall.models import FirewallRules @@ -16,44 +18,32 @@ import plogical.randomPassword # Create your views here. def terminal(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + password = plogical.randomPassword.generate_pass() - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() + verifyPath = "/home/cyberpanel/" + str(randint(100000, 999999)) + writeToFile = open(verifyPath, 'w') + writeToFile.write(password) + writeToFile.close() - password = plogical.randomPassword.generate_pass() + ## setting up ssh server + path = '/etc/systemd/system/cpssh.service' + curPath = '/usr/local/CyberCP/WebTerminal/cpssh.service' - verifyPath = "/home/cyberpanel/" + str(randint(100000, 999999)) - writeToFile = open(verifyPath, 'w') - writeToFile.write(password) - writeToFile.close() + if not os.path.exists(path): + command = 'mv %s %s' % (curPath, path) + ProcessUtilities.executioner(command) - ## setting up ssh server - path = '/etc/systemd/system/cpssh.service' - curPath = '/usr/local/CyberCP/WebTerminal/cpssh.service' + command = 'systemctl start cpssh' + ProcessUtilities.executioner(command) - if not os.path.exists(path): - command = 'mv %s %s' % (curPath, path) - ProcessUtilities.executioner(command) - - command = 'systemctl start cpssh' - ProcessUtilities.executioner(command) - - FirewallUtilities.addRule('tcp', '5678', '0.0.0.0/0') - - newFWRule = FirewallRules(name='terminal', proto='tcp', port='5678', ipAddress='0.0.0.0/0') - newFWRule.save() - - return render(request, 'WebTerminal/WebTerminal.html', {'verifyPath': verifyPath, 'password': password}) - except BaseException as msg: - logging.writeToFile(str(msg)) - return redirect(loadLoginPage) + FirewallUtilities.addRule('tcp', '5678', '0.0.0.0/0') + newFWRule = FirewallRules(name='terminal', proto='tcp', port='5678', ipAddress='0.0.0.0/0') + newFWRule.save() + proc = httpProc(request, 'WebTerminal/WebTerminal.html', + {'verifyPath': verifyPath, 'password': password}) + return proc.render() def restart(request): try: diff --git a/backup/backupManager.py b/backup/backupManager.py index 6d0a93d50..ba5dcd9e8 100755 --- a/backup/backupManager.py +++ b/backup/backupManager.py @@ -4,6 +4,8 @@ import os.path import sys import django +from plogical.httpProc import httpProc + sys.path.append('/usr/local/CyberCP') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") django.setup() @@ -39,43 +41,28 @@ class BackupManager: def loadBackupHome(self, request=None, userID=None, data=None): try: currentACL = ACLManager.loadedACL(userID) - return render(request, 'backup/index.html', currentACL) + proc = httpProc(request, 'backup/index.html', currentACL) + return proc.render() except BaseException as msg: return HttpResponse(str(msg)) def backupSite(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'createBackup') == 0: - return ACLManager.loadError() - - websitesName = ACLManager.findAllSites(currentACL, userID) - return render(request, 'backup/backup.html', {'websiteList': websitesName}) - except BaseException as msg: - return HttpResponse(str(msg)) + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID) + proc = httpProc(request, 'backup/backup.html', {'websiteList': websitesName}, 'createBackup') + return proc.render() def gDrive(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - admin = Administrator.objects.get(pk=userID) - - if ACLManager.currentContextPermission(currentACL, 'createBackup') == 0: - return ACLManager.loadError() - - gDriveAcctsList = [] - - gDriveAccts = admin.gdrive_set.all() - - for items in gDriveAccts: - gDriveAcctsList.append(items.name) - - websitesName = ACLManager.findAllSites(currentACL, userID) - - return render(request, 'backup/googleDrive.html', {'accounts': gDriveAcctsList, 'websites': websitesName}) - except BaseException as msg: - return HttpResponse(str(msg)) + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + gDriveAcctsList = [] + gDriveAccts = admin.gdrive_set.all() + for items in gDriveAccts: + gDriveAcctsList.append(items.name) + websitesName = ACLManager.findAllSites(currentACL, userID) + proc = httpProc(request, 'backup/googleDrive.html', {'accounts': gDriveAcctsList, 'websites': websitesName}, + 'createBackup') + return proc.render() def gDriveSetup(self, userID=None, request=None): try: @@ -356,32 +343,23 @@ class BackupManager: return HttpResponse(json_data) def restoreSite(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) + path = os.path.join("/home", "backup") + if not os.path.exists(path): + proc = httpProc(request, 'backup/restore.html', 'restoreBackup') + return proc.render() + else: + all_files = [] + ext = ".tar.gz" - if ACLManager.currentContextPermission(currentACL, 'restoreBackup') == 0: - return ACLManager.loadError() + command = 'sudo chown -R cyberpanel:cyberpanel ' + path + ACLManager.executeCall(command) - path = os.path.join("/home", "backup") - - if not os.path.exists(path): - return render(request, 'backup/restore.html') - else: - all_files = [] - ext = ".tar.gz" - - command = 'sudo chown -R cyberpanel:cyberpanel ' + path - ACLManager.executeCall(command) - - files = os.listdir(path) - for filename in files: - if filename.endswith(ext): - all_files.append(filename) - - return render(request, 'backup/restore.html', {'backups': all_files}) - - except BaseException as msg: - return HttpResponse(str(msg)) + files = os.listdir(path) + for filename in files: + if filename.endswith(ext): + all_files.append(filename) + proc = httpProc(request, 'backup/restore.html', {'backups': all_files}, 'restoreBackup') + return proc.render() def getCurrentBackups(self, userID=None, data=None): try: @@ -695,16 +673,8 @@ class BackupManager: return HttpResponse(final_json) def backupDestinations(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0: - return ACLManager.loadError() - - return render(request, 'backup/backupDestinations.html', {}) - - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'backup/backupDestinations.html', {}, 'addDeleteDestinations') + return proc.render() def submitDestinationCreation(self, userID=None, data=None): try: @@ -868,25 +838,15 @@ class BackupManager: return HttpResponse(final_json) def scheduleBackup(self, request, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: - return ACLManager.loadError() - - destinations = NormalBackupDests.objects.all() - - dests = [] - - for dest in destinations: - dests.append(dest.name) - - websitesName = ACLManager.findAllSites(currentACL, userID) - - return render(request, 'backup/backupSchedule.html', {'destinations': dests, 'websites': websitesName}) - - except BaseException as msg: - return HttpResponse(str(msg)) + currentACL = ACLManager.loadedACL(userID) + destinations = NormalBackupDests.objects.all() + dests = [] + for dest in destinations: + dests.append(dest.name) + websitesName = ACLManager.findAllSites(currentACL, userID) + proc = httpProc(request, 'backup/backupSchedule.html', {'destinations': dests, 'websites': websitesName}, + 'scheDuleBackups') + return proc.render() def getCurrentBackupSchedules(self, userID=None, data=None): try: @@ -1009,16 +969,8 @@ class BackupManager: return HttpResponse(final_json) def remoteBackups(self, request, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: - return ACLManager.loadError() - - return render(request, 'backup/remoteBackups.html') - - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'backup/remoteBackups.html', 'remoteBackups') + return proc.render() def submitRemoteBackups(self, userID=None, data=None): try: @@ -1371,25 +1323,12 @@ class BackupManager: return HttpResponse(json_data) def backupLogs(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - all_files = [] - - logFiles = BackupJob.objects.all().order_by('-id') - - for logFile in logFiles: - all_files.append(logFile.logFile) - - return render(request, 'backup/backupLogs.html', {'backups': all_files}) - - except BaseException as msg: - return HttpResponse(str(msg)) + all_files = [] + logFiles = BackupJob.objects.all().order_by('-id') + for logFile in logFiles: + all_files.append(logFile.logFile) + proc = httpProc(request, 'backup/backupLogs.html', {'backups': all_files}, 'admin') + return proc.render() def fetchLogs(self, userID=None, data=None): try: diff --git a/backup/static/backup/backup.js b/backup/static/backup/backup.js index 9105a96c5..49980c5f9 100755 --- a/backup/static/backup/backup.js +++ b/backup/static/backup/backup.js @@ -6,6 +6,21 @@ app.controller('backupWebsiteControl', function ($scope, $http, $timeout) { + $(document).ready(function () { + $(".destinationHide").hide(); + $('#create-backup-select').select2(); + }); + + $('#create-backup-select').on('select2:select', function (e) { + var data = e.params.data; + $scope.websiteToBeBacked = data.text; + $(".destinationHide").show(); + getBackupStatus(); + populateCurrentRecords(); + $scope.destination = false; + $scope.runningBackup = true; + }); + $scope.destination = true; $scope.backupButton = true; $scope.backupLoading = true; @@ -43,7 +58,6 @@ app.controller('backupWebsiteControl', function ($scope, $http, $timeout) { }; - function getBackupStatus() { $scope.backupLoadingBottom = false; @@ -111,12 +125,10 @@ app.controller('backupWebsiteControl', function ($scope, $http, $timeout) { }; - $scope.destinationSelection = function () { $scope.backupButton = false; }; - function populateCurrentRecords() { var websiteToBeBacked = $scope.websiteToBeBacked; @@ -152,7 +164,6 @@ app.controller('backupWebsiteControl', function ($scope, $http, $timeout) { }; - $scope.createBackup = function () { var websiteToBeBacked = $scope.websiteToBeBacked; @@ -189,10 +200,8 @@ app.controller('backupWebsiteControl', function ($scope, $http, $timeout) { }; - $scope.deleteBackup = function (id) { - url = "/backup/deleteBackup"; var data = { diff --git a/backup/templates/backup/backup.html b/backup/templates/backup/backup.html index 5d83cb414..76dc4a5bc 100755 --- a/backup/templates/backup/backup.html +++ b/backup/templates/backup/backup.html @@ -29,7 +29,7 @@
- {% for items in websiteList %} {% endfor %} @@ -37,7 +37,7 @@
-
+
+
-
{$databaseWebsite|getwebsitename$}_{$ dbName $}
+
_{$ dbName $}
-
+
-
{$databaseWebsite|getwebsitename$}_{$ dbUsername $}
+
_{$ dbUsername $}
-
+
@@ -62,7 +61,7 @@
-
+
@@ -73,37 +72,13 @@
-
+
- - -
- -
-
-

{% trans "Cannot create database. Error message:" %} {$ errorMessage $}

-
- -
-

{% trans "Database created successfully." %}

-
- - -
-

{% trans "Could not connect to server. Please refresh this page." %}

-
-
- - - -
- - diff --git a/databases/templates/databases/listDataBases.html b/databases/templates/databases/listDataBases.html index 2f8589839..9423ec949 100755 --- a/databases/templates/databases/listDataBases.html +++ b/databases/templates/databases/listDataBases.html @@ -26,7 +26,7 @@
diff --git a/dns/dnsManager.py b/dns/dnsManager.py index acdca57a9..bbb507607 100755 --- a/dns/dnsManager.py +++ b/dns/dnsManager.py @@ -4,10 +4,10 @@ import errno import os.path import sys import django + sys.path.append('/usr/local/CyberCP') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") django.setup() -from django.shortcuts import render from django.http import HttpResponse import json try: @@ -24,6 +24,7 @@ import CloudFlare import re import plogical.CyberCPLogFileWriter as logging from plogical.processUtilities import ProcessUtilities +from plogical.httpProc import httpProc class DNSManager: defaultNameServersPath = '/home/cyberpanel/defaultNameservers' @@ -37,29 +38,23 @@ class DNSManager: self.email = data[0].rstrip('\n') self.key = data[1].rstrip('\n') - def loadDNSHome(self, request = None, userID = None): - try: - admin = Administrator.objects.get(pk=userID) - return render(request, 'dns/index.html', {"type": admin.type}) - except BaseException as msg: - return HttpResponse(str(msg)) + admin = Administrator.objects.get(pk=userID) + template = 'dns/index.html' + proc = httpProc(request, template, {"type": admin.type}, 'createDNSZone') + return proc.render() def createNameserver(self, request = None, userID = None): - try: - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'createNameServer') == 0: - return ACLManager.loadError() + mailUtilities.checkHome() - mailUtilities.checkHome() + if os.path.exists('/home/cyberpanel/powerdns'): + finalData = {"status": 1} + else: + finalData = {"status": 0} - if os.path.exists('/home/cyberpanel/powerdns'): - return render(request, "dns/createNameServer.html", {"status": 1}) - else: - return render(request, "dns/createNameServer.html", {"status": 0}) - - except BaseException as msg: - return HttpResponse(str(msg)) + template = 'dns/createNameServer.html' + proc = httpProc(request, template, finalData, 'createNameServer') + return proc.render() def NSCreation(self, userID = None, data = None): try: @@ -118,17 +113,15 @@ class DNSManager: return HttpResponse(final_json) def createDNSZone(self, request = None, userID = None): - try: - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'createDNSZone') == 0: - return ACLManager.loadError() - if os.path.exists('/home/cyberpanel/powerdns'): - return render(request, 'dns/createDNSZone.html', {"status": 1}) - else: - return render(request, 'dns/createDNSZone.html', {"status": 0}) - except BaseException as msg: - return HttpResponse(str(msg)) + if os.path.exists('/home/cyberpanel/powerdns'): + finalData = {'status': 1} + else: + finalData = {'status': 0} + + template = 'dns/createDNSZone.html' + proc = httpProc(request, template, finalData, 'createDNSZone') + return proc.render() def zoneCreation(self, userID = None, data = None): try: @@ -166,21 +159,17 @@ class DNSManager: return HttpResponse(final_json) def addDeleteDNSRecords(self, request = None, userID = None): - try: + currentACL = ACLManager.loadedACL(userID) - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'addDeleteRecords') == 0: - return ACLManager.loadError() + if not os.path.exists('/home/cyberpanel/powerdns'): + finalData = {"status": 0} + else: + finalData = {"status": 1} - if not os.path.exists('/home/cyberpanel/powerdns'): - return render(request, 'dns/addDeleteDNSRecords.html', {"status": 0}) - - domainsList = ACLManager.findAllDomains(currentACL, userID) - - return render(request, 'dns/addDeleteDNSRecords.html', {"domainsList": domainsList, "status": 1}) - - except BaseException as msg: - return HttpResponse(str(msg)) + finalData['domainsList'] = ACLManager.findAllDomains(currentACL, userID) + template = 'dns/addDeleteDNSRecords.html' + proc = httpProc(request, template, finalData, 'addDeleteRecords') + return proc.render() def getCurrentRecordsForDomain(self, userID = None, data = None): try: @@ -499,22 +488,16 @@ class DNSManager: return HttpResponse(final_json) def deleteDNSZone(self, request = None, userID = None): + currentACL = ACLManager.loadedACL(userID) + if not os.path.exists('/home/cyberpanel/powerdns'): + finalData = {"status": 0} + else: + finalData = {"status": 1} - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'deleteZone') == 0: - return ACLManager.loadError() - - if not os.path.exists('/home/cyberpanel/powerdns'): - return render(request, 'dns/addDeleteDNSRecords.html', {"status": 0}) - - domainsList = ACLManager.findAllDomains(currentACL, userID) - - return render(request, 'dns/deleteDNSZone.html', {"domainsList": domainsList, "status": 1}) - - except BaseException as msg: - return HttpResponse(str(msg)) + finalData['domainsList'] = ACLManager.findAllDomains(currentACL, userID) + template = 'dns/deleteDNSZone.html' + proc = httpProc(request, template, finalData, 'deleteZone') + return proc.render() def submitZoneDeletion(self, userID = None, data = None): try: @@ -549,46 +532,36 @@ class DNSManager: return HttpResponse(final_json) def configureDefaultNameServers(self, request=None, userID=None): + currentACL = ACLManager.loadedACL(userID) - try: - currentACL = ACLManager.loadedACL(userID) + if not os.path.exists('/home/cyberpanel/powerdns'): + data = {"status": 0} + else: + data = {"status": 1} - if currentACL['admin'] == 1: + data['domainsList'] = ACLManager.findAllDomains(currentACL, userID) + if os.path.exists(DNSManager.defaultNameServersPath): + nsData = open(DNSManager.defaultNameServersPath, 'r').readlines() + try: + data['firstNS'] = nsData[0].rstrip('\n') + except: + pass + try: + data['secondNS'] = nsData[1].rstrip('\n') + except: + pass + try: + data['thirdNS'] = nsData[2].rstrip('\n') + except: + pass + try: + data['forthNS'] = nsData[3].rstrip('\n') + except: pass - else: - return ACLManager.loadError() - - if not os.path.exists('/home/cyberpanel/powerdns'): - return render(request, 'dns/addDeleteDNSRecords.html', {"status": 0}) - - data = {} - data['domainsList'] = ACLManager.findAllDomains(currentACL, userID) - data['status'] = 1 - - if os.path.exists(DNSManager.defaultNameServersPath): - nsData = open(DNSManager.defaultNameServersPath, 'r').readlines() - try: - data['firstNS'] = nsData[0].rstrip('\n') - except: - pass - try: - data['secondNS'] = nsData[1].rstrip('\n') - except: - pass - try: - data['thirdNS'] = nsData[2].rstrip('\n') - except: - pass - try: - data['forthNS'] = nsData[3].rstrip('\n') - except: - pass - - return render(request, 'dns/configureDefaultNameServers.html', data) - - except BaseException as msg: - return HttpResponse(str(msg)) + template = 'dns/configureDefaultNameServers.html' + proc = httpProc(request, template, data, 'admin') + return proc.render() def saveNSConfigurations(self, userID = None, data = None): try: @@ -615,7 +588,6 @@ class DNSManager: except: pass - writeToFile = open(DNSManager.defaultNameServersPath, 'w') writeToFile.write(nsContent.rstrip('\n')) writeToFile.close() @@ -631,35 +603,30 @@ class DNSManager: return HttpResponse(final_json) def addDeleteDNSRecordsCloudFlare(self, request = None, userID = None): - try: + currentACL = ACLManager.loadedACL(userID) + if not os.path.exists('/home/cyberpanel/powerdns'): + status = 0 + else: + status = 1 + admin = Administrator.objects.get(pk=userID) - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'addDeleteRecords') == 0: - return ACLManager.loadError() + CloudFlare = 0 - if not os.path.exists('/home/cyberpanel/powerdns'): - return render(request, 'dns/addDeleteDNSRecordsCloudFlare.html', {"status": 0}) + cfPath = '%s%s' % (DNS.CFPath, admin.userName) - admin = Administrator.objects.get(pk=userID) + if os.path.exists(cfPath): + CloudFlare = 1 + domainsList = ACLManager.findAllDomains(currentACL, userID) + self.admin = admin + self.loadCFKeys() + data = {"domainsList": domainsList, "status": status, 'CloudFlare': CloudFlare, 'cfEmail': self.email, + 'cfToken': self.key} + else: + data = {"status": status, 'CloudFlare': CloudFlare} - CloudFlare = 0 - - cfPath = '%s%s' %(DNS.CFPath, admin.userName) - - if os.path.exists(cfPath): - CloudFlare = 1 - domainsList = ACLManager.findAllDomains(currentACL, userID) - - self.admin = admin - self.loadCFKeys() - - return render(request, 'dns/addDeleteDNSRecordsCloudFlare.html', - {"domainsList": domainsList, "status": 1, 'CloudFlare': CloudFlare, 'cfEmail': self.email, 'cfToken': self.key}) - else: - return render(request, 'dns/addDeleteDNSRecordsCloudFlare.html', {"status": 1, 'CloudFlare': CloudFlare}) - - except BaseException as msg: - return HttpResponse(str(msg)) + template = 'dns/addDeleteDNSRecordsCloudFlare.html' + proc = httpProc(request, template, data, 'addDeleteRecords') + return proc.render() def saveCFConfigs(self, userID = None, data = None): try: diff --git a/dockerManager/container.py b/dockerManager/container.py index 65fb3d787..13a600571 100755 --- a/dockerManager/container.py +++ b/dockerManager/container.py @@ -1,11 +1,8 @@ #!/usr/local/CyberCP/bin/python -import os import os.path import sys import django -import mimetypes - sys.path.append('/usr/local/CyberCP') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") django.setup() @@ -25,7 +22,7 @@ import requests from plogical.processUtilities import ProcessUtilities from serverStatus.serverStatusUtil import ServerStatusUtil import threading as multi - +from plogical.httpProc import httpProc # Use default socket to connect class ContainerManager(multi.Thread): @@ -39,16 +36,8 @@ class ContainerManager(multi.Thread): self.data = data def renderDM(self): - - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - return render(self.request, self.templateName, self.data) + proc = httpProc(self.request, self.templateName, self.data, 'admin') + return proc.render() def run(self): try: @@ -91,59 +80,54 @@ class ContainerManager(multi.Thread): logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, str(msg) + ' [404].', 1) def createContainer(self, request=None, userID=None, data=None): + client = docker.from_env() + dockerAPI = docker.APIClient() + + adminNames = ACLManager.loadAllUsers(userID) + tag = request.GET.get('tag') + image = request.GET.get('image') + tag = tag.split(" (")[0] + + if "/" in image: + name = image.split("/")[0] + "." + image.split("/")[1] + else: + name = image + try: - admin = Administrator.objects.get(pk=userID) - if admin.acl.adminStatus != 1: - return ACLManager.loadError() + inspectImage = dockerAPI.inspect_image(image + ":" + tag) + except docker.errors.ImageNotFound: + val = request.session['userID'] + admin = Administrator.objects.get(pk=val) + proc = httpProc(request, 'dockerManager/images.html', {"type": admin.type, + 'image': image, + 'tag': tag}) + return proc.render() - client = docker.from_env() - dockerAPI = docker.APIClient() + envList = {}; + if 'Env' in inspectImage['Config']: + for item in inspectImage['Config']['Env']: + if '=' in item: + splitedItem = item.split('=', 1) + print(splitedItem) + envList[splitedItem[0]] = splitedItem[1] + else: + envList[item] = "" - adminNames = ACLManager.loadAllUsers(userID) - tag = request.GET.get('tag') - image = request.GET.get('image') - tag = tag.split(" (")[0] + portConfig = {}; + if 'ExposedPorts' in inspectImage['Config']: + for item in inspectImage['Config']['ExposedPorts']: + portDef = item.split('/') + portConfig[portDef[0]] = portDef[1] - if "/" in image: - name = image.split("/")[0] + "." + image.split("/")[1] - else: - name = image + if image is None or image is '' or tag is None or tag is '': + return redirect(loadImages) - try: - inspectImage = dockerAPI.inspect_image(image + ":" + tag) - except docker.errors.ImageNotFound: - val = request.session['userID'] - admin = Administrator.objects.get(pk=val) - return render(request, 'dockerManager/images.html', {"type": admin.type, - 'image': image, - 'tag': tag}) + Data = {"ownerList": adminNames, "image": image, "name": name, "tag": tag, "portConfig": portConfig, + "envList": envList} - envList = {}; - if 'Env' in inspectImage['Config']: - for item in inspectImage['Config']['Env']: - if '=' in item: - splitedItem = item.split('=', 1) - print(splitedItem) - envList[splitedItem[0]] = splitedItem[1] - else: - envList[item] = "" - - portConfig = {}; - if 'ExposedPorts' in inspectImage['Config']: - for item in inspectImage['Config']['ExposedPorts']: - portDef = item.split('/') - portConfig[portDef[0]] = portDef[1] - - if image is None or image is '' or tag is None or tag is '': - return redirect(loadImages) - - Data = {"ownerList": adminNames, "image": image, "name": name, "tag": tag, "portConfig": portConfig, - "envList": envList} - - return render(request, 'dockerManager/runContainer.html', Data) - - except BaseException as msg: - return HttpResponse(str(msg)) + template = 'dockerManager/runContainer.html' + proc = httpProc(request, template, Data, 'admin') + return proc.render() def loadContainerHome(self, request=None, userID=None, data=None): name = self.name @@ -196,51 +180,52 @@ class ContainerManager(multi.Thread): data['memoryUsage'] = 0 data['cpuUsage'] = 0 - return render(request, 'dockerManager/viewContainer.html', data) + template = 'dockerManager/viewContainer.html' + proc = httpProc(request, template, data, 'admin') + return proc.render() def listContainers(self, request=None, userID=None, data=None): - try: - client = docker.from_env() - dockerAPI = docker.APIClient() + client = docker.from_env() + dockerAPI = docker.APIClient() - currentACL = ACLManager.loadedACL(userID) - containers = ACLManager.findAllContainers(currentACL, userID) + currentACL = ACLManager.loadedACL(userID) + containers = ACLManager.findAllContainers(currentACL, userID) - allContainers = client.containers.list() - containersList = [] - showUnlistedContainer = True + allContainers = client.containers.list() + containersList = [] + showUnlistedContainer = True - # TODO: Add condition to show unlisted Containers only if user has admin level access + # TODO: Add condition to show unlisted Containers only if user has admin level access - unlistedContainers = [] - for container in allContainers: - if container.name not in containers: - unlistedContainers.append(container) + unlistedContainers = [] + for container in allContainers: + if container.name not in containers: + unlistedContainers.append(container) - if not unlistedContainers: - showUnlistedContainer = False + if not unlistedContainers: + showUnlistedContainer = False - adminNames = ACLManager.loadAllUsers(userID) + adminNames = ACLManager.loadAllUsers(userID) - pages = float(len(containers)) / float(10) - pagination = [] + pages = float(len(containers)) / float(10) + pagination = [] - if pages <= 1.0: - pages = 1 - pagination.append('
  • ') - else: - pages = ceil(pages) - finalPages = int(pages) + 1 + if pages <= 1.0: + pages = 1 + pagination.append('
  • ') + else: + pages = ceil(pages) + finalPages = int(pages) + 1 - for i in range(1, finalPages): - pagination.append('
  • ' + str(i) + '
  • ') + for i in range(1, finalPages): + pagination.append('
  • ' + str(i) + '
  • ') - return render(request, 'dockerManager/listContainers.html', {"pagination": pagination, - "unlistedContainers": unlistedContainers, - "adminNames": adminNames, - "showUnlistedContainer": showUnlistedContainer}) - except BaseException as msg: - return HttpResponse(str(msg)) + template = 'dockerManager/listContainers.html' + proc = httpProc(request, template, {"pagination": pagination, + "unlistedContainers": unlistedContainers, + "adminNames": adminNames, + "showUnlistedContainer": showUnlistedContainer}, 'admin') + return proc.render() def getContainerLogs(self, userID=None, data=None): try: @@ -774,7 +759,9 @@ class ContainerManager(multi.Thread): except: continue - return render(request, 'dockerManager/images.html', {"images": images, "test": ''}) + template = 'dockerManager/images.html' + proc = httpProc(request, template, {"images": images, "test": ''}, 'admin') + return proc.render() except BaseException as msg: return HttpResponse(str(msg)) @@ -808,7 +795,9 @@ class ContainerManager(multi.Thread): except: continue - return render(request, 'dockerManager/manageImages.html', {"images": images}) + template = 'dockerManager/manageImages.html' + proc = httpProc(request, template, {"images": images}, 'admin') + return proc.render() except BaseException as msg: return HttpResponse(str(msg)) diff --git a/dockerManager/views.py b/dockerManager/views.py index 976b27206..2e58b9f33 100755 --- a/dockerManager/views.py +++ b/dockerManager/views.py @@ -1,9 +1,10 @@ # -*- coding: utf-8 -*- -from django.shortcuts import render, redirect, HttpResponse +from django.shortcuts import redirect, HttpResponse from loginSystem.models import Administrator from loginSystem.views import loadLoginPage +from plogical.httpProc import httpProc from .container import ContainerManager from .decorators import preDockerRun from plogical.acl import ACLManager @@ -25,15 +26,11 @@ def dockerPermission(request, userID, context): @preDockerRun def loadDockerHome(request): - try: - userID = request.session['userID'] - perm = dockerPermission(request, userID, 'loadDockerHome') - if perm: return perm - - admin = Administrator.objects.get(pk=userID) - return render(request,'dockerManager/index.html',{"type":admin.type}) - except KeyError: - return redirect(loadLoginPage) + userID = request.session['userID'] + admin = Administrator.objects.get(pk=userID) + template = 'dockerManager/index.html' + proc = httpProc(request, template, {"type": admin.type}, 'admin') + return proc.render() def installDocker(request): try: diff --git a/emailMarketing/emailMarketingManager.py b/emailMarketing/emailMarketingManager.py index ef2061be9..beb4bef6c 100755 --- a/emailMarketing/emailMarketingManager.py +++ b/emailMarketing/emailMarketingManager.py @@ -4,6 +4,7 @@ from loginSystem.views import loadLoginPage import json from random import randint import time +from plogical.httpProc import httpProc from .models import EmailMarketing, EmailLists, EmailsInList, EmailJobs from websiteFunctions.models import Websites from .emailMarketing import emailMarketing as EM @@ -12,7 +13,6 @@ import smtplib from .models import SMTPHosts, EmailTemplate from loginSystem.models import Administrator from .emACL import emACL -from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging class EmailMarketingManager: @@ -21,18 +21,8 @@ class EmailMarketingManager: self.domain = domain def emailMarketing(self): - try: - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - return render(self.request, 'emailMarketing/emailMarketing.html') - except KeyError as msg: - return redirect(loadLoginPage) + proc = httpProc(self.request, 'emailMarketing/emailMarketing.html', None, 'admin') + return proc.render() def fetchUsers(self): try: @@ -123,7 +113,8 @@ class EmailMarketingManager: if emACL.checkIfEMEnabled(admin.userName) == 0: return ACLManager.loadError() - return render(self.request, 'emailMarketing/createEmailList.html', {'domain': self.domain}) + proc = httpProc(self.request, 'emailMarketing/createEmailList.html', {'domain': self.domain}) + return proc.render() except KeyError as msg: return redirect(loadLoginPage) @@ -168,6 +159,7 @@ class EmailMarketingManager: userID = self.request.session['userID'] currentACL = ACLManager.loadedACL(userID) admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: pass else: @@ -178,12 +170,15 @@ class EmailMarketingManager: listNames = emACL.getEmailsLists(self.domain) - return render(self.request, 'emailMarketing/manageLists.html', {'listNames': listNames, 'domain': self.domain}) + proc = httpProc(self.request, 'emailMarketing/manageLists.html', {'listNames': listNames, 'domain': self.domain}) + return proc.render() + except KeyError as msg: return redirect(loadLoginPage) def configureVerify(self): try: + userID = self.request.session['userID'] currentACL = ACLManager.loadedACL(userID) admin = Administrator.objects.get(pk=userID) @@ -196,7 +191,10 @@ class EmailMarketingManager: if emACL.checkIfEMEnabled(admin.userName) == 0: return ACLManager.loadError() - return render(self.request, 'emailMarketing/configureVerify.html', {'domain': self.domain}) + proc = httpProc(self.request, 'emailMarketing/configureVerify.html', + {'domain': self.domain}) + return proc.render() + except KeyError as msg: return redirect(loadLoginPage) @@ -490,7 +488,10 @@ class EmailMarketingManager: for items in emailLists: listNames.append(items.listName) - return render(self.request, 'emailMarketing/manageSMTPHosts.html', {'listNames': listNames, 'domain': self.domain}) + + proc = httpProc(self.request, 'emailMarketing/manageSMTPHosts.html', + {'listNames': listNames, 'domain': self.domain}) + return proc.render() except KeyError as msg: return redirect(loadLoginPage) @@ -657,7 +658,9 @@ class EmailMarketingManager: if emACL.checkIfEMEnabled(admin.userName) == 0: return ACLManager.loadErrorJson() - return render(self.request, 'emailMarketing/composeMessages.html') + proc = httpProc(self.request, 'emailMarketing/composeMessages.html', + None) + return proc.render() except KeyError as msg: return redirect(loadLoginPage) @@ -709,7 +712,11 @@ class EmailMarketingManager: Data['templateNames'] = templateNames Data['hostNames'] = hostNames Data['listNames'] = listNames - return render(self.request, 'emailMarketing/sendEmails.html', Data) + + proc = httpProc(self.request, 'emailMarketing/sendEmails.html', + Data) + return proc.render() + except KeyError as msg: return redirect(loadLoginPage) diff --git a/emailPremium/views.py b/emailPremium/views.py index 62f224844..47299efe9 100755 --- a/emailPremium/views.py +++ b/emailPremium/views.py @@ -1,11 +1,8 @@ # -*- coding: utf-8 -*- - -from django.shortcuts import render,redirect +from django.shortcuts import redirect from django.http import HttpResponse from mailServer.models import Domains, EUsers -# Create your views here. -from loginSystem.models import Administrator from websiteFunctions.models import Websites from loginSystem.views import loadLoginPage import plogical.CyberCPLogFileWriter as logging @@ -13,31 +10,19 @@ import json from .models import DomainLimits, EmailLimits from math import ceil from postfixSenderPolicy.client import cacheClient -import _thread from plogical.mailUtilities import mailUtilities from plogical.virtualHostUtilities import virtualHostUtilities from random import randint from plogical.acl import ACLManager from plogical.processUtilities import ProcessUtilities - -# Create your views here. +from plogical.httpProc import httpProc ## Email Policy Server def emailPolicyServer(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - return render(request, 'emailPremium/policyServer.html') - - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'emailPremium/policyServer.html', + None, 'admin') + return proc.render() def fetchPolicyServerStatus(request): try: @@ -129,57 +114,43 @@ def savePolicyServerStatus(request): ## Email Policy Server configs def listDomains(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() + websites = DomainLimits.objects.all() - try: - websites = DomainLimits.objects.all() + ## Check if Policy Server is installed. - ## Check if Policy Server is installed. + command = 'sudo cat /etc/postfix/main.cf' + output = ProcessUtilities.outputExecutioner(command).split('\n') - command = 'sudo cat /etc/postfix/main.cf' - output = ProcessUtilities.outputExecutioner(command).split('\n') + installCheck = 0 - installCheck = 0 + for items in output: + if items.find('check_policy_service unix:/var/log/policyServerSocket') > -1: + installCheck = 1 + break - for items in output: - if items.find('check_policy_service unix:/var/log/policyServerSocket') > -1: - installCheck = 1 - break + if installCheck == 0: + proc = httpProc(request, 'emailPremium/listDomains.html', {"installCheck": installCheck}, 'admin') + return proc.render() - if installCheck == 0: - return render(request, 'emailPremium/listDomains.html', {"installCheck": installCheck}) + ### - ### + pages = float(len(websites)) / float(10) + pagination = [] - pages = float(len(websites)) / float(10) - pagination = [] + if pages <= 1.0: + pages = 1 + pagination.append('
  • ') + else: + pages = ceil(pages) + finalPages = int(pages) + 1 - if pages <= 1.0: - pages = 1 - pagination.append('
  • ') - else: - pages = ceil(pages) - finalPages = int(pages) + 1 + for i in range(1, finalPages): + pagination.append('
  • ' + str(i) + '
  • ') - for i in range(1, finalPages): - pagination.append('
  • ' + str(i) + '
  • ') - - - return render(request,'emailPremium/listDomains.html',{"pagination":pagination, "installCheck": installCheck}) - - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse("See CyberCP main log file.") - - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'emailPremium/listDomains.html', + {"pagination": pagination, "installCheck": installCheck}, 'admin') + return proc.render() def getFurtherDomains(request): try: @@ -304,57 +275,47 @@ def enableDisableEmailLimits(request): return HttpResponse(json_data) def emailLimits(request,domain): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + if Websites.objects.filter(domain=domain).exists(): + website = Websites.objects.get(domain=domain) + domainEmail = Domains.objects.get(domainOwner=website) + domainLimits = DomainLimits.objects.get(domain=domainEmail) - if currentACL['admin'] == 1: - pass + Data = {} + Data['domain'] = domain + Data['monthlyLimit'] = domainLimits.monthlyLimit + Data['monthlyUsed'] = domainLimits.monthlyUsed + Data['emailAccounts'] = domainEmail.eusers_set.count() + + if domainLimits.limitStatus == 1: + Data['limitsOn'] = 1 + Data['limitsOff'] = 0 else: - return ACLManager.loadError() + Data['limitsOn'] = 0 + Data['limitsOff'] = 1 + ## Pagination for emails - if Websites.objects.filter(domain=domain).exists(): - website = Websites.objects.get(domain=domain) - domainEmail = Domains.objects.get(domainOwner=website) - domainLimits = DomainLimits.objects.get(domain=domainEmail) + pages = float(Data['emailAccounts']) / float(10) + pagination = [] - Data = {} - Data['domain'] = domain - Data['monthlyLimit'] = domainLimits.monthlyLimit - Data['monthlyUsed'] = domainLimits.monthlyUsed - Data['emailAccounts'] = domainEmail.eusers_set.count() - - if domainLimits.limitStatus == 1: - Data['limitsOn'] = 1 - Data['limitsOff'] = 0 - else: - Data['limitsOn'] = 0 - Data['limitsOff'] = 1 - - ## Pagination for emails - - - pages = float(Data['emailAccounts']) / float(10) - pagination = [] - - if pages <= 1.0: - pages = 1 - pagination.append('
  • ') - else: - pages = ceil(pages) - finalPages = int(pages) + 1 - - for i in range(1, finalPages): - pagination.append('
  • ' + str(i) + '
  • ') - - Data['pagination'] = pagination - - return render(request, 'emailPremium/emailLimits.html', Data) + if pages <= 1.0: + pages = 1 + pagination.append('
  • ') else: - return render(request, 'emailPremium/emailLimits.html', {"error":1,"domain": "This domain does not exists"}) - except KeyError: - return redirect(loadLoginPage) + pages = ceil(pages) + finalPages = int(pages) + 1 + + for i in range(1, finalPages): + pagination.append('
  • ' + str(i) + '
  • ') + + Data['pagination'] = pagination + + proc = httpProc(request, 'emailPremium/emailLimits.html', Data, 'admin') + return proc.render() + else: + proc = httpProc(request, 'emailPremium/emailLimits.html', {"error": 1, "domain": "This domain does not exists"}, + 'admin') + return proc.render() def changeDomainLimit(request): try: @@ -495,39 +456,29 @@ def enableDisableIndividualEmailLimits(request): return HttpResponse(json_data) def emailPage(request, emailAddress): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + Data = {} + Data['emailAddress'] = emailAddress - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() + email = EUsers.objects.get(email=emailAddress) + logEntries = email.emaillogs_set.all().count() - Data = {} - Data['emailAddress'] = emailAddress + pages = float(logEntries) / float(10) + pagination = [] - email = EUsers.objects.get(email=emailAddress) - logEntries = email.emaillogs_set.all().count() + if pages <= 1.0: + pages = 1 + pagination.append('
  • ') + else: + pages = ceil(pages) + finalPages = int(pages) + 1 - pages = float(logEntries) / float(10) - pagination = [] + for i in range(1, finalPages): + pagination.append('
  • ' + str(i) + '
  • ') - if pages <= 1.0: - pages = 1 - pagination.append('
  • ') - else: - pages = ceil(pages) - finalPages = int(pages) + 1 + Data['pagination'] = pagination - for i in range(1, finalPages): - pagination.append('
  • ' + str(i) + '
  • ') - - Data['pagination'] = pagination - - return render(request, 'emailPremium/emailPage.html', Data) - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'emailPremium/emailPage.html', Data, 'admin') + return proc.render() def getEmailStats(request): try: @@ -771,24 +722,14 @@ def flushEmailLogs(request): ### SpamAssassin def spamAssassinHome(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + checkIfSpamAssassinInstalled = 0 - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() + if mailUtilities.checkIfSpamAssassinInstalled() == 1: + checkIfSpamAssassinInstalled = 1 - checkIfSpamAssassinInstalled = 0 - - if mailUtilities.checkIfSpamAssassinInstalled() == 1: - checkIfSpamAssassinInstalled = 1 - - return render(request, 'emailPremium/SpamAssassin.html',{'checkIfSpamAssassinInstalled': checkIfSpamAssassinInstalled}) - - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'emailPremium/SpamAssassin.html', + {'checkIfSpamAssassinInstalled': checkIfSpamAssassinInstalled}, 'admin') + return proc.render() def installSpamAssassin(request): try: @@ -951,9 +892,6 @@ def fetchSpamAssassinSettings(request): final_dic = {'fetchStatus': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json) - - - return render(request,'managePHP/editPHPConfig.html') except KeyError: return redirect(loadLoginPage) @@ -1028,19 +966,9 @@ def saveSpamAssassinConfigurations(request): return HttpResponse(json_data) def mailQueue(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - return render(request, 'emailPremium/mailQueue.html') - - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'emailPremium/mailQueue.html', + None, 'admin') + return proc.render() def fetchMailQueue(request): try: @@ -1176,29 +1104,19 @@ def delete(request): ## MailScanner def MailScanner(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + checkIfMailScannerInstalled = 0 - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] - checkIfMailScannerInstalled = 0 + if mailUtilities.checkIfMailScannerInstalled() == 1: + checkIfMailScannerInstalled = 1 - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - - if mailUtilities.checkIfMailScannerInstalled() == 1: - checkIfMailScannerInstalled = 1 - - return render(request, 'emailPremium/MailScanner.html',{'checkIfMailScannerInstalled': checkIfMailScannerInstalled, 'ipAddress': ipAddress}) - - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'emailPremium/MailScanner.html', + {'checkIfMailScannerInstalled': checkIfMailScannerInstalled, 'ipAddress': ipAddress}, 'admin') + return proc.render() def installMailScanner(request): try: diff --git a/filemanager/filemanager.py b/filemanager/filemanager.py index e347a6ca8..9a6cc3046 100755 --- a/filemanager/filemanager.py +++ b/filemanager/filemanager.py @@ -546,12 +546,18 @@ class FileManager: if self.data['fileName'].find(self.data['home']) == -1 or self.data['fileName'].find('..') > -1: return self.ajaxPre(0, 'Not allowed to move in this path, please choose location inside home!') + command = 'stat -c "%%a" %s' % (self.returnPathEnclosed(self.data['fileName'])) + currentMode = ProcessUtilities.outputExecutioner(command).strip('\n') + command = 'mv ' + tempPath + ' ' + self.returnPathEnclosed(self.data['fileName']) ProcessUtilities.executioner(command) command = 'chown %s:%s %s' % (website.externalApp, website.externalApp, self.data['fileName']) ProcessUtilities.executioner(command) + command = 'chmod %s %s' % (currentMode, self.returnPathEnclosed(self.data['fileName'])) + ProcessUtilities.executioner(command) + self.changeOwner(self.data['fileName']) json_data = json.dumps(finalData) @@ -711,6 +717,9 @@ class FileManager: else: groupName = 'nogroup' + command = 'chown %s:%s /home/%s' % (website.externalApp, website.externalApp, domainName) + ProcessUtilities.popenExecutioner(command) + command = 'chown -R %s:%s /home/%s/public_html/*' % (externalApp, externalApp, domainName) ProcessUtilities.popenExecutioner(command) diff --git a/firewall/firewallManager.py b/firewall/firewallManager.py index 7c51b7213..355a8e435 100755 --- a/firewall/firewallManager.py +++ b/firewall/firewallManager.py @@ -3,6 +3,9 @@ import os import os.path import sys import django + +from plogical.httpProc import httpProc + sys.path.append('/usr/local/CyberCP') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") django.setup() @@ -31,30 +34,14 @@ class FirewallManager: self.request = request def securityHome(self, request = None, userID = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - return render(request, 'firewall/index.html') - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'firewall/index.html', + None, 'admin') + return proc.render() def firewallHome(self, request = None, userID = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - return render(request, 'firewall/firewall.html') - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'firewall/firewall.html', + None, 'admin') + return proc.render() def getCurrentRules(self, userID = None): try: @@ -265,17 +252,9 @@ class FirewallManager: return HttpResponse(final_json) def secureSSH(self, request = None, userID = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - return render(request, 'firewall/secureSSH.html') - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'firewall/secureSSH.html', + None, 'admin') + return proc.render() def getSSHConfigs(self, userID = None, data = None): try: @@ -487,34 +466,26 @@ class FirewallManager: return HttpResponse(final_json) def loadModSecurityHome(self, request = None, userID = None): - try: - currentACL = ACLManager.loadedACL(userID) + if ProcessUtilities.decideServer() == ProcessUtilities.OLS: + OLS = 1 + confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() + command = "sudo cat " + confPath + httpdConfig = ProcessUtilities.outputExecutioner(command).splitlines() - if ProcessUtilities.decideServer() == ProcessUtilities.OLS: - OLS = 1 - confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") + modSecInstalled = 0 - command = "sudo cat " + confPath - httpdConfig = ProcessUtilities.outputExecutioner(command).splitlines() + for items in httpdConfig: + if items.find('module mod_security') > -1: + modSecInstalled = 1 + break + else: + OLS = 0 + modSecInstalled = 1 - modSecInstalled = 0 - - for items in httpdConfig: - if items.find('module mod_security') > -1: - modSecInstalled = 1 - break - else: - OLS = 0 - modSecInstalled = 1 - - return render(request, 'firewall/modSecurity.html', {'modSecInstalled': modSecInstalled, 'OLS': OLS}) - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'firewall/modSecurity.html', + {'modSecInstalled': modSecInstalled, 'OLS': OLS}, 'admin') + return proc.render() def installModSec(self, userID = None, data = None): try: @@ -870,34 +841,24 @@ class FirewallManager: return HttpResponse(json_data) def modSecRules(self, request = None, userID = None): - try: + if ProcessUtilities.decideServer() == ProcessUtilities.OLS: + confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") - currentACL = ACLManager.loadedACL(userID) + command = "sudo cat " + confPath + httpdConfig = ProcessUtilities.outputExecutioner(command).split('\n') - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() + modSecInstalled = 0 - if ProcessUtilities.decideServer() == ProcessUtilities.OLS: - confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") + for items in httpdConfig: + if items.find('module mod_security') > -1: + modSecInstalled = 1 + break + else: + modSecInstalled = 1 - command = "sudo cat " + confPath - httpdConfig = ProcessUtilities.outputExecutioner(command).split('\n') - - modSecInstalled = 0 - - for items in httpdConfig: - if items.find('module mod_security') > -1: - modSecInstalled = 1 - break - else: - modSecInstalled = 1 - - return render(request, 'firewall/modSecurityRules.html', {'modSecInstalled': modSecInstalled}) - - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'firewall/modSecurityRules.html', + {'modSecInstalled': modSecInstalled}, 'admin') + return proc.render() def fetchModSecRules(self, userID = None, data = None): try: @@ -994,35 +955,25 @@ class FirewallManager: return HttpResponse(json_data) def modSecRulesPacks(self, request = None, userID = None): - try: + if ProcessUtilities.decideServer() == ProcessUtilities.OLS: - currentACL = ACLManager.loadedACL(userID) + confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() + command = "sudo cat " + confPath + httpdConfig = ProcessUtilities.outputExecutioner(command).split('\n') - if ProcessUtilities.decideServer() == ProcessUtilities.OLS: + modSecInstalled = 0 - confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") + for items in httpdConfig: + if items.find('module mod_security') > -1: + modSecInstalled = 1 + break + else: + modSecInstalled = 1 - command = "sudo cat " + confPath - httpdConfig = ProcessUtilities.outputExecutioner(command).split('\n') - - modSecInstalled = 0 - - for items in httpdConfig: - if items.find('module mod_security') > -1: - modSecInstalled = 1 - break - else: - modSecInstalled = 1 - - return render(request, 'firewall/modSecurityRulesPacks.html', {'modSecInstalled': modSecInstalled}) - - except BaseException as msg: - return HttpResponse(msg) + proc = httpProc(request, 'firewall/modSecurityRulesPacks.html', + {'modSecInstalled': modSecInstalled}, 'admin') + return proc.render() def getOWASPAndComodoStatus(self, userID = None, data = None): try: @@ -1299,26 +1250,18 @@ class FirewallManager: return HttpResponse(json_data) def csf(self): + csfInstalled = 1 try: - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - csfInstalled = 1 - try: - command = 'csf -h' - output = ProcessUtilities.outputExecutioner(command) - if output.find("command not found") > -1: - csfInstalled = 0 - except subprocess.CalledProcessError: + command = 'csf -h' + output = ProcessUtilities.outputExecutioner(command) + if output.find("command not found") > -1: csfInstalled = 0 - return render(self.request,'firewall/csf.html', {'csfInstalled' : csfInstalled}) - except BaseException as msg: - return HttpResponse(str(msg)) + except subprocess.CalledProcessError: + csfInstalled = 0 + + proc = httpProc(self.request, 'firewall/csf.html', + {'csfInstalled': csfInstalled}, 'admin') + return proc.render() def installCSF(self): try: @@ -1548,45 +1491,35 @@ class FirewallManager: return HttpResponse(final_json) def imunify(self): - try: - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() + fullAddress = '%s:%s' % (ipAddress, ProcessUtilities.fetchCurrentPort()) - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] + data = {} + data['ipAddress'] = fullAddress - fullAddress = '%s:%s' % (ipAddress, ProcessUtilities.fetchCurrentPort()) + data['CL'] = 1 - data = {} - data['ipAddress'] = fullAddress + if os.path.exists(FirewallManager.imunifyPath): + data['imunify'] = 1 + else: + data['imunify'] = 0 - if os.path.exists(FirewallManager.CLPath): - data['CL'] = 1 - else: - data['CL'] = 0 - - if os.path.exists(FirewallManager.imunifyPath): - data['imunify'] = 1 - else: - data['imunify'] = 0 - - if data['CL'] == 0: - return render(self.request, 'firewall/notAvailable.html', data) - elif data['imunify'] == 0: - return render(self.request, 'firewall/notAvailable.html', data) - else: - return render(self.request, 'firewall/imunify.html', data) - - - except BaseException as msg: - return HttpResponse(str(msg)) + if data['CL'] == 0: + proc = httpProc(self.request, 'firewall/notAvailable.html', + data, 'admin') + return proc.render() + elif data['imunify'] == 0: + proc = httpProc(self.request, 'firewall/notAvailable.html', + data, 'admin') + return proc.render() + else: + proc = httpProc(self.request, 'firewall/imunify.html', + data, 'admin') + return proc.render() def submitinstallImunify(self): try: @@ -1615,40 +1548,29 @@ class FirewallManager: logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, str(msg) + ' [404].', 1) def imunifyAV(self): - try: - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() + fullAddress = '%s:%s' % (ipAddress, ProcessUtilities.fetchCurrentPort()) - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] + data = {} + data['ipAddress'] = fullAddress - fullAddress = '%s:%s' % (ipAddress, ProcessUtilities.fetchCurrentPort()) + if os.path.exists(FirewallManager.imunifyAVPath): + data['imunify'] = 1 + else: + data['imunify'] = 0 - data = {} - data['ipAddress'] = fullAddress - - - - if os.path.exists(FirewallManager.imunifyAVPath): - data['imunify'] = 1 - else: - data['imunify'] = 0 - - if data['imunify'] == 0: - return render(self.request, 'firewall/notAvailableAV.html', data) - else: - return render(self.request, 'firewall/imunifyAV.html', data) - - - except BaseException as msg: - return HttpResponse(str(msg)) + if data['imunify'] == 0: + proc = httpProc(self.request, 'firewall/notAvailableAV.html', + data, 'admin') + return proc.render() + else: + proc = httpProc(self.request, 'firewall/imunifyAV.html', + data, 'admin') + return proc.render() def submitinstallImunifyAV(self): try: diff --git a/firewall/templates/firewall/imunify.html b/firewall/templates/firewall/imunify.html index d599ed09b..02e663ad2 100755 --- a/firewall/templates/firewall/imunify.html +++ b/firewall/templates/firewall/imunify.html @@ -27,7 +27,7 @@

    {% trans "Imunify is now integrated via their new API. You can manage Imunify by clicking below. You can use your server root credentials to access Imunify." %}


    - + diff --git a/ftp/ftpManager.py b/ftp/ftpManager.py index 3812d57a9..2eda896ed 100755 --- a/ftp/ftpManager.py +++ b/ftp/ftpManager.py @@ -2,11 +2,14 @@ import os.path import sys import django + +from plogical.httpProc import httpProc + sys.path.append('/usr/local/CyberCP') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") django.setup() import json -from django.shortcuts import render,redirect +from django.shortcuts import redirect from django.http import HttpResponse try: from .models import Users @@ -32,32 +35,26 @@ class FTPManager: self.extraArgs = extraArgs def loadFTPHome(self): - try: - val = self.request.session['userID'] - return render(self.request, 'ftp/index.html') - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(self.request, 'ftp/index.html', + None, 'createFTPAccount') + return proc.render() def createFTPAccount(self): - try: - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'createFTPAccount') == 0: - return ACLManager.loadError() + admin = Administrator.objects.get(pk=userID) - admin = Administrator.objects.get(pk=userID) + if not os.path.exists('/home/cyberpanel/pureftpd'): + proc = httpProc(self.request, 'ftp/createFTPAccount.html', + {"status": 0}, 'createFTPAccount') + return proc.render() - if not os.path.exists('/home/cyberpanel/pureftpd'): - return render(self.request, "ftp/createFTPAccount.html", {"status": 0}) + websitesName = ACLManager.findAllSites(currentACL, userID) - websitesName = ACLManager.findAllSites(currentACL, userID) - - return render(self.request, 'ftp/createFTPAccount.html', - {'websiteList': websitesName, 'admin': admin.userName, "status": 1}) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse(str(msg)) + proc = httpProc(self.request, 'ftp/createFTPAccount.html', + {'websiteList': websitesName, 'OwnerFTP': admin.userName, "status": 1}, 'createFTPAccount') + return proc.render() def submitFTPCreation(self): try: @@ -114,23 +111,19 @@ class FTPManager: return HttpResponse(json_data) def deleteFTPAccount(self): - try: + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + if not os.path.exists('/home/cyberpanel/pureftpd'): + proc = httpProc(self.request, 'ftp/deleteFTPAccount.html', + {"status": 0}, 'deleteFTPAccount') + return proc.render() - if ACLManager.currentContextPermission(currentACL, 'deleteFTPAccount') == 0: - return ACLManager.loadError() + websitesName = ACLManager.findAllSites(currentACL, userID) - if not os.path.exists('/home/cyberpanel/pureftpd'): - return render(self.request, "ftp/deleteFTPAccount.html", {"status": 0}) - - websitesName = ACLManager.findAllSites(currentACL, userID) - - return render(self.request, 'ftp/deleteFTPAccount.html', {'websiteList': websitesName, "status": 1}) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse(str(msg)) + proc = httpProc(self.request, 'ftp/deleteFTPAccount.html', + {'websiteList': websitesName, "status": 1}, 'deleteFTPAccount') + return proc.render() def fetchFTPAccounts(self): try: @@ -204,22 +197,18 @@ class FTPManager: return HttpResponse(json_data) def listFTPAccounts(self): - try: - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'listFTPAccounts') == 0: - return ACLManager.loadError() + if not os.path.exists('/home/cyberpanel/pureftpd'): + proc = httpProc(self.request, 'ftp/listFTPAccounts.html', + {"status": 0}, 'listFTPAccounts') + return proc.render() - if not os.path.exists('/home/cyberpanel/pureftpd'): - return render(self.request, "ftp/listFTPAccounts.html", {"status": 0}) - - websitesName = ACLManager.findAllSites(currentACL, userID) - - return render(self.request, 'ftp/listFTPAccounts.html', {'websiteList': websitesName, "status": 1}) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse(str(msg)) + websitesName = ACLManager.findAllSites(currentACL, userID) + proc = httpProc(self.request, 'ftp/listFTPAccounts.html', + {'websiteList': websitesName, "status": 1}, 'listFTPAccounts') + return proc.render() def getAllFTPAccounts(self): try: diff --git a/ftp/static/ftp/ftp.js b/ftp/static/ftp/ftp.js index a80377e6b..113845c8f 100755 --- a/ftp/static/ftp/ftp.js +++ b/ftp/static/ftp/ftp.js @@ -6,22 +6,22 @@ /* Java script code to create account */ app.controller('createFTPAccount', function ($scope, $http) { + + + $(document).ready(function () { + $( ".ftpDetails" ).hide(); + $( ".ftpPasswordView" ).hide(); + $('.create-ftp-acct-select').select2(); + }); + + $('.create-ftp-acct-select').on('select2:select', function (e) { + var data = e.params.data; + $scope.ftpDomain = data.text; + $( ".ftpDetails" ).show(); + + }); + $scope.ftpLoading = true; - $scope.ftpDetails = true; - $scope.canNotCreate = true; - $scope.successfullyCreated = true; - $scope.couldNotConnect = true; - - $scope.showFTPDetails = function () { - - $scope.ftpLoading = true; - $scope.ftpDetails = false; - $scope.canNotCreate = true; - $scope.successfullyCreated = true; - $scope.couldNotConnect = true; - - - }; $scope.createFTPAccount = function () { @@ -62,37 +62,35 @@ app.controller('createFTPAccount', function ($scope, $http) { function ListInitialDatas(response) { - if (response.data.creatFTPStatus == 1) { - + if (response.data.creatFTPStatus === 1) { $scope.ftpLoading = true; - $scope.ftpDetails = false; - $scope.canNotCreate = true; - $scope.successfullyCreated = false; - $scope.couldNotConnect = true; + new PNotify({ + title: 'Success!', + text: 'FTP account successfully created.', + type: 'success' + }); } else { $scope.ftpLoading = true; - $scope.ftpDetails = false; - $scope.canNotCreate = false; - $scope.successfullyCreated = true; - $scope.couldNotConnect = true; - - $scope.errorMessage = response.data.error_message; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); } - } - function cantLoadInitialDatas(response) { $scope.ftpLoading = true; - $scope.ftpDetails = false; - $scope.canNotCreate = true; - $scope.successfullyCreated = true; - $scope.couldNotConnect = false; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); } @@ -109,15 +107,13 @@ app.controller('createFTPAccount', function ($scope, $http) { /// - $scope.generatedPasswordView = true; - $scope.generatePassword = function () { - $scope.generatedPasswordView = false; + $( ".ftpPasswordView" ).show(); $scope.ftpPassword = randomPassword(16); }; $scope.usePassword = function () { - $scope.generatedPasswordView = true; + $(".ftpPasswordView" ).hide(); }; }); diff --git a/ftp/templates/ftp/createFTPAccount.html b/ftp/templates/ftp/createFTPAccount.html index d82425c7b..9c068cf8c 100755 --- a/ftp/templates/ftp/createFTPAccount.html +++ b/ftp/templates/ftp/createFTPAccount.html @@ -41,7 +41,7 @@
    - {% for items in websiteList %} {% endfor %} @@ -53,17 +53,17 @@ -
    +
    -
    {{ admin }}_{$ ftpUserName $}
    +
    {{ OwnerFTP }}_{$ ftpUserName $}
    -
    +
    @@ -74,7 +74,7 @@
    -
    +
    -
    +
    -
    +
    -
    - -
    -
    -

    {% trans "Cannot create FTP account. Error message:" %} {$ errorMessage - $}

    -
    - -
    -

    {% trans "FTP Account with username:" %} {$ ftpUserName - $} {% trans "is successfully created." %}

    -
    -
    -

    {% trans "FTP Account with username:" %} {$ ftpUserName - $} {% trans "is successfully created." %}

    -
    - -
    - - -
    - - {% endif %} diff --git a/install/cyberpanel.repo b/install/cyberpanel.repo old mode 100755 new mode 100644 diff --git a/install/cyberso.pub b/install/cyberso.pub new file mode 100644 index 000000000..f87da8339 --- /dev/null +++ b/install/cyberso.pub @@ -0,0 +1 @@ +ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD3txFD2sk0fG9MX4l8vpvXYn8ymRN8107PCYywxvwIVN2KnWcPvsKreOajdJr6wj07jqXpviolQdkCM+qPRodHmTX5gpRz0GQobik1S1bihc2wTC4CA9WWAolXxBxnUO5FnMJMoB3tWmg+1tpJZnr+ZATFHjCbmTH+Ra5KO/bROt/gYoiiZvEAzLJNrLYOKBZ9Ik6/GBWFLALosjM8wFK6LQrrOzeNSOK7+aActliF0RjssHwi/65H0Hv172GsIecWvWTnOXrkhi134OtQmbSRtnVAMtjaPsWGO1PEJZya2iRa41fslolH2iQV9Bwe5m0pclceE14UV0cEvO7CqavF cyberso@ip-172-26-3-119.eu-west-2.compute.internal \ No newline at end of file diff --git a/install/install.py b/install/install.py index 89823b25f..84899beb4 100755 --- a/install/install.py +++ b/install/install.py @@ -14,8 +14,8 @@ from os.path import * from stat import * import stat -VERSION = '2.0' -BUILD = 3 +VERSION = '2.1' +BUILD = 1 char_set = {'small': 'abcdefghijklmnopqrstuvwxyz', 'nums': '0123456789', @@ -776,18 +776,11 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout'; command = 'debconf-set-selections ' + file_name preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR) - command = 'apt-get -y install postfix' + command = 'apt-get -y install postfix postfix-mysql' # os.remove(file_name) preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR) - if self.distro == centos or self.distro == cent8: - pass - else: - command = 'apt-get -y install dovecot-imapd dovecot-pop3d postfix-mysql' - - preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR) - ## if self.distro == centos: @@ -795,42 +788,42 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout'; elif self.distro == cent8: command = 'dnf install --enablerepo=gf-plus dovecot23 dovecot23-mysql -y' else: - command = 'apt-get -y install dovecot-mysql' + command = 'apt-get -y install dovecot-mysql dovecot-imapd dovecot-pop3d' preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR) - if self.distro != centos: - command = 'curl https://repo.dovecot.org/DOVECOT-REPO-GPG | gpg --import' - subprocess.call(command, shell=True) - - command = 'gpg --export ED409DA1 > /etc/apt/trusted.gpg.d/dovecot.gpg' - subprocess.call(command, shell=True) - - debPath = '/etc/apt/sources.list.d/dovecot.list' - writeToFile = open(debPath, 'w') - writeToFile.write('deb https://repo.dovecot.org/ce-2.3-latest/ubuntu/bionic bionic main\n') - writeToFile.close() - - try: - command = 'apt update -y' - subprocess.call(command, shell=True) - except: - pass - - try: - command = 'DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical sudo apt-get -q -y -o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold" --only-upgrade install dovecot-mysql -y' - subprocess.call(command, shell=True) - - command = 'dpkg --configure -a' - subprocess.call(command, shell=True) - - command = 'apt --fix-broken install -y' - subprocess.call(command, shell=True) - - command = 'DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical sudo apt-get -q -y -o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold" --only-upgrade install dovecot-mysql -y' - subprocess.call(command, shell=True) - except: - pass + # if self.distro != centos: + # command = 'curl https://repo.dovecot.org/DOVECOT-REPO-GPG | gpg --import' + # subprocess.call(command, shell=True) + # + # command = 'gpg --export ED409DA1 > /etc/apt/trusted.gpg.d/dovecot.gpg' + # subprocess.call(command, shell=True) + # + # debPath = '/etc/apt/sources.list.d/dovecot.list' + # writeToFile = open(debPath, 'w') + # writeToFile.write('deb https://repo.dovecot.org/ce-2.3-latest/ubuntu/bionic bionic main\n') + # writeToFile.close() + # + # try: + # command = 'apt update -y' + # subprocess.call(command, shell=True) + # except: + # pass + # + # try: + # command = 'DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical sudo apt-get -q -y -o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold" --only-upgrade install dovecot-mysql -y' + # subprocess.call(command, shell=True) + # + # command = 'dpkg --configure -a' + # subprocess.call(command, shell=True) + # + # command = 'apt --fix-broken install -y' + # subprocess.call(command, shell=True) + # + # command = 'DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical sudo apt-get -q -y -o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold" --only-upgrade install dovecot-mysql -y' + # subprocess.call(command, shell=True) + # except: + # pass except BaseException as msg: logging.InstallLog.writeToFile('[ERROR] ' + str(msg) + " [install_postfix_davecot]") @@ -845,20 +838,14 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout'; os.chdir(self.cwd) - if mysql == 'Two': - mysql_virtual_domains = "email-configs/mysql-virtual_domains.cf" - mysql_virtual_forwardings = "email-configs/mysql-virtual_forwardings.cf" - mysql_virtual_mailboxes = "email-configs/mysql-virtual_mailboxes.cf" - mysql_virtual_email2email = "email-configs/mysql-virtual_email2email.cf" - davecotmysql = "email-configs/dovecot-sql.conf.ext" - else: - mysql_virtual_domains = "email-configs-one/mysql-virtual_domains.cf" - mysql_virtual_forwardings = "email-configs-one/mysql-virtual_forwardings.cf" - mysql_virtual_mailboxes = "email-configs-one/mysql-virtual_mailboxes.cf" - mysql_virtual_email2email = "email-configs-one/mysql-virtual_email2email.cf" - davecotmysql = "email-configs-one/dovecot-sql.conf.ext" + mysql_virtual_domains = "email-configs-one/mysql-virtual_domains.cf" + mysql_virtual_forwardings = "email-configs-one/mysql-virtual_forwardings.cf" + mysql_virtual_mailboxes = "email-configs-one/mysql-virtual_mailboxes.cf" + mysql_virtual_email2email = "email-configs-one/mysql-virtual_email2email.cf" + davecotmysql = "email-configs-one/dovecot-sql.conf.ext" - ### update password: + + ### update password: data = open(davecotmysql, "r").readlines() @@ -875,8 +862,6 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout'; else: writeDataToFile.writelines(items) - # if self.distro == ubuntu: - # os.fchmod(writeDataToFile.fileno(), stat.S_IRUSR | stat.S_IWUSR) writeDataToFile.close() @@ -894,9 +879,6 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout'; else: writeDataToFile.writelines(items) - # if self.distro == ubuntu: - # os.fchmod(writeDataToFile.fileno(), stat.S_IRUSR | stat.S_IWUSR) - writeDataToFile.close() ### update password: @@ -913,9 +895,6 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout'; else: writeDataToFile.writelines(items) - # if self.distro == ubuntu: - # os.fchmod(writeDataToFile.fileno(), stat.S_IRUSR | stat.S_IWUSR) - writeDataToFile.close() ### update password: @@ -932,9 +911,6 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout'; else: writeDataToFile.writelines(items) - # if self.distro == ubuntu: - # os.fchmod(writeDataToFile.fileno(), stat.S_IRUSR | stat.S_IWUSR) - writeDataToFile.close() ### update password: @@ -951,9 +927,6 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout'; else: writeDataToFile.writelines(items) - # if self.distro == ubuntu: - # os.fchmod(writeDataToFile.fileno(), stat.S_IRUSR | stat.S_IWUSR) - writeDataToFile.close() @@ -1060,37 +1033,24 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout'; # Cleanup config files for ubuntu if self.distro == ubuntu: preFlightsChecks.stdOut("Cleanup postfix/dovecot config files", 1) - if mysql == 'Two': - self.centos_lib_dir_to_ubuntu("email-configs/master.cf", "/usr/libexec/", "/usr/lib/") - self.centos_lib_dir_to_ubuntu("email-configs/main.cf", "/usr/libexec/postfix", - "/usr/lib/postfix/sbin") - else: - self.centos_lib_dir_to_ubuntu("email-configs-one/master.cf", "/usr/libexec/", "/usr/lib/") - self.centos_lib_dir_to_ubuntu("email-configs-one/main.cf", "/usr/libexec/postfix", - "/usr/lib/postfix/sbin") + + self.centos_lib_dir_to_ubuntu("email-configs-one/master.cf", "/usr/libexec/", "/usr/lib/") + self.centos_lib_dir_to_ubuntu("email-configs-one/main.cf", "/usr/libexec/postfix", + "/usr/lib/postfix/sbin") ########### Copy config files - if mysql == 'Two': - shutil.copy("email-configs/mysql-virtual_domains.cf", "/etc/postfix/mysql-virtual_domains.cf") - shutil.copy("email-configs/mysql-virtual_forwardings.cf", "/etc/postfix/mysql-virtual_forwardings.cf") - shutil.copy("email-configs/mysql-virtual_mailboxes.cf", "/etc/postfix/mysql-virtual_mailboxes.cf") - shutil.copy("email-configs/mysql-virtual_email2email.cf", "/etc/postfix/mysql-virtual_email2email.cf") - shutil.copy("email-configs/main.cf", main) - shutil.copy("email-configs/master.cf", master) - shutil.copy("email-configs/dovecot.conf", davecot) - shutil.copy("email-configs/dovecot-sql.conf.ext", davecotmysql) - else: - shutil.copy("email-configs-one/mysql-virtual_domains.cf", "/etc/postfix/mysql-virtual_domains.cf") - shutil.copy("email-configs-one/mysql-virtual_forwardings.cf", - "/etc/postfix/mysql-virtual_forwardings.cf") - shutil.copy("email-configs-one/mysql-virtual_mailboxes.cf", "/etc/postfix/mysql-virtual_mailboxes.cf") - shutil.copy("email-configs-one/mysql-virtual_email2email.cf", - "/etc/postfix/mysql-virtual_email2email.cf") - shutil.copy("email-configs-one/main.cf", main) - shutil.copy("email-configs-one/master.cf", master) - shutil.copy("email-configs-one/dovecot.conf", davecot) - shutil.copy("email-configs-one/dovecot-sql.conf.ext", davecotmysql) + shutil.copy("email-configs-one/mysql-virtual_domains.cf", "/etc/postfix/mysql-virtual_domains.cf") + shutil.copy("email-configs-one/mysql-virtual_forwardings.cf", + "/etc/postfix/mysql-virtual_forwardings.cf") + shutil.copy("email-configs-one/mysql-virtual_mailboxes.cf", "/etc/postfix/mysql-virtual_mailboxes.cf") + shutil.copy("email-configs-one/mysql-virtual_email2email.cf", + "/etc/postfix/mysql-virtual_email2email.cf") + shutil.copy("email-configs-one/main.cf", main) + shutil.copy("email-configs-one/master.cf", master) + shutil.copy("email-configs-one/dovecot.conf", davecot) + shutil.copy("email-configs-one/dovecot-sql.conf.ext", davecotmysql) + ######################################## Permissions @@ -2197,7 +2157,7 @@ def main(): parser.add_argument('--mysqlport', help='MySQL port if remote is chosen.') args = parser.parse_args() - logging.InstallLog.writeToFile("Starting CyberPanel installation..") + logging.InstallLog.writeToFile("Starting CyberPanel installation..,10") preFlightsChecks.stdOut("Starting CyberPanel installation..") if args.ent == None: @@ -2388,7 +2348,7 @@ echo $oConfig->Save() ? 'Done' : 'Error'; except: pass - logging.InstallLog.writeToFile("CyberPanel installation successfully completed!") + logging.InstallLog.writeToFile("CyberPanel installation successfully completed!,80") if __name__ == "__main__": diff --git a/install/installCyberPanel.py b/install/installCyberPanel.py index d526db048..baeed20d7 100755 --- a/install/installCyberPanel.py +++ b/install/installCyberPanel.py @@ -656,13 +656,16 @@ def Main(cwd, mysql, distro, ent, serial = None, port = "8090", ftp = None, dns installer = InstallCyberPanel("/usr/local/lsws/",cwd, distro, ent, serial, port, ftp, dns, publicip, remotemysql, mysqlhost, mysqldb, mysqluser, mysqlpassword, mysqlport) + logging.InstallLog.writeToFile('Installing LiteSpeed Web server,40') installer.installLiteSpeed() if ent == 0: installer.changePortTo80() + logging.InstallLog.writeToFile('Installing Optimized PHPs..,50') installer.installAllPHPVersions() if ent == 0: installer.fix_ols_configs() + logging.InstallLog.writeToFile('Installing MySQL,60') installer.installMySQL(mysql) installer.changeMYSQLRootPassword() diff --git a/install/installLog.py b/install/installLog.py index 6aa1b7254..2c2b8db39 100755 --- a/install/installLog.py +++ b/install/installLog.py @@ -3,9 +3,22 @@ import time class InstallLog: fileName = "/var/log/installLogs.txt" + currentPercent = '10' + @staticmethod def writeToFile(message): + + if message.find(',') == -1: + message = '%s,%s' % (message, InstallLog.currentPercent) + elif message.find('mount -o') > -1 or message.find('usermod -G lscpd,') > -1: + message = '%s,%s' % (message.replace(',', '-'), InstallLog.currentPercent) + else: + try: + InstallLog.currentPercent = message.split(',')[1] + except: + pass + file = open(InstallLog.fileName,'a') file.writelines("[" + time.strftime( - "%m.%d.%Y_%H-%M-%S") + "] "+message + "\n") + "%m.%d.%Y_%H-%M-%S") + "] " + message + "\n") file.close() diff --git a/install/litespeed/conf/httpd_config.conf b/install/litespeed/conf/httpd_config.conf index 31783e118..74c4402e3 100755 --- a/install/litespeed/conf/httpd_config.conf +++ b/install/litespeed/conf/httpd_config.conf @@ -32,6 +32,7 @@ expires { enableExpires 1 expiresByType image/*=A604800, text/css=A604800, application/x-javascript=A604800 } +autoLoadHtaccess 1 tuning { eventDispatcher best @@ -199,4 +200,7 @@ include phpconfigs/php55.conf include phpconfigs/php56.conf include phpconfigs/php70.conf include phpconfigs/php71.conf - +include phpconfigs/php72.conf +include phpconfigs/php73.conf +include phpconfigs/php74.conf +include phpconfigs/php80.conf diff --git a/loginSystem/models.py b/loginSystem/models.py index abd302914..35089bca1 100755 --- a/loginSystem/models.py +++ b/loginSystem/models.py @@ -72,6 +72,9 @@ class ACL(models.Model): manageSSL = models.IntegerField(default=1) hostnameSSL = models.IntegerField(default=0) mailServerSSL = models.IntegerField(default=0) + config = models.TextField(default='{}') + + class Administrator(models.Model): userName = models.CharField(unique=True,max_length = 50) @@ -93,6 +96,7 @@ class Administrator(models.Model): acl = models.ForeignKey(ACL, default=1, on_delete=models.PROTECT) twoFA = models.IntegerField(default=0) secretKey = models.CharField(max_length=50, default='None') + config = models.TextField(default='{}') diff --git a/loginSystem/static/loginSystem/login-systen.js b/loginSystem/static/loginSystem/login-system.js similarity index 100% rename from loginSystem/static/loginSystem/login-systen.js rename to loginSystem/static/loginSystem/login-system.js diff --git a/loginSystem/templates/loginSystem/login.html b/loginSystem/templates/loginSystem/login.html index c34b049b6..d4b285da3 100755 --- a/loginSystem/templates/loginSystem/login.html +++ b/loginSystem/templates/loginSystem/login.html @@ -1,249 +1,361 @@ + - - - - Login - CyberPanel - - + .col-login-left { + background: rgb(51, 204, 204); + background: -moz-linear-gradient(0deg, rgba(51, 204, 204, 1) 0%, rgba(0, 0, 122, 1) 100%); + background: -webkit-linear-gradient(0deg, rgba(51, 204, 204, 1) 0%, rgba(0, 0, 122, 1) 100%); + background: linear-gradient(0deg, rgba(51, 204, 204, 1) 0%, rgba(0, 0, 122, 1) 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#33cccc", endColorstr="#00007a", GradientType=1); + justify-content: space-between; + } - - {% load static %} + .form-group .input-group select.form-control, + .form-group .input-group input.form-control, + button.btn.btn-login { + height: 45px; - + } + button.btn.btn-login { + background-color: rgb(51, 204, 204); + box-shadow: 0 0 px 0px rgba(0, 0, 0, 0), 0 1px 2px rgba(0, 0, 0, 0); + transition: all 0.3s cubic-bezier(.25, .8, .25, 1); + } + button.btn.btn-login:hover { + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24); + } - + .form-group .input-group select.form-control:focus, + .form-group .input-group input.form-control:focus, + button.btn.btn-login { + border: 1px solid rgb(51, 204, 204); + } - + .col-login-right { + background: #ffffff; + justify-content: center; + } - + .col-login-right .login-wrapper { + display: flex; + flex-direction: column; + justify-content: space-around; + } + a.login-changelogs { + border-top: 1px solid #fff; + } - + .login-changelogs .card { + padding: 1em; + background-color: #fff; + border-radius: 8px; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24); + transition: all 0.3s cubic-bezier(.25, .8, .25, 1); + } - + .login-changelogs .card:hover { + color: rgb(51, 204, 204); + box-shadow: 0 12px 24px rgba(0, 0, 0, 0.16), 0 10px 10px rgba(0, 0, 0, 0.18); + } + .card-body { + padding-left: 15px; + } - + .object-fit { + height: 100%; + width: 100%; + object-fit: cover; + border-radius: 6px; + } - + h4.card-learnmore { + margin-top: 15px; + position: relative; + color: rgb(51, 204, 204); + font-weight: 500; + font-size: 1.2em; - + } - + h4.card-learnmore span { + display: inline; + padding-bottom: 4px; + border-bottom: 1px solid rgb(51, 204, 204); + } + .alert.alert-danger { + text-align: center; + margin: 1em 2em 1em 2em; + padding-top: 1em; + padding-bottom: 1em; + border: 1px solid red; + } - + .spinner>div { + width: 18px; + height: 18px; + background-color: #333; + border-radius: 100%; + display: inline-block; + -webkit-animation: bouncedelay 1.4s infinite ease-in-out; + animation: bouncedelay 1.4s infinite ease-in-out; + -webkit-animation-fill-mode: both; + animation-fill-mode: both + } + + .spinner .bounce1 { + -webkit-animation-delay: -.32s; + animation-delay: -.32s + } + + .spinner .bounce2 { + -webkit-animation-delay: -.16s; + animation-delay: -.16s + } + + @-webkit-keyframes bouncedelay { + + 0%, + 80%, + 100% { + -webkit-transform: scale(0.0) + } + + 40% { + -webkit-transform: scale(1.0) + } + } + + @keyframes bouncedelay { + + 0%, + 80%, + 100% { + transform: scale(0.0); + -webkit-transform: scale(0.0) + } + + 40% { + transform: scale(1.0); + -webkit-transform: scale(1.0) + } + } + + + + Login - CyberPanel + + + + + {% load static %} + + + + + + + + + + + + + + + + + + + + + + + -
    +
    -
    -
    -
    +
    +
    +
    -
    +
    -
    -
    -
    +
    + - -
    -
    -
    -
    -

    - - CyberPanel - v 2.0 -

    -

    Web Hosting Control Panel

    -
    -
    -
    -
    -
    - - - - -
    -
    -
    -
    - - - - -
    - -
    - -
    -
    - - - - -
    -
    - - -
    -
    - -
    -
    - - - -
    + +
    +
    +
    + + -
    -
    - - - +
    + + + - \ No newline at end of file + + diff --git a/loginSystem/templates/loginSystem/test.html b/loginSystem/templates/loginSystem/test.html index 554fecddb..54ce02540 100755 --- a/loginSystem/templates/loginSystem/test.html +++ b/loginSystem/templates/loginSystem/test.html @@ -279,7 +279,7 @@ - + @@ -356,4 +356,4 @@ - \ No newline at end of file + diff --git a/loginSystem/views.py b/loginSystem/views.py index da4af680e..4d600cb94 100644 --- a/loginSystem/views.py +++ b/loginSystem/views.py @@ -18,8 +18,8 @@ from django.http import HttpResponse from django.utils import translation # Create your views here. -VERSION = '2.0' -BUILD = 3 +VERSION = '2.1' +BUILD = 1 def verifyLogin(request): try: diff --git a/mailServer/mailserverManager.py b/mailServer/mailserverManager.py index c76325ae5..d16fbd6b9 100755 --- a/mailServer/mailserverManager.py +++ b/mailServer/mailserverManager.py @@ -3,6 +3,9 @@ import os.path import sys import django + +from plogical.httpProc import httpProc + sys.path.append('/usr/local/CyberCP') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") django.setup() @@ -55,50 +58,42 @@ class MailServerManager(multi.Thread): logging.CyberCPLogFileWriter.writeToFile(str(msg) + ' [MailServerManager.run]') def loadEmailHome(self): - try: - val = self.request.session['userID'] - return render(self.request, 'mailServer/index.html') - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(self.request, 'mailServer/index.html', + None, 'createEmail') + return proc.render() def createEmailAccount(self): - try: - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'createEmail') == 0: - return ACLManager.loadError() + if not os.path.exists('/home/cyberpanel/postfix'): + proc = httpProc(self.request, 'mailServer/createEmailAccount.html', + {"status": 0}, 'createEmail') + return proc.render() - if not os.path.exists('/home/cyberpanel/postfix'): - return render(self.request, "mailServer/createEmailAccount.html", {"status": 0}) + websitesName = ACLManager.findAllSites(currentACL, userID) + websitesName = websitesName + ACLManager.findChildDomains(websitesName) - websitesName = ACLManager.findAllSites(currentACL, userID) - websitesName = websitesName + ACLManager.findChildDomains(websitesName) - - return render(self.request, 'mailServer/createEmailAccount.html', - {'websiteList': websitesName, "status": 1}) - except BaseException as msg: - return redirect(loadLoginPage) + proc = httpProc(self.request, 'mailServer/createEmailAccount.html', + {'websiteList': websitesName, "status": 1}, 'createEmail') + return proc.render() def listEmails(self): - try: - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'listEmails') == 0: - return ACLManager.loadError() + if not os.path.exists('/home/cyberpanel/postfix'): + proc = httpProc(self.request, 'mailServer/listEmails.html', + {"status": 0}, 'listEmails') + return proc.render() - if not os.path.exists('/home/cyberpanel/postfix'): - return render(self.request, "mailServer/listEmails.html", {"status": 0}) + websitesName = ACLManager.findAllSites(currentACL, userID) + websitesName = websitesName + ACLManager.findChildDomains(websitesName) - websitesName = ACLManager.findAllSites(currentACL, userID) - websitesName = websitesName + ACLManager.findChildDomains(websitesName) - - return render(self.request, 'mailServer/listEmails.html', - {'websiteList': websitesName, "status": 1}) - except BaseException as msg: - return redirect(loadLoginPage) + proc = httpProc(self.request, 'mailServer/listEmails.html', + {'websiteList': websitesName, "status": 1}, 'listEmails') + return proc.render() def submitEmailCreation(self): try: @@ -142,24 +137,20 @@ class MailServerManager(multi.Thread): return HttpResponse(json_data) def deleteEmailAccount(self): - try: + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + if not os.path.exists('/home/cyberpanel/postfix'): + proc = httpProc(self.request, 'mailServer/deleteEmailAccount.html', + {"status": 0}, 'deleteEmail') + return proc.render() - if ACLManager.currentContextPermission(currentACL, 'deleteEmail') == 0: - return ACLManager.loadError() + websitesName = ACLManager.findAllSites(currentACL, userID) + websitesName = websitesName + ACLManager.findChildDomains(websitesName) - if not os.path.exists('/home/cyberpanel/postfix'): - return render(self.request, "mailServer/deleteEmailAccount.html", {"status": 0}) - - websitesName = ACLManager.findAllSites(currentACL, userID) - websitesName = websitesName + ACLManager.findChildDomains(websitesName) - - return render(self.request, 'mailServer/deleteEmailAccount.html', - {'websiteList': websitesName, "status": 1}) - except BaseException as msg: - return redirect(loadLoginPage) + proc = httpProc(self.request, 'mailServer/deleteEmailAccount.html', + {'websiteList': websitesName, "status": 1}, 'deleteEmail') + return proc.render() def getEmailsForDomain(self): try: @@ -284,22 +275,20 @@ class MailServerManager(multi.Thread): return HttpResponse(json_data) def emailForwarding(self): - try: - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'emailForwarding') == 0: - return ACLManager.loadError() + if not os.path.exists('/home/cyberpanel/postfix'): + proc = httpProc(self.request, 'mailServer/emailForwarding.html', + {"status": 0}, 'emailForwarding') + return proc.render() - if not os.path.exists('/home/cyberpanel/postfix'): - return render(self.request, "mailServer/emailForwarding.html", {"status": 0}) + websitesName = ACLManager.findAllSites(currentACL, userID) + websitesName = websitesName + ACLManager.findChildDomains(websitesName) - websitesName = ACLManager.findAllSites(currentACL, userID) - websitesName = websitesName + ACLManager.findChildDomains(websitesName) - - return render(self.request, 'mailServer/emailForwarding.html', {'websiteList': websitesName, "status": 1}) - except BaseException as msg: - return redirect(loadLoginPage) + proc = httpProc(self.request, 'mailServer/emailForwarding.html', + {'websiteList': websitesName, "status": 1}, 'emailForwarding') + return proc.render() def fetchCurrentForwardings(self): try: @@ -573,23 +562,20 @@ class MailServerManager(multi.Thread): ####### def changeEmailAccountPassword(self): - try: - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'changeEmailPassword') == 0: - return ACLManager.loadError() + if not os.path.exists('/home/cyberpanel/postfix'): + proc = httpProc(self.request, 'mailServer/changeEmailPassword.html', + {"status": 0}, 'changeEmailPassword') + return proc.render() - if not os.path.exists('/home/cyberpanel/postfix'): - return render(self.request, "mailServer/changeEmailPassword.html", {"status": 0}) + websitesName = ACLManager.findAllSites(currentACL, userID) + websitesName = websitesName + ACLManager.findChildDomains(websitesName) - websitesName = ACLManager.findAllSites(currentACL, userID) - websitesName = websitesName + ACLManager.findChildDomains(websitesName) - - return render(self.request, 'mailServer/changeEmailPassword.html', - {'websiteList': websitesName, "status": 1}) - except BaseException as msg: - return redirect(loadLoginPage) + proc = httpProc(self.request, 'mailServer/changeEmailPassword.html', + {'websiteList': websitesName, "status": 1}, 'changeEmailPassword') + return proc.render() def submitPasswordChange(self): try: @@ -641,23 +627,17 @@ class MailServerManager(multi.Thread): ####### def dkimManager(self): - try: - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'dkimManager') == 0: - return ACLManager.loadError() + openDKIMInstalled = 1 - openDKIMInstalled = 1 + websitesName = ACLManager.findAllSites(currentACL, userID) + websitesName = websitesName + ACLManager.findChildDomains(websitesName) - websitesName = ACLManager.findAllSites(currentACL, userID) - websitesName = websitesName + ACLManager.findChildDomains(websitesName) - - return render(self.request, 'mailServer/dkimManager.html', - {'websiteList': websitesName, 'openDKIMInstalled': openDKIMInstalled}) - - except BaseException as msg: - return redirect(loadLoginPage) + proc = httpProc(self.request, 'mailServer/dkimManager.html', + {'websiteList': websitesName, 'openDKIMInstalled': openDKIMInstalled}, 'dkimManager') + return proc.render() def fetchDKIMKeys(self): try: diff --git a/managePHP/views.py b/managePHP/views.py index 9f672a3c9..2549da31a 100755 --- a/managePHP/views.py +++ b/managePHP/views.py @@ -20,6 +20,7 @@ from xml.etree import ElementTree from plogical.acl import ACLManager from plogical.processUtilities import ProcessUtilities from .phpManager import PHPManager +from plogical.httpProc import httpProc # Create your views here. @@ -29,12 +30,10 @@ def loadPHPHome(request): userID = request.session['userID'] currentACL = ACLManager.loadedACL(userID) - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() + proc = httpProc(request, 'managePHP/index.html', + None, 'admin') + return proc.render() - return render(request, 'managePHP/index.html') except KeyError: return redirect(loadLoginPage) @@ -43,11 +42,6 @@ def installExtensions(request): userID = request.session['userID'] currentACL = ACLManager.loadedACL(userID) - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - if PHP.objects.count() == 0: for i in range(3, 7): php = "php" + str(5) + str(i) @@ -1247,7 +1241,10 @@ def installExtensions(request): except: pass - return render(request, 'managePHP/installExtensions.html', {'phps': PHPManager.findPHPVersions()}) + proc = httpProc(request, 'managePHP/installExtensions.html', + {'phps': PHPManager.findPHPVersions()}, 'admin') + return proc.render() + except KeyError: return redirect(loadLoginPage) @@ -1601,14 +1598,10 @@ def getRequestStatusApache(request): def editPHPConfigs(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + proc = httpProc(request, 'managePHP/editPHPConfig.html', + {'phps': PHPManager.findPHPVersions()}, 'admin') + return proc.render() - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - return render(request, 'managePHP/editPHPConfig.html', {'phps': PHPManager.findPHPVersions()}) except KeyError: return redirect(loadLoginPage) @@ -1695,7 +1688,9 @@ def getCurrentPHPConfig(request): return HttpResponse(final_json) - return render(request, 'managePHP/editPHPConfig.html') + proc = httpProc(request, 'managePHP/editPHPConfig.html', + None, 'admin') + return proc.render() except KeyError: return redirect(loadLoginPage) diff --git a/manageSSL/views.py b/manageSSL/views.py index 0dfdb16c5..9d455158e 100755 --- a/manageSSL/views.py +++ b/manageSSL/views.py @@ -1,49 +1,31 @@ # -*- coding: utf-8 -*- - -from django.shortcuts import render, redirect -from loginSystem.views import loadLoginPage +from plogical.httpProc import httpProc from websiteFunctions.models import Websites, ChildDomains from loginSystem.models import Administrator from plogical.virtualHostUtilities import virtualHostUtilities from django.http import HttpResponse import json -import shlex -import subprocess from plogical.acl import ACLManager -from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging from plogical.processUtilities import ProcessUtilities - # Create your views here. - def loadSSLHome(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - return render(request, 'manageSSL/index.html', currentACL) - except KeyError: - return redirect(loadLoginPage) + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + proc = httpProc(request, 'manageSSL/index.html', + currentACL, 'admin') + return proc.render() def manageSSL(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - elif currentACL['manageSSL'] == 1: - pass - else: - return ACLManager.loadError() - - websitesName = ACLManager.findAllSites(currentACL, userID) - - return render(request, 'manageSSL/manageSSL.html', {'websiteList': websitesName}) - except KeyError: - return redirect(loadLoginPage) + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID) + proc = httpProc(request, 'manageSSL/manageSSL.html', + {'websiteList': websitesName}, 'manageSSL') + return proc.render() def issueSSL(request): @@ -115,22 +97,12 @@ def issueSSL(request): def sslForHostName(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - elif currentACL['hostnameSSL'] == 1: - pass - else: - return ACLManager.loadError() - - websitesName = ACLManager.findAllSites(currentACL, userID, 1) - - return render(request, 'manageSSL/sslForHostName.html', {'websiteList': websitesName}) - except KeyError: - return redirect(loadLoginPage) + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID, 1) + proc = httpProc(request, 'manageSSL/sslForHostName.html', + {'websiteList': websitesName}, 'hostnameSSL') + return proc.render() def obtainHostNameSSL(request): @@ -197,23 +169,15 @@ def obtainHostNameSSL(request): def sslForMailServer(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) - if currentACL['admin'] == 1: - pass - elif currentACL['mailServerSSL'] == 1: - pass - else: - return ACLManager.loadError() + websitesName = ACLManager.findAllSites(currentACL, userID) + websitesName = websitesName + ACLManager.findChildDomains(websitesName) - websitesName = ACLManager.findAllSites(currentACL, userID) - websitesName = websitesName + ACLManager.findChildDomains(websitesName) - - return render(request, 'manageSSL/sslForMailServer.html', {'websiteList': websitesName}) - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'manageSSL/sslForMailServer.html', + {'websiteList': websitesName}, 'mailServerSSL') + return proc.render() def obtainMailServerSSL(request): diff --git a/manageServices/views.py b/manageServices/views.py index c4bc2f697..ddca457b6 100755 --- a/manageServices/views.py +++ b/manageServices/views.py @@ -1,11 +1,12 @@ # -*- coding: utf-8 -*- -from django.shortcuts import render from django.shortcuts import HttpResponse, redirect import plogical.CyberCPLogFileWriter as logging from loginSystem.views import loadLoginPage import os import json + +from plogical.httpProc import httpProc from plogical.mailUtilities import mailUtilities from plogical.acl import ACLManager from .models import PDNSStatus, SlaveServers @@ -14,84 +15,41 @@ from plogical.processUtilities import ProcessUtilities # Create your views here. def managePowerDNS(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + data = {} + data['status'] = 1 + pdnsStatus = PDNSStatus.objects.get(pk=1) - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - try: + if pdnsStatus.type == 'MASTER': + counter = 1 - data = {} - data['status'] = 1 + for items in SlaveServers.objects.all(): - pdnsStatus = PDNSStatus.objects.get(pk=1) - - if pdnsStatus.type == 'MASTER': - counter = 1 - - for items in SlaveServers.objects.all(): - - if counter == 1: - data['slaveServer'] = items.slaveServer - data['slaveServerIP'] = items.slaveServerIP - else: - data['slaveServer%s' % (str(counter))] = items.slaveServer - data['slaveServerIP%s' % (str(counter))] = items.slaveServerIP - - counter = counter + 1 + if counter == 1: + data['slaveServer'] = items.slaveServer + data['slaveServerIP'] = items.slaveServerIP else: - data['slaveServerNS'] = pdnsStatus.masterServer - data['masterServerIP'] = pdnsStatus.masterIP + data['slaveServer%s' % (str(counter))] = items.slaveServer + data['slaveServerIP%s' % (str(counter))] = items.slaveServerIP - return render(request, 'manageServices/managePowerDNS.html', data) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse("See CyberCP main log file.") + counter = counter + 1 + else: + data['slaveServerNS'] = pdnsStatus.masterServer + data['masterServerIP'] = pdnsStatus.masterIP - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'manageServices/managePowerDNS.html', + data, 'admin') + return proc.render() def managePostfix(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - try: - - return render(request, 'manageServices/managePostfix.html', {"status": 1}) - - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse("See CyberCP main log file.") - - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'manageServices/managePostfix.html', + {"status": 1}, 'admin') + return proc.render() def managePureFtpd(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - try: - return render(request, 'manageServices/managePureFtpd.html', {"status": 1}) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse("See CyberCP main log file.") - - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'manageServices/managePureFtpd.html', + {"status": 1}, 'admin') + return proc.render() def fetchStatus(request): try: @@ -301,46 +259,33 @@ def saveStatus(request): return HttpResponse(json_data) def manageApplications(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + services = [] - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() + ## ElasticSearch - services = [] + esPath = '/home/cyberpanel/elasticsearch' + rPath = '/home/cyberpanel/redis' - ## ElasticSearch + if os.path.exists(esPath): + installed = 'Installed' + else: + installed = 'Not-Installed' - esPath = '/home/cyberpanel/elasticsearch' - rPath = '/home/cyberpanel/redis' + if os.path.exists(rPath): + rInstalled = 'Installed' + else: + rInstalled = 'Not-Installed' - if os.path.exists(esPath): - installed = 'Installed' - else: - installed = 'Not-Installed' + elasticSearch = {'image': '/static/manageServices/images/elastic-search.png', 'name': 'Elastic Search', + 'installed': installed} + redis = {'image': '/static/manageServices/images/redis.png', 'name': 'Redis', + 'installed': rInstalled} + services.append(elasticSearch) + services.append(redis) - if os.path.exists(rPath): - rInstalled = 'Installed' - else: - rInstalled = 'Not-Installed' - - elasticSearch = {'image': '/static/manageServices/images/elastic-search.png', 'name': 'Elastic Search', 'installed': installed} - redis = {'image': '/static/manageServices/images/redis.png', 'name': 'Redis', - 'installed': rInstalled} - services.append(elasticSearch) - services.append(redis) - - try: - return render(request, 'manageServices/applications.html', {'services': services}) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse("See CyberCP main log file.") - - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'manageServices/applications.html', + {'services': services}, 'admin') + return proc.render() def removeInstall(request): try: diff --git a/packages/packagesManager.py b/packages/packagesManager.py index 69d798f35..610e961c3 100755 --- a/packages/packagesManager.py +++ b/packages/packagesManager.py @@ -2,13 +2,11 @@ import os.path import sys import django - -from plogical import hashPassword - +from plogical.httpProc import httpProc sys.path.append('/usr/local/CyberCP') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") django.setup() -from django.shortcuts import render,redirect +from django.shortcuts import redirect from django.http import HttpResponse from loginSystem.views import loadLoginPage from loginSystem.models import Administrator @@ -21,39 +19,24 @@ class PackagesManager: self.request = request def packagesHome(self): - try: - val = self.request.session['userID'] - return render(self.request, 'packages/index.html', {}) - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(self.request, 'packages/index.html', + None, 'admin') + return proc.render() def createPacakge(self): - try: - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'createPackage') == 0: - return ACLManager.loadError() - - admin = Administrator.objects.get(pk=userID) - return render(self.request, 'packages/createPackage.html', {"admin": admin.userName}) - - except KeyError: - return redirect(loadLoginPage) + userID = self.request.session['userID'] + admin = Administrator.objects.get(pk=userID) + proc = httpProc(self.request, 'packages/createPackage.html', + {"admin": admin.userName}, 'createPackage') + return proc.render() def deletePacakge(self): - try: - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'deletePackage') == 0: - return ACLManager.loadError() - - packageList = ACLManager.loadPackages(userID, currentACL) - return render(self.request, 'packages/deletePackage.html', {"packageList": packageList}) - - except BaseException as msg: - return HttpResponse(str(msg)) + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + packageList = ACLManager.loadPackages(userID, currentACL) + proc = httpProc(self.request, 'packages/deletePackage.html', + {"packageList": packageList}, 'deletePackage') + return proc.render() def submitPackage(self): try: @@ -134,18 +117,12 @@ class PackagesManager: return HttpResponse(json_data) def modifyPackage(self): - try: - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'modifyPackage') == 0: - return ACLManager.loadError() - - packageList = ACLManager.loadPackages(userID, currentACL) - return render(self.request, 'packages/modifyPackage.html', {"packList": packageList}) - - except BaseException as msg: - return HttpResponse(str(msg)) + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + packageList = ACLManager.loadPackages(userID, currentACL) + proc = httpProc(self.request, 'packages/modifyPackage.html', + {"packList": packageList}, 'modifyPackage') + return proc.render() def submitModify(self): try: @@ -225,18 +202,12 @@ class PackagesManager: def listPackages(self): - try: - userID = self.request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'listPackages') == 0: - return ACLManager.loadError() - - packageList = ACLManager.loadPackages(userID, currentACL) - return render(self.request, 'packages/listPackages.html', {"packList": packageList}) - - except BaseException as msg: - return redirect(loadLoginPage) + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + packageList = ACLManager.loadPackages(userID, currentACL) + proc = httpProc(self.request, 'packages/listPackages.html', + {"packList": packageList}, 'listPackages') + return proc.render() def listPackagesAPI(self,data=None): """ diff --git a/plogical/IncScheduler.py b/plogical/IncScheduler.py index 4fd07d81c..734c96a58 100644 --- a/plogical/IncScheduler.py +++ b/plogical/IncScheduler.py @@ -335,7 +335,6 @@ class IncScheduler(): message='Backup for %s successfully sent to Google Drive.' % (website.domain)).save() os.remove(completeFileToSend) - except BaseException as msg: GDriveJobLogs(owner=items, status=backupSchedule.ERROR, message='[Site] Site backup failed, Error message: %s.' % (str(msg))).save() @@ -625,11 +624,21 @@ Automatic backup failed for %s on %s. ts = time.time() retentionSeconds = 86400 * plan.retention - s3 = boto3.resource( - 's3', - aws_access_key_id=aws_access_key_id, - aws_secret_access_key=aws_secret_access_key - ) + + if region.find('http') > -1: + s3 = boto3.resource( + 's3', + aws_access_key_id=aws_access_key_id, + aws_secret_access_key=aws_secret_access_key, + endpoint_url=region + ) + else: + s3 = boto3.resource( + 's3', + aws_access_key_id=aws_access_key_id, + aws_secret_access_key=aws_secret_access_key, + ) + bucket = s3.Bucket(plan.bucket) for file in bucket.objects.all(): @@ -642,12 +651,19 @@ Automatic backup failed for %s on %s. ### - client = boto3.client( - 's3', - aws_access_key_id = aws_access_key_id, - aws_secret_access_key = aws_secret_access_key, - #region_name=region - ) + if region.find('http') > -1: + client = boto3.client( + 's3', + aws_access_key_id=aws_access_key_id, + aws_secret_access_key=aws_secret_access_key, + endpoint_url=region + ) + else: + client = boto3.client( + 's3', + aws_access_key_id = aws_access_key_id, + aws_secret_access_key = aws_secret_access_key, + ) ## @@ -666,6 +682,10 @@ Automatic backup failed for %s on %s. extraArgs['data'] = int(PlanConfig['data']) extraArgs['emails'] = int(PlanConfig['emails']) extraArgs['databases'] = int(PlanConfig['databases']) + extraArgs['port'] = '0' + extraArgs['ip'] = '0' + extraArgs['destinationDomain'] = 'None' + extraArgs['path'] = '/home/cyberpanel/backups/%s/backup-' % (items.domain) + items.domain + "-" + time.strftime("%m.%d.%Y_%H-%M-%S") bu = backupUtilities(extraArgs) result, fileName = bu.CloudBackups() @@ -711,6 +731,61 @@ Automatic backup failed for %s on %s. except BaseException as msg: logging.writeToFile(str(msg) + ' [S3Backups.runAWSBackups]') + @staticmethod + def CalculateAndUpdateDiskUsage(): + for website in Websites.objects.all(): + try: + try: + config = json.loads(website.config) + except: + config = {} + + config['DiskUsage'], config['DiskUsagePercentage'] = virtualHostUtilities.getDiskUsage("/home/" + website.domain, website.package.diskSpace) + + ## Calculate bw usage + + from plogical.vhost import vhost + config['bwInMB'], config['bwUsage'] = vhost.findDomainBW(website.domain, int(website.package.bandwidth)) + + website.config = json.dumps(config) + website.save() + + except BaseException as msg: + logging.writeToFile('%s. [CalculateAndUpdateDiskUsage:753]' % (str(msg))) + + @staticmethod + def WPUpdates(): + from cloudAPI.models import WPDeployments + for wp in WPDeployments.objects.all(): + try: + try: + config = json.loads(wp.config) + except: + config = {} + + ### Core Updates + + if config['updates'] == 'Minor and Security Updates': + command = 'wp core update --minor --allow-root --path=/home/%s/public_html' % (config['domainName']) + ProcessUtilities.executioner(command) + elif config['updates'] == 'All (minor and major)': + command = 'wp core update --allow-root --path=/home/%s/public_html' % (config['domainName']) + ProcessUtilities.executioner(command) + + ### Plugins, for plugins we will do minor updates only. + + if config['pluginUpdates'] == 'Enabled': + command = 'wp plugin update --all --minor --allow-root --path=/home/%s/public_html' % (config['domainName']) + ProcessUtilities.executioner(command) + + ### Themes, for plugins we will do minor updates only. + + if config['themeUpdates'] == 'Enabled': + command = 'wp theme update --all --minor --allow-root --path=/home/%s/public_html' % (config['domainName']) + ProcessUtilities.executioner(command) + + except BaseException as msg: + logging.writeToFile('%s. [WPUpdates:767]' % (str(msg))) def main(): @@ -724,6 +799,8 @@ def main(): IncScheduler.forceRunAWSBackup(args.planName) return 0 + IncScheduler.CalculateAndUpdateDiskUsage() + IncScheduler.WPUpdates() IncScheduler.startBackup(args.function) IncScheduler.runGoogleDriveBackups(args.function) IncScheduler.git(args.function) diff --git a/plogical/acl.py b/plogical/acl.py old mode 100755 new mode 100644 index e02c95782..36dd7a3a9 --- a/plogical/acl.py +++ b/plogical/acl.py @@ -71,78 +71,79 @@ class ACLManager: finalResponse['serverIPAddress'] = serverIPAddress finalResponse['adminName'] = admin.firstName - if admin.acl.adminStatus == 1: + config = json.loads(admin.acl.config) + + if config['adminStatus']: finalResponse['admin'] = 1 else: finalResponse['admin'] = 0 - - acl = ACL.objects.get(name=admin.acl.name) - finalResponse['versionManagement'] = acl.versionManagement + finalResponse['versionManagement'] = config['versionManagement'] ## User Management - finalResponse['createNewUser'] = acl.createNewUser - finalResponse['listUsers'] = acl.listUsers - finalResponse['deleteUser'] = acl.deleteUser - finalResponse['changeUserACL'] = acl.changeUserACL - finalResponse['resellerCenter'] = acl.resellerCenter + finalResponse['createNewUser'] = config['createNewUser'] + finalResponse['listUsers'] = config['listUsers'] + finalResponse['deleteUser'] = config['deleteUser'] + finalResponse['changeUserACL'] = config['changeUserACL'] + finalResponse['resellerCenter'] = config['resellerCenter'] ## Website Management - finalResponse['createWebsite'] = acl.createWebsite - finalResponse['modifyWebsite'] = acl.modifyWebsite - finalResponse['suspendWebsite'] = acl.suspendWebsite - finalResponse['deleteWebsite'] = acl.deleteWebsite + finalResponse['createWebsite'] = config['createWebsite'] + finalResponse['modifyWebsite'] = config['modifyWebsite'] + finalResponse['suspendWebsite'] = config['suspendWebsite'] + finalResponse['deleteWebsite'] = config['deleteWebsite'] ## Package Management - finalResponse['createPackage'] = acl.createPackage - finalResponse['listPackages'] = acl.listPackages - finalResponse['deletePackage'] = acl.deletePackage - finalResponse['modifyPackage'] = acl.modifyPackage + finalResponse['createPackage'] = config['createPackage'] + finalResponse['listPackages'] = config['listPackages'] + finalResponse['deletePackage'] = config['deletePackage'] + finalResponse['modifyPackage'] = config['modifyPackage'] ## Database Management - finalResponse['createDatabase'] = acl.createDatabase - finalResponse['deleteDatabase'] = acl.deleteDatabase - finalResponse['listDatabases'] = acl.listDatabases + finalResponse['createDatabase'] = config['createDatabase'] + finalResponse['deleteDatabase'] = config['deleteDatabase'] + finalResponse['listDatabases'] = config['listDatabases'] ## DNS Management - finalResponse['createNameServer'] = acl.createNameServer - finalResponse['createDNSZone'] = acl.createDNSZone - finalResponse['deleteZone'] = acl.deleteZone - finalResponse['addDeleteRecords'] = acl.addDeleteRecords + finalResponse['createNameServer'] = config['createNameServer'] + finalResponse['createDNSZone'] = config['createDNSZone'] + finalResponse['deleteZone'] = config['deleteZone'] + finalResponse['addDeleteRecords'] = config['addDeleteRecords'] ## Email Management - finalResponse['createEmail'] = acl.createEmail - finalResponse['listEmails'] = acl.listEmails - finalResponse['deleteEmail'] = acl.deleteEmail - finalResponse['emailForwarding'] = acl.emailForwarding - finalResponse['changeEmailPassword'] = acl.changeEmailPassword - finalResponse['dkimManager'] = acl.dkimManager + finalResponse['createEmail'] = config['createEmail'] + finalResponse['listEmails'] = config['listEmails'] + finalResponse['deleteEmail'] = config['deleteEmail'] + finalResponse['emailForwarding'] = config['emailForwarding'] + finalResponse['changeEmailPassword'] = config['changeEmailPassword'] + finalResponse['dkimManager'] = config['dkimManager'] ## FTP Management - finalResponse['createFTPAccount'] = acl.createFTPAccount - finalResponse['deleteFTPAccount'] = acl.deleteFTPAccount - finalResponse['listFTPAccounts'] = acl.listFTPAccounts + finalResponse['createFTPAccount'] = config['createFTPAccount'] + finalResponse['deleteFTPAccount'] = config['deleteFTPAccount'] + finalResponse['listFTPAccounts'] = config['listFTPAccounts'] ## Backup Management - finalResponse['createBackup'] = acl.createBackup - finalResponse['restoreBackup'] = acl.restoreBackup - finalResponse['addDeleteDestinations'] = acl.addDeleteDestinations - finalResponse['scheDuleBackups'] = acl.scheDuleBackups - finalResponse['remoteBackups'] = acl.remoteBackups + finalResponse['createBackup'] = config['createBackup'] + finalResponse['googleDriveBackups'] = config['googleDriveBackups'] + finalResponse['restoreBackup'] = config['restoreBackup'] + finalResponse['addDeleteDestinations'] = config['addDeleteDestinations'] + finalResponse['scheDuleBackups'] = config['scheDuleBackups'] + finalResponse['remoteBackups'] = config['remoteBackups'] ## SSL Management - finalResponse['manageSSL'] = acl.manageSSL - finalResponse['hostnameSSL'] = acl.hostnameSSL - finalResponse['mailServerSSL'] = acl.mailServerSSL + finalResponse['manageSSL'] = config['manageSSL'] + finalResponse['hostnameSSL'] = config['hostnameSSL'] + finalResponse['mailServerSSL'] = config['mailServerSSL'] return finalResponse @@ -409,35 +410,34 @@ class ACLManager: websiteNames = [] if currentACL['admin'] == 1: - allWebsites = Websites.objects.all() + allWebsites = Websites.objects.all().order_by('domain') for items in allWebsites: websiteNames.append(items.domain) if fetchChilds: - for child in items.childdomains_set.all(): + for child in items.childdomains_set.all().order_by('domain'): websiteNames.append(child.domain) - else: admin = Administrator.objects.get(pk=userID) - websites = admin.websites_set.all() + websites = admin.websites_set.all().order_by('domain') admins = Administrator.objects.filter(owner=admin.pk) for items in websites: websiteNames.append(items.domain) if fetchChilds: - for child in items.childdomains_set.all(): + for child in items.childdomains_set.all().order_by('domain'): websiteNames.append(child.domain) for items in admins: - webs = items.websites_set.all() + webs = items.websites_set.all().order_by('domain') for web in webs: websiteNames.append(web.domain) if fetchChilds: - for child in web.childdomains_set.all(): + for child in web.childdomains_set.all().order_by('domain'): websiteNames.append(child.domain) @@ -469,13 +469,13 @@ class ACLManager: @staticmethod def findWebsiteObjects(currentACL, userID): if currentACL['admin'] == 1: - return Websites.objects.all() + return Websites.objects.all().order_by('domain') else: websiteList = [] admin = Administrator.objects.get(pk=userID) - websites = admin.websites_set.all() + websites = admin.websites_set.all().order_by('domain') for items in websites: websiteList.append(items) @@ -483,7 +483,7 @@ class ACLManager: admins = Administrator.objects.filter(owner=admin.pk) for items in admins: - webs = items.websites_set.all() + webs = items.websites_set.all().order_by('domain') for web in webs: websiteList.append(web) @@ -494,12 +494,12 @@ class ACLManager: domainsList = [] if currentACL['admin'] == 1: - domains = Websites.objects.all() + domains = Websites.objects.all().order_by('domain') for items in domains: domainsList.append(items.domain) else: admin = Administrator.objects.get(pk=userID) - domains = admin.websites_set.all() + domains = admin.websites_set.all().order_by('domain') for items in domains: domainsList.append(items.domain) @@ -507,7 +507,7 @@ class ACLManager: admins = Administrator.objects.filter(owner=admin.pk) for items in admins: - doms = items.websites_set.all() + doms = items.websites_set.all().order_by('domain') for dom in doms: domainsList.append(dom.domain) @@ -518,12 +518,12 @@ class ACLManager: domainsList = [] if currentACL['admin'] == 1: - domains = Websites.objects.order_by('domain').all() + domains = Websites.objects.all().order_by('domain') for items in domains: domainsList.append(items.domain) else: admin = Administrator.objects.get(pk=userID) - domains = admin.websites_set.all() + domains = admin.websites_set.all().order_by('domain') for items in domains: domainsList.append(items.domain) @@ -531,7 +531,7 @@ class ACLManager: admins = Administrator.objects.filter(owner=admin.pk) for items in admins: - doms = items.websites_set.all() + doms = items.websites_set.all().order_by('domain') for dom in doms: domainsList.append(dom.domain) return domainsList @@ -675,7 +675,7 @@ class ACLManager: for items in websiteNames: website = Websites.objects.get(domain = items) - for childDomain in website.childdomains_set.all(): + for childDomain in website.childdomains_set.all().order_by('domain'): childDomains.append(childDomain.domain) return childDomains diff --git a/plogical/adminPass.py b/plogical/adminPass.py index bf32680c0..1cd46ebc4 100755 --- a/plogical/adminPass.py +++ b/plogical/adminPass.py @@ -12,8 +12,8 @@ from plogical.acl import ACLManager from packages.models import Package from baseTemplate.models import version -VERSION = '2.0' -BUILD = 3 +VERSION = '2.1' +BUILD = 1 if not os.geteuid() == 0: sys.exit("\nOnly root can run this script\n") @@ -22,39 +22,53 @@ def main(): parser = argparse.ArgumentParser(description='Reset admin user password!') parser.add_argument('--password', help='New Password') + parser.add_argument('--api', help='Enable/Disable API') args = parser.parse_args() - adminPass = args.password + if args.api != None: + if args.api == '1': + admin = Administrator.objects.get(userName="admin") + admin.api = 1 + admin.save() + print("API Enabled.") + else: + admin = Administrator.objects.get(userName="admin") + admin.api = 0 + admin.save() + print("API Disabled.") + else: - numberOfAdministrator = Administrator.objects.count() - if numberOfAdministrator == 0: - ACLManager.createDefaultACLs() - acl = ACL.objects.get(name='admin') - token = hashPassword.generateToken('admin', '1234567') + adminPass = args.password - email = 'usman@cyberpersons.com' - admin = Administrator(userName="admin", password=hashPassword.hash_password(adminPass), type=1, email=email, - firstName="Cyber", lastName="Panel", acl=acl, token=token) + numberOfAdministrator = Administrator.objects.count() + if numberOfAdministrator == 0: + ACLManager.createDefaultACLs() + acl = ACL.objects.get(name='admin') + token = hashPassword.generateToken('admin', '1234567') + + email = 'usman@cyberpersons.com' + admin = Administrator(userName="admin", password=hashPassword.hash_password(adminPass), type=1, email=email, + firstName="Cyber", lastName="Panel", acl=acl, token=token) + admin.save() + + vers = version(currentVersion=VERSION, build=BUILD) + vers.save() + + package = Package(admin=admin, packageName="Default", diskSpace=1000, + bandwidth=1000, ftpAccounts=1000, dataBases=1000, + emailAccounts=1000, allowedDomains=20) + package.save() + + print("Admin password successfully changed!") + return 1 + + token = hashPassword.generateToken('admin', adminPass) + admin = Administrator.objects.get(userName="admin") + admin.password = hashPassword.hash_password(adminPass) + admin.token = token admin.save() - vers = version(currentVersion=VERSION, build=BUILD) - vers.save() - - package = Package(admin=admin, packageName="Default", diskSpace=1000, - bandwidth=1000, ftpAccounts=1000, dataBases=1000, - emailAccounts=1000, allowedDomains=20) - package.save() - print("Admin password successfully changed!") - return 1 - - token = hashPassword.generateToken('admin', adminPass) - admin = Administrator.objects.get(userName="admin") - admin.password = hashPassword.hash_password(adminPass) - admin.token = token - admin.save() - - print("Admin password successfully changed!") if __name__ == "__main__": main() diff --git a/plogical/applicationInstaller.py b/plogical/applicationInstaller.py index a63950d61..7450c22f0 100755 --- a/plogical/applicationInstaller.py +++ b/plogical/applicationInstaller.py @@ -1,4 +1,5 @@ #!/usr/local/CyberCP/bin/python +import argparse import os, sys sys.path.append('/usr/local/CyberCP') @@ -384,13 +385,10 @@ $parameters = array( def installWPCLI(self): try: - command = 'wget https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar' + command = 'wget -O /usr/bin/wp https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar' ProcessUtilities.executioner(command) - command = 'chmod +x wp-cli.phar' - ProcessUtilities.executioner(command) - - command = 'mv wp-cli.phar /usr/bin/wp' + command = 'chmod +x /usr/bin/wp' ProcessUtilities.executioner(command) except BaseException as msg: @@ -466,7 +464,6 @@ $parameters = array( def installWordPress(self): try: - admin = self.extraArgs['admin'] domainName = self.extraArgs['domainName'] home = self.extraArgs['home'] tempStatusPath = self.extraArgs['tempStatusPath'] @@ -476,6 +473,7 @@ $parameters = array( adminPassword = self.extraArgs['adminPassword'] adminEmail = self.extraArgs['adminEmail'] + FNULL = open(os.devnull, 'w') ### Check WP CLI @@ -520,8 +518,8 @@ $parameters = array( dbName, dbUser, dbPassword = self.dbCreation(tempStatusPath, website.master) self.permPath = website.path + except BaseException as msg: - except: website = Websites.objects.get(domain=domainName) externalApp = website.externalApp self.masterDomain = website.domain @@ -544,6 +542,7 @@ $parameters = array( dbName, dbUser, dbPassword = self.dbCreation(tempStatusPath, website) self.permPath = '/home/%s/public_html' % (website.domain) + ## Security Check command = 'chmod 755 %s' % (self.permPath) @@ -567,8 +566,15 @@ $parameters = array( statusFile.writelines('Downloading WordPress Core,30') statusFile.close() - command = "wp core download --allow-root --path=" + finalPath - ProcessUtilities.executioner(command, externalApp) + try: + command = "wp core download --allow-root --path=%s --version=%s" % (finalPath, self.extraArgs['version']) + except: + command = "wp core download --allow-root --path=" + finalPath + + result = ProcessUtilities.outputExecutioner(command, externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) ## @@ -577,7 +583,10 @@ $parameters = array( statusFile.close() command = "wp core config --dbname=" + dbName + " --dbuser=" + dbUser + " --dbpass=" + dbPassword + " --dbhost=%s --dbprefix=wp_ --allow-root --path=" % (ApplicationInstaller.LOCALHOST) + finalPath - ProcessUtilities.executioner(command, externalApp) + result = ProcessUtilities.outputExecutioner(command, externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) if home == '0': path = self.extraArgs['path'] @@ -586,7 +595,10 @@ $parameters = array( finalURL = domainName command = 'wp core install --url="http://' + finalURL + '" --title="' + blogTitle + '" --admin_user="' + adminUser + '" --admin_password="' + adminPassword + '" --admin_email="' + adminEmail + '" --allow-root --path=' + finalPath - ProcessUtilities.executioner(command, externalApp) + result = ProcessUtilities.outputExecutioner(command, externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) ## @@ -595,14 +607,84 @@ $parameters = array( statusFile.close() command = "wp plugin install litespeed-cache --allow-root --path=" + finalPath - ProcessUtilities.executioner(command, externalApp) + result = ProcessUtilities.outputExecutioner(command, externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) statusFile = open(tempStatusPath, 'w') statusFile.writelines('Activating LSCache Plugin,90') statusFile.close() command = "wp plugin activate litespeed-cache --allow-root --path=" + finalPath - ProcessUtilities.executioner(command, externalApp) + result = ProcessUtilities.outputExecutioner(command, externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + + try: + if self.extraArgs['updates']: + if self.extraArgs['updates'] == 'Disabled': + command = "wp config set WP_AUTO_UPDATE_CORE false --raw --allow-root --path=" + finalPath + result = ProcessUtilities.outputExecutioner(command, externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + elif self.extraArgs['updates'] == 'Minor and Security Updates': + command = "wp config set WP_AUTO_UPDATE_CORE minor --allow-root --path=" + finalPath + result = ProcessUtilities.outputExecutioner(command, externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + else: + command = "wp config set WP_AUTO_UPDATE_CORE true --raw --allow-root --path=" + finalPath + result = ProcessUtilities.outputExecutioner(command, externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + except: + pass + + try: + if self.extraArgs['appsSet'] == 'WordPress + LSCache + Classic Editor': + + command = "wp plugin install classic-editor --allow-root --path=" + finalPath + result = ProcessUtilities.outputExecutioner(command, externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines('Activating Classic Editor Plugin,90') + statusFile.close() + + command = "wp plugin activate classic-editor --allow-root --path=" + finalPath + result = ProcessUtilities.outputExecutioner(command, externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + + elif self.extraArgs['appsSet'] == 'WordPress + LSCache + WooCommerce': + + command = "wp plugin install woocommerce --allow-root --path=" + finalPath + result = ProcessUtilities.outputExecutioner(command, externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines('Activating WooCommerce Plugin,90') + statusFile.close() + + command = "wp plugin activate woocommerce --allow-root --path=" + finalPath + result = ProcessUtilities.outputExecutioner(command, externalApp) + + if result.find('Success:') == -1: + raise BaseException(result) + + except: + pass + ## @@ -619,18 +701,10 @@ $parameters = array( except BaseException as msg: # remove the downloaded files - FNULL = open(os.devnull, 'w') - homeDir = "/home/" + domainName + "/public_html" - - if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: - groupName = 'nobody' - else: - groupName = 'nogroup' - - if not os.path.exists(homeDir): - command = "chown " + externalApp + ":" + groupName + " " + homeDir - ProcessUtilities.executioner(command, externalApp) + from filemanager.filemanager import FileManager + fm = FileManager(None, None) + fm.fixPermissions(self.masterDomain) try: mysqlUtilities.deleteDatabase(dbName, dbUser) @@ -639,10 +713,6 @@ $parameters = array( except: pass - command = 'chmod 750 %s' % (self.permPath) - ProcessUtilities.executioner(command) - - statusFile = open(self.tempStatusPath, 'w') statusFile.writelines(str(msg) + " [404]") statusFile.close() @@ -1217,3 +1287,374 @@ $parameters = array( # statusFile.writelines(str(msg) + " [404]") # statusFile.close() # return 0 + + def DeployWordPress(self): + try: + + if self.extraArgs['createSite']: + logging.statusWriter(self.extraArgs['tempStatusPath'], 'Creating this application..,10') + + ## Create site + + import re + from plogical.virtualHostUtilities import virtualHostUtilities + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + externalApp = "".join(re.findall("[a-zA-Z]+", self.extraArgs['domain']))[:5] + str(randint(1000, 9999)) + + virtualHostUtilities.createVirtualHost(self.extraArgs['domain'], self.extraArgs['email'], 'PHP 7.4', + externalApp, 1, 1, 0, + 'admin', 'Default', 0, tempStatusPath, + 0) + result = open(tempStatusPath, 'r').read() + if result.find('[404]') > -1: + logging.statusWriter(self.extraArgs['tempStatusPath'], 'Failed to create application. Error: %s [404]' % (result)) + return 0 + + ## Install WordPress + + logging.statusWriter(self.extraArgs['tempStatusPath'], 'Installing WordPress.,50') + + currentTemp = self.extraArgs['tempStatusPath'] + self.extraArgs['domainName'] = self.extraArgs['domain'] + self.extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + self.extraArgs['blogTitle'] = self.extraArgs['title'] + self.extraArgs['adminUser'] = self.extraArgs['userName'] + self.extraArgs['adminPassword'] = self.extraArgs['password'] + self.extraArgs['adminEmail'] = self.extraArgs['email'] + + self.installWordPress() + + result = open(self.extraArgs['tempStatusPath'], 'r').read() + if result.find('[404]') > -1: + self.extraArgs['tempStatusPath'] = currentTemp + raise BaseException('Failed to install WordPress. Error: %s [404]' % (result)) + + self.extraArgs['tempStatusPath'] = currentTemp + + + logging.statusWriter(self.extraArgs['tempStatusPath'], 'Completed [200].') + + try: + ### Save config in db + + from cloudAPI.models import WPDeployments + from websiteFunctions.models import Websites + import json + + website = Websites.objects.get(domain=self.extraArgs['domain']) + del self.extraArgs['adminPassword'] + del self.extraArgs['password'] + del self.extraArgs['tempStatusPath'] + del self.extraArgs['domain'] + del self.extraArgs['adminEmail'] + del self.extraArgs['adminUser'] + del self.extraArgs['blogTitle'] + del self.extraArgs['appsSet'] + + wpDeploy = WPDeployments(owner=website, config=json.dumps(self.extraArgs)) + wpDeploy.save() + except: + pass + + ## Set up cron if missing + + if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: + localCronPath = "/var/spool/cron/root" + else: + localCronPath = "/var/spool/cron/crontabs/root" + + cronData = open(localCronPath, 'r').read() + + if cronData.find('WPAutoUpdates.py') == -1: + writeToFile = open(localCronPath, 'a') + writeToFile.write('0 12 * * * /usr/local/CyberCP/bin/python /usr/local/CyberCP/plogical/WPAutoUpdates.py\n') + writeToFile.close() + + except BaseException as msg: + self.extraArgs['websiteName'] = self.extraArgs['domain'] + from websiteFunctions.website import WebsiteManager + wm = WebsiteManager() + wm.submitWebsiteDeletion(1, self.extraArgs) + logging.statusWriter(self.extraArgs['tempStatusPath'], '%s [404].' % (str(msg))) + + + def installWhmcs(self): + try: + + admin = self.extraArgs['admin'] + domainName = self.extraArgs['domainName'] + home = self.extraArgs['home'] + firstName = self.extraArgs['firstName'] + lastName = self.extraArgs['lastName'] + email = self.extraArgs['email'] + username = self.extraArgs['username'] + password = self.extraArgs['password'] + whmcs_installer = self.extraArgs['whmcsinstallerpath'] + whmcs_licensekey = self.extraArgs['whmcslicensekey'] + tempStatusPath = self.extraArgs['tempStatusPath'] + self.tempStatusPath = tempStatusPath + + FNULL = open(os.devnull, 'w') + + ## Open Status File + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines('Setting up paths,0') + statusFile.close() + + finalPath = '' + self.permPath = '' + + try: + website = ChildDomains.objects.get(domain=domainName) + externalApp = website.master.externalApp + self.masterDomain = website.master.domain + + if home == '0': + path = self.extraArgs['path'] + finalPath = website.path.rstrip('/') + "/" + path + "/" + else: + finalPath = website.path + "/" + + if website.master.package.dataBases > website.master.databases_set.all().count(): + pass + else: + raise BaseException("Maximum database limit reached for this website.") + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines('Setting up Database,20') + statusFile.close() + + dbName, dbUser, dbPassword = self.dbCreation(tempStatusPath, website.master) + self.permPath = website.path + + except: + website = Websites.objects.get(domain=domainName) + externalApp = website.externalApp + self.masterDomain = website.domain + + if home == '0': + path = self.extraArgs['path'] + finalPath = "/home/" + domainName + "/public_html/" + path + "/" + else: + finalPath = "/home/" + domainName + "/public_html/" + + if website.package.dataBases > website.databases_set.all().count(): + pass + else: + raise BaseException("Maximum database limit reached for this website.") + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines('Setting up Database,20') + statusFile.close() + + dbName, dbUser, dbPassword = self.dbCreation(tempStatusPath, website) + self.permPath = '/home/%s/public_html' % (website.domain) + + ## Security Check + + command = 'chmod 755 %s' % (self.permPath) + ProcessUtilities.executioner(command) + + if finalPath.find("..") > -1: + raise BaseException('Specified path must be inside virtual host home.') + + if not os.path.exists(finalPath): + command = 'mkdir -p ' + finalPath + ProcessUtilities.executioner(command, externalApp) + + ## checking for directories/files + + if self.dataLossCheck(finalPath, tempStatusPath) == 0: + raise BaseException('Directory is not empty.') + + #### + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines('Extracting WHMCS Installer zip..,30') + statusFile.close() + command = "unzip -qq %s -d %s" % (whmcs_installer, finalPath) + ProcessUtilities.executioner(command, externalApp) + + ## + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines('Configuring the installation,40') + statusFile.close() + + if home == '0': + path = self.extraArgs['path'] + # finalURL = domainName + '/' + path + finalURL = domainName + else: + finalURL = domainName + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines('Installing and configuring WHMCS..,60') + statusFile.close() + + command = "chown -R " + externalApp + ":" + groupName + " " + homeDir + ProcessUtilities.executioner(command, externalApp) + + # Walk through whmcs webinstaller via curl with all except errors hidden https://stackoverflow.com/a/49502232 + # Accept EULA and generate configuration.php + command = "curl %s/install/install.php?step=2 --insecure --silent --output /dev/null --show-error --fail" % (finalURL) + ProcessUtilities.executioner(command, externalApp) + + command = "curl %s/install/install.php?step=2 --insecure --silent --output /dev/null --show-error --fail" % (finalURL) + ProcessUtilities.executioner(command, externalApp) + + command = "mv %s/configuration.php.new %s/configuration.php" % (finalPath, finalPath) + ProcessUtilities.executioner(command, externalApp) + + # Post database and license information to webinstaller form + command = """ + curl %s/install/install.php?step=4" \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + --data "licenseKey=%s&databaseHost=localhost&databasePort=&databaseUsername=%s&databasePassword=%s&databaseName=%s" \ + --compressed \ + --insecure \ + --silent \ + --output /dev/null \ + --show-error \ + --fail + """ % (whmcs_licensekey, dbUser, dbPassword, dbName) + + # Post admin user and password information to webinstaller form + command = """ + curl %s/install/install.php?step=5" \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + --data "firstName=%s&lastName=%s&email=%s&username=%s&password=%s&confirmPassword=%s" \ + --compressed \ + --insecure \ + --silent \ + --output /dev/null \ + --show-error \ + --fail + """ % (firstName, lastName, email, username, password, password) + + ## + + command = "rm -rf " + finalPath + "install" + ProcessUtilities.executioner(command, externalApp) + + + ### Update whmcs urls to siteurl + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines('Update whmcs urls to siteurl..,70') + statusFile.close() + + try: + + import MySQLdb.cursors as cursors + import MySQLdb as mysql + + conn = mysql.connect(host='localhost', user=dbUser, passwd=dbPassword, port=3306, + cursorclass=cursors.SSCursor) + cursor = conn.cursor() + + cursor.execute("use %s;UPDATE tblconfiguration SET value='%s' WHERE setting='SystemURL';" % (dbName, finalURL)) + cursor.execute("use %s;UPDATE tblconfiguration SET value='%s' WHERE setting='Domain';" % (dbName, finalURL)) + cursor.execute("use %s;UPDATE tblconfiguration SET value='%s' WHERE setting='SystemSSLURL';" % (dbName, finalURL)) + + conn.close() + except BaseException as msg: + logging.writeToFile(str(msg)) + + + + # Secure WHMCS configuration.php file : https://docs.whmcs.com/Further_Security_Steps#Secure_the_configuration.php_File + command = "chmod 400 %s/configuration.php" % (finalPath) + ProcessUtilities.executioner(command) + + ## + + from filemanager.filemanager import FileManager + + fm = FileManager(None, None) + fm.fixPermissions(self.masterDomain) + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines("Successfully Installed. [200]") + statusFile.close() + return 0 + + + except BaseException as msg: + # remove the downloaded files + + homeDir = "/home/" + domainName + "/public_html" + + if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8: + groupName = 'nobody' + else: + groupName = 'nogroup' + + if not os.path.exists(homeDir): + command = "chown -R " + externalApp + ":" + groupName + " " + homeDir + ProcessUtilities.executioner(command, externalApp) + + try: + mysqlUtilities.deleteDatabase(dbName, dbUser) + db = Databases.objects.get(dbName=dbName) + db.delete() + except: + pass + + command = 'chmod 750 %s' % (self.permPath) + ProcessUtilities.executioner(command) + + statusFile = open(self.tempStatusPath, 'w') + statusFile.writelines(str(msg) + " [404]") + statusFile.close() + return 0 + +def main(): + parser = argparse.ArgumentParser(description='CyberPanel Application Installer') + parser.add_argument('function', help='Specify a function to call!') + parser.add_argument('--tempStatusPath', help='') + parser.add_argument('--appsSet', help='') + parser.add_argument('--domain', help='') + parser.add_argument('--email', help='') + parser.add_argument('--password', help='') + parser.add_argument('--pluginUpdates', help='') + parser.add_argument('--themeUpdates', help='') + parser.add_argument('--title', help='') + parser.add_argument('--updates', help='') + parser.add_argument('--userName', help='') + parser.add_argument('--version', help='') + parser.add_argument('--path', help='') + parser.add_argument('--createSite', help='') + + + args = parser.parse_args() + + if args.function == "DeployWordPress": + + extraArgs = {} + extraArgs['domain'] = args.domain + extraArgs['tempStatusPath'] = args.tempStatusPath + extraArgs['appsSet'] = args.appsSet + extraArgs['email'] = args.email + extraArgs['password'] = args.password + extraArgs['pluginUpdates'] = args.pluginUpdates + extraArgs['themeUpdates'] = args.themeUpdates + extraArgs['title'] = args.title + extraArgs['updates'] = args.updates + extraArgs['userName'] = args.userName + extraArgs['version'] = args.version + extraArgs['createSite'] = int(args.createSite) + + if args.path != None: + extraArgs['path'] = args.path + extraArgs['home'] = '0' + else: + extraArgs['home'] = '1' + + ai = ApplicationInstaller(None, extraArgs) + ai.DeployWordPress() + + +if __name__ == "__main__": + main() diff --git a/plogical/backupManager.py b/plogical/backupManager.py deleted file mode 100644 index 3e2c6fd30..000000000 --- a/plogical/backupManager.py +++ /dev/null @@ -1,1312 +0,0 @@ -#!/usr/local/CyberCP/bin/python -import os -import os.path -import sys -import django -sys.path.append('/usr/local/CyberCP') -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") -django.setup() -import json -from plogical.acl import ACLManager -from plogical import CyberCPLogFileWriter as logging -from websiteFunctions.models import Websites, Backups, dest, backupSchedules -from plogical.virtualHostUtilities import virtualHostUtilities -import subprocess -import shlex -from django.shortcuts import HttpResponse, render -from loginSystem.models import Administrator -from plogical.mailUtilities import mailUtilities -from random import randint -import time -import plogical.backupUtilities as backupUtil -import requests - -class BackupManager: - def __init__(self, domain = None, childDomain = None): - self.domain = domain - self.childDomain = childDomain - - def loadBackupHome(self, request = None, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - return render(request, 'backup/index.html', currentACL) - except BaseException as msg: - return HttpResponse(str(msg)) - - def backupSite(self, request = None, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'createBackup') == 0: - return ACLManager.loadError() - - websitesName = ACLManager.findAllSites(currentACL, userID) - return render(request, 'backup/backup.html', {'websiteList': websitesName}) - except BaseException as msg: - return HttpResponse(str(msg)) - - def restoreSite(self, request = None, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'restoreBackup') == 0: - return ACLManager.loadError() - - path = os.path.join("/home", "backup") - - if not os.path.exists(path): - return render(request, 'backup/restore.html') - else: - all_files = [] - ext = ".tar.gz" - - command = 'sudo chown -R cyberpanel:cyberpanel ' + path - ACLManager.executeCall(command) - - files = os.listdir(path) - for filename in files: - if filename.endswith(ext): - all_files.append(filename) - - return render(request, 'backup/restore.html', {'backups': all_files}) - - except BaseException as msg: - return HttpResponse(str(msg)) - - def getCurrentBackups(self, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - backupDomain = data['websiteToBeBacked'] - - if ACLManager.checkOwnership(backupDomain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('fetchStatus', 0) - - website = Websites.objects.get(domain=backupDomain) - - backups = website.backups_set.all() - - json_data = "[" - checker = 0 - - for items in backups: - if items.status == 0: - status = "Pending" - else: - status = "Completed" - dic = {'id': items.id, - 'file': items.fileName, - 'date': items.date, - 'size': items.size, - 'status': status - } - - 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, 'fetchStatus': 1, 'error_message': "None", "data": json_data}) - return HttpResponse(final_json) - except BaseException as msg: - final_dic = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def submitBackupCreation(self, userID = None, data = None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - backupDomain = data['websiteToBeBacked'] - website = Websites.objects.get(domain=backupDomain) - - if ACLManager.checkOwnership(backupDomain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('metaStatus', 0) - - ## defining paths - - ## /home/example.com/backup - backupPath = os.path.join("/home", backupDomain, "backup/") - domainUser = website.externalApp - backupName = 'backup-' + domainUser + "-" + time.strftime("%I-%M-%S-%a-%b-%Y") - - ## /home/example.com/backup/backup-example-06-50-03-Thu-Feb-2018 - tempStoragePath = os.path.join(backupPath, backupName) - - execPath = "sudo nice -n 10 python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" - execPath = execPath + " submitBackupCreation --tempStoragePath " + tempStoragePath + " --backupName " \ - + backupName + " --backupPath " + backupPath + ' --backupDomain ' + backupDomain - - subprocess.Popen(shlex.split(execPath)) - - time.sleep(2) - - final_json = json.dumps({'status': 1, 'metaStatus': 1, 'error_message': "None", 'tempStorage': tempStoragePath}) - return HttpResponse(final_json) - - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - final_dic = {'status': 0, 'metaStatus': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def backupStatus(self, userID = None, data = None): - try: - - backupDomain = data['websiteToBeBacked'] - status = os.path.join("/home", backupDomain, "backup/status") - - ## read file name - - try: - backupFileNamePath = os.path.join("/home", backupDomain, "backup/backupFileName") - command = "sudo cat " + backupFileNamePath - fileName = subprocess.check_output(shlex.split(command)).decode("utf-8") - except: - fileName = "Fetching.." - - ## file name read ends - - if os.path.exists(status): - command = "sudo cat " + status - status = subprocess.check_output(shlex.split(command)).decode("utf-8") - - if status.find("Completed") > -1: - - command = 'sudo rm -f ' + status - subprocess.call(shlex.split(command)) - - backupOb = Backups.objects.get(fileName=fileName) - backupOb.status = 1 - - ## adding backup data to database. - try: - backupOb.size = str(int(float( - os.path.getsize("/home/" + backupDomain + "/backup/" + fileName + ".tar.gz")) / ( - 1024.0 * 1024.0))) + "MB" - backupOb.save() - except: - backupOb.size = str( - int(os.path.getsize("/home/" + backupDomain + "/backup/" + fileName + ".tar.gz"))) - backupOb.save() - - final_json = json.dumps( - {'backupStatus': 1, 'error_message': "None", "status": status, "abort": 1, - 'fileName': fileName, }) - return HttpResponse(final_json) - - elif status.find("[5009]") > -1: - ## removing status file, so that backup can re-run - try: - command = 'sudo rm -f ' + status - cmd = shlex.split(command) - subprocess.call(cmd) - - backupObs = Backups.objects.filter(fileName=fileName) - for items in backupObs: - items.delete() - - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [backupStatus]") - - final_json = json.dumps( - {'backupStatus': 1, 'fileName': fileName, 'error_message': "None", "status": status, - "abort": 1}) - return HttpResponse(final_json) - else: - final_json = json.dumps( - {'backupStatus': 1, 'error_message': "None", 'fileName': fileName, "status": status, - "abort": 0}) - return HttpResponse(final_json) - else: - final_json = json.dumps({'backupStatus': 0, 'error_message': "None", "status": 0, "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.CyberCPLogFileWriter.writeToFile(str(msg) + " [backupStatus]") - return HttpResponse(final_json) - - def cancelBackupCreation(self, userID = None, data = None): - try: - - backupCancellationDomain = data['backupCancellationDomain'] - fileName = data['fileName'] - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" - - execPath = execPath + " cancelBackupCreation --backupCancellationDomain " + backupCancellationDomain + " --fileName " + fileName - - subprocess.call(shlex.split(execPath)) - - try: - backupOb = Backups.objects.get(fileName=fileName) - backupOb.delete() - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [cancelBackupCreation]") - - final_json = json.dumps({'abortStatus': 1, 'error_message': "None", "status": 0}) - return HttpResponse(final_json) - - except BaseException as msg: - final_dic = {'abortStatus': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def deleteBackup(self, userID = None, data = None): - try: - backupID = data['backupID'] - backup = Backups.objects.get(id=backupID) - - domainName = backup.website.domain - - path = "/home/" + domainName + "/backup/" + backup.fileName + ".tar.gz" - command = 'sudo rm -f ' + path - ACLManager.executeCall(command) - - backup.delete() - - final_json = json.dumps({'status': 1, 'deleteStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - except BaseException as msg: - final_dic = {'status': 0, 'deleteStatus': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - - return HttpResponse(final_json) - - def submitRestore(self, data = None): - try: - backupFile = data['backupFile'] - originalFile = "/home/backup/" + backupFile - - if not os.path.exists(originalFile): - dir = data['dir'] - else: - dir = "CyberPanelRestore" - - execPath = "sudo nice -n 10 python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" - execPath = execPath + " submitRestore --backupFile " + backupFile + " --dir " + dir - subprocess.Popen(shlex.split(execPath)) - time.sleep(4) - - final_dic = {'restoreStatus': 1, 'error_message': "None"} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except BaseException as msg: - final_dic = {'restoreStatus': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def restoreStatus(self, data = None): - try: - backupFile = data['backupFile'].strip(".tar.gz") - - path = os.path.join("/home", "backup", data['backupFile']) - - if os.path.exists(path): - path = os.path.join("/home", "backup", backupFile) - elif os.path.exists(data['backupFile']): - path = data['backupFile'].strip(".tar.gz") - else: - dir = data['dir'] - path = "/home/backup/transfer-" + str(dir) + "/" + backupFile - - if os.path.exists(path): - try: - execPath = "sudo cat " + path + "/status" - status = subprocess.check_output(shlex.split(execPath)).decode("utf-8") - - if status.find("Done") > -1: - - command = "sudo rm -rf " + path - subprocess.call(shlex.split(command)) - - final_json = json.dumps( - {'restoreStatus': 1, 'error_message': "None", "status": status, 'abort': 1, - 'running': 'Completed'}) - return HttpResponse(final_json) - elif status.find("[5009]") > -1: - ## removing temporarily generated files while restoring - command = "sudo rm -rf " + path - subprocess.call(shlex.split(command)) - final_json = json.dumps({'restoreStatus': 1, 'error_message': "None", - "status": status, 'abort': 1, 'alreadyRunning': 0, - 'running': 'Error'}) - return HttpResponse(final_json) - else: - final_json = json.dumps( - {'restoreStatus': 1, 'error_message': "None", "status": status, 'abort': 0, - 'running': 'Running..'}) - return HttpResponse(final_json) - - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - status = "Just Started" - final_json = json.dumps( - {'restoreStatus': 1, 'error_message': "None", "status": status, 'abort': 0, - 'running': 'Running..'}) - return HttpResponse(final_json) - else: - final_json = json.dumps( - {'restoreStatus': 1, 'error_message': "None", "status": "OK To Run", 'running': 'Halted', - 'abort': 1}) - return HttpResponse(final_json) - - except BaseException as msg: - final_dic = {'restoreStatus': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def backupDestinations(self, request = None, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0: - return ACLManager.loadError() - - return render(request, 'backup/backupDestinations.html', {}) - - except BaseException as msg: - return HttpResponse(str(msg)) - - def submitDestinationCreation(self, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0: - return ACLManager.loadErrorJson('destStatus', 0) - - destinations = backupUtil.backupUtilities.destinationsPath - - ipAddress = data['IPAddress'] - password = data['password'] - - if dest.objects.all().count() == 2: - final_dic = {'destStatus': 0, - 'error_message': "Currently only one remote destination is allowed."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - try: - d = dest.objects.get(destLoc=ipAddress) - final_dic = {'destStatus': 0, 'error_message': "This destination already exists."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except: - - try: - port = data['backupSSHPort'] - except: - port = "22" - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" - execPath = execPath + " submitDestinationCreation --ipAddress " + ipAddress + " --password " \ - + password + " --port " + port - - output = subprocess.check_output(shlex.split(execPath)).decode("utf-8") - - if output.find('1,') > -1: - try: - writeToFile = open(destinations, "w") - writeToFile.writelines(ipAddress + "\n") - writeToFile.writelines(data['backupSSHPort'] + "\n") - writeToFile.close() - newDest = dest(destLoc=ipAddress) - newDest.save() - except: - writeToFile = open(destinations, "w") - writeToFile.writelines(ipAddress + "\n") - writeToFile.writelines("22" + "\n") - writeToFile.close() - newDest = dest(destLoc=ipAddress) - newDest.save() - - final_dic = {'destStatus': 1, 'error_message': "None"} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - else: - final_dic = {'destStatus': 0, 'error_message': output} - 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 getCurrentBackupDestinations(self, userID = None, data = None): - try: - - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0: - return ACLManager.loadErrorJson('fetchStatus', 0) - - records = dest.objects.all() - - json_data = "[" - checker = 0 - - for items in records: - if items.destLoc == "Home": - continue - dic = {'id': items.id, - 'ip': items.destLoc, - } - - 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({'fetchStatus': 1, 'error_message': "None", "data": json_data}) - return HttpResponse(final_json) - - except BaseException as msg: - final_dic = {'fetchStatus': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def getConnectionStatus(self, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0: - return ACLManager.loadErrorJson('connStatus', 0) - - ipAddress = data['IPAddress'] - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" - execPath = execPath + " getConnectionStatus --ipAddress " + ipAddress - - output = subprocess.check_output(shlex.split(execPath)).decode("utf-8") - - if output.find('1,') > -1: - final_dic = {'connStatus': 1, 'error_message': "None"} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - else: - final_dic = {'connStatus': 0, 'error_message': output} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - except BaseException as msg: - final_dic = {'connStatus': 1, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def deleteDestination(self, userID = None, data = None): - try: - - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0: - return ACLManager.loadErrorJson('delStatus', 0) - - ipAddress = data['IPAddress'] - - delDest = dest.objects.get(destLoc=ipAddress) - delDest.delete() - - path = "/usr/local/CyberCP/backup/" - destinations = path + "destinations" - - data = open(destinations, 'r').readlines() - - writeToFile = open(destinations, 'r') - - for items in data: - if items.find(ipAddress) > -1: - continue - else: - writeToFile.writelines(items) - - writeToFile.close() - - ## Deleting Cron Tab Entries for this destination - - path = "/etc/crontab" - - data = open(path, 'r').readlines() - - writeToFile = open(path, 'w') - - for items in data: - if items.find("backupSchedule.py") > -1: - continue - else: - writeToFile.writelines(items) - - writeToFile.close() - - final_dic = {'delStatus': 1, 'error_message': "None"} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - except BaseException as msg: - final_dic = {'delStatus': 1, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def scheduleBackup(self, request, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: - return ACLManager.loadError() - - if dest.objects.all().count() <= 1: - try: - homeDest = dest(destLoc="Home") - homeDest.save() - except: - pass - backups = dest.objects.all() - - destinations = [] - - for items in backups: - destinations.append(items.destLoc) - - return render(request, 'backup/backupSchedule.html', {'destinations': destinations}) - - except BaseException as msg: - return HttpResponse(str(msg)) - - def getCurrentBackupSchedules(self, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: - return ACLManager.loadErrorJson('fetchStatus', 0) - - records = backupSchedules.objects.all() - - json_data = "[" - checker = 0 - - for items in records: - dic = {'id': items.id, - 'destLoc': items.dest.destLoc, - 'frequency': items.frequency, - } - - 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({'fetchStatus': 1, 'error_message': "None", "data": json_data}) - return HttpResponse(final_json) - - except BaseException as msg: - final_dic = {'fetchStatus': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def submitBackupSchedule(self, userID = None, data = None): - try: - backupDest = data['backupDest'] - backupFreq = data['backupFreq'] - - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: - return ACLManager.loadErrorJson('scheduleStatus', 0) - - path = "/etc/crontab" - - ## check if already exists - try: - schedule = backupSchedules.objects.get(frequency=backupFreq) - if schedule.dest.destLoc == backupDest: - final_json = json.dumps( - {'scheduleStatus': 0, 'error_message': "This schedule already exists"}) - return HttpResponse(final_json) - else: - if backupDest == "Home" and backupFreq == "Daily": - cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py" - - virtualHostUtilities.permissionControl(path) - - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - command = "sudo systemctl restart crond" - - subprocess.call(shlex.split(command)) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() - - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - - elif backupDest == "Home" and backupFreq == "Weekly": - cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py " - - virtualHostUtilities.permissionControl(path) - - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - command = "sudo systemctl restart crond" - - subprocess.call(shlex.split(command)) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() - - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - - elif backupDest != "Home" and backupFreq == "Daily": - cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupSchedule.py" - - virtualHostUtilities.permissionControl(path) - - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - command = "sudo systemctl restart crond" - - subprocess.call(shlex.split(command)) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() - - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - - elif backupDest != "Home" and backupFreq == "Weekly": - cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupSchedule.py " - - virtualHostUtilities.permissionControl(path) - - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - command = "sudo systemctl restart crond" - - subprocess.call(shlex.split(command)) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() - - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - except: - if backupDest == "Home" and backupFreq == "Daily": - cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py" - - virtualHostUtilities.permissionControl(path) - - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - command = "sudo systemctl restart crond" - - subprocess.call(shlex.split(command)) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() - - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - - elif backupDest == "Home" and backupFreq == "Weekly": - cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py " - - virtualHostUtilities.permissionControl(path) - - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - command = "sudo systemctl restart crond" - - subprocess.call(shlex.split(command)) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() - - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - - elif backupDest != "Home" and backupFreq == "Daily": - cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupSchedule.py" - - virtualHostUtilities.permissionControl(path) - - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - command = "sudo systemctl restart crond" - - subprocess.call(shlex.split(command)) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() - - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - - elif backupDest != "Home" and backupFreq == "Weekly": - cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupSchedule.py " - - virtualHostUtilities.permissionControl(path) - - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - command = "sudo systemctl restart crond" - - subprocess.call(shlex.split(command)) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() - - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - - except BaseException as msg: - final_json = json.dumps({'scheduleStatus': 0, 'error_message': str(msg)}) - return HttpResponse(final_json) - - def scheduleDelete(self, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: - return ACLManager.loadErrorJson('scheduleStatus', 0) - - backupDest = data['destLoc'] - backupFreq = data['frequency'] - - path = "/etc/crontab" - - if backupDest == "Home" and backupFreq == "Daily": - - virtualHostUtilities.permissionControl(path) - - data = open(path, "r").readlines() - writeToFile = open(path, 'w') - - for items in data: - if items.find("0-6") > -1 and items.find("backupScheduleLocal.py") > -1: - continue - else: - writeToFile.writelines(items) - - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - command = "sudo systemctl restart crond" - - subprocess.call(shlex.split(command)) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules.objects.get(dest=destination, frequency=backupFreq) - newSchedule.delete() - - final_json = json.dumps({'delStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - - elif backupDest == "Home" and backupFreq == "Weekly": - - virtualHostUtilities.permissionControl(path) - - data = open(path, "r").readlines() - writeToFile = open(path, 'w') - - for items in data: - if items.find("* 3") > -1 and items.find("backupScheduleLocal.py") > -1: - continue - else: - writeToFile.writelines(items) - - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - command = "sudo systemctl restart crond" - - subprocess.call(shlex.split(command)) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules.objects.get(dest=destination, frequency=backupFreq) - newSchedule.delete() - - final_json = json.dumps({'delStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - - elif backupDest != "Home" and backupFreq == "Daily": - - virtualHostUtilities.permissionControl(path) - - data = open(path, "r").readlines() - writeToFile = open(path, 'w') - - for items in data: - if items.find("0-6") > -1 and items.find("backupSchedule.py") > -1: - continue - else: - writeToFile.writelines(items) - - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - command = "sudo systemctl restart crond" - - subprocess.call(shlex.split(command)) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules.objects.get(dest=destination, frequency=backupFreq) - newSchedule.delete() - - final_json = json.dumps({'delStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - - elif backupDest != "Home" and backupFreq == "Weekly": - - virtualHostUtilities.permissionControl(path) - - data = open(path, "r").readlines() - writeToFile = open(path, 'w') - - for items in data: - if items.find("* 3") > -1 and items.find("backupSchedule.py") > -1: - continue - else: - writeToFile.writelines(items) - - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - command = "sudo systemctl restart crond" - - subprocess.call(shlex.split(command)) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules.objects.get(dest=destination, frequency=backupFreq) - newSchedule.delete() - - final_json = json.dumps({'delStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - - except BaseException as msg: - final_json = json.dumps({'delStatus': 0, 'error_message': str(msg)}) - return HttpResponse(final_json) - - def remoteBackups(self, request, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: - return ACLManager.loadError() - - return render(request, 'backup/remoteBackups.html') - - except BaseException as msg: - return HttpResponse(str(msg)) - - def submitRemoteBackups(self, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: - return ACLManager.loadErrorJson() - - ipAddress = data['ipAddress'] - password = data['password'] - - ## Ask for Remote version of CyberPanel - - try: - finalData = json.dumps({'username': "admin", "password": password}) - - url = "https://" + ipAddress + ":8090/api/cyberPanelVersion" - - r = requests.post(url, data=finalData, verify=False) - - data = json.loads(r.text) - - if data['getVersion'] == 1: - - if float(data['currentVersion']) >= 1.6 and data['build'] >= 0: - pass - else: - data_ret = {'status': 0, - 'error_message': "Your version does not match with version of remote server.", - "dir": "Null"} - data_ret = json.dumps(data_ret) - return HttpResponse(data_ret) - else: - data_ret = {'status': 0, - 'error_message': "Not able to fetch version of remote server. Error Message: " + - data[ - 'error_message'], "dir": "Null"} - data_ret = json.dumps(data_ret) - return HttpResponse(data_ret) - - - except BaseException as msg: - data_ret = {'status': 0, - 'error_message': "Not able to fetch version of remote server. Error Message: " + str( - msg), - "dir": "Null"} - data_ret = json.dumps(data_ret) - return HttpResponse(data_ret) - - ## Fetch public key of remote server! - - finalData = json.dumps({'username': "admin", "password": password}) - - url = "https://" + ipAddress + ":8090/api/fetchSSHkey" - r = requests.post(url, data=finalData, verify=False) - data = json.loads(r.text) - - if data['pubKeyStatus'] == 1: - pubKey = data["pubKey"].strip("\n") - else: - final_json = json.dumps({'status': 0, - 'error_message': "I am sorry, I could not fetch key from remote server. Error Message: " + - data['error_message'] - }) - return HttpResponse(final_json) - - ## write key - - ## Writing key to a temporary location, to be read later by backup process. - - mailUtilities.checkHome() - - pathToKey = "/home/cyberpanel/" + str(randint(1000, 9999)) - - vhost = open(pathToKey, "w") - vhost.write(pubKey) - vhost.close() - - ## - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/remoteTransferUtilities.py" - execPath = execPath + " writeAuthKey --pathToKey " + pathToKey - output = subprocess.check_output(shlex.split(execPath)).decode("utf-8") - - if output.find("1,None") > -1: - pass - else: - final_json = json.dumps({'status': 0, 'error_message': output}) - return HttpResponse(final_json) - - ## - - try: - finalData = json.dumps({'username': "admin", "password": password}) - - url = "https://" + ipAddress + ":8090/api/fetchAccountsFromRemoteServer" - - r = requests.post(url, data=finalData, verify=False) - - data = json.loads(r.text) - - if data['fetchStatus'] == 1: - json_data = data['data'] - data_ret = {'status': 1, 'error_message': "None", - "dir": "Null", 'data': json_data} - data_ret = json.dumps(data_ret) - return HttpResponse(data_ret) - else: - data_ret = {'status': 0, - 'error_message': "Not able to fetch accounts from remote server. Error Message: " + - data['error_message'], "dir": "Null"} - data_ret = json.dumps(data_ret) - return HttpResponse(data_ret) - except BaseException as msg: - data_ret = {'status': 0, - 'error_message': "Not able to fetch accounts from remote server. Error Message: " + str( - msg), "dir": "Null"} - data_ret = json.dumps(data_ret) - return HttpResponse(data_ret) - - except BaseException as msg: - final_json = json.dumps({'status': 0, 'error_message': str(msg)}) - return HttpResponse(final_json) - - def starRemoteTransfer(self, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: - return ACLManager.loadErrorJson('remoteTransferStatus', 0) - - ipAddress = data['ipAddress'] - password = data['password'] - accountsToTransfer = data['accountsToTransfer'] - - try: - - ipFile = os.path.join("/etc", "cyberpanel", "machineIP") - f = open(ipFile) - ownIP = f.read() - - finalData = json.dumps({'username': "admin", "password": password, "ipAddress": ownIP, - "accountsToTransfer": accountsToTransfer}) - - url = "https://" + ipAddress + ":8090/api/remoteTransfer" - - r = requests.post(url, data=finalData, verify=False) - - data = json.loads(r.text) - - if data['transferStatus'] == 1: - - ## Create local backup dir - - localBackupDir = os.path.join("/home", "backup") - - if not os.path.exists(localBackupDir): - command = "sudo mkdir " + localBackupDir - subprocess.call(shlex.split(command)) - - ## create local directory that will host backups - - localStoragePath = "/home/backup/transfer-" + str(data['dir']) - - ## making local storage directory for backups - - command = "sudo mkdir " + localStoragePath - subprocess.call(shlex.split(command)) - - final_json = json.dumps( - {'remoteTransferStatus': 1, 'error_message': "None", "dir": data['dir']}) - return HttpResponse(final_json) - else: - final_json = json.dumps({'remoteTransferStatus': 0, - 'error_message': "Can not initiate remote transfer. Error message: " + - data['error_message']}) - return HttpResponse(final_json) - - except BaseException as msg: - final_json = json.dumps({'remoteTransferStatus': 0, - 'error_message': "Can not initiate remote transfer. Error message: " + - str(msg)}) - return HttpResponse(final_json) - - except BaseException as msg: - final_json = json.dumps({'remoteTransferStatus': 0, 'error_message': str(msg)}) - return HttpResponse(final_json) - - def getRemoteTransferStatus(self, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: - return ACLManager.loadErrorJson('remoteTransferStatus', 0) - - ipAddress = data['ipAddress'] - password = data['password'] - dir = data['dir'] - username = "admin" - - finalData = json.dumps({'dir': dir, "username": username, "password": password}) - r = requests.post("https://" + ipAddress + ":8090/api/FetchRemoteTransferStatus", data=finalData, - verify=False) - - data = json.loads(r.text) - - if data['fetchStatus'] == 1: - if data['status'].find("Backups are successfully generated and received on") > -1: - - data = {'remoteTransferStatus': 1, 'error_message': "None", "status": data['status'], - 'backupsSent': 1} - json_data = json.dumps(data) - return HttpResponse(json_data) - elif data['status'].find("[5010]") > -1: - data = {'remoteTransferStatus': 0, 'error_message': data['status'], - 'backupsSent': 0} - json_data = json.dumps(data) - return HttpResponse(json_data) - else: - data = {'remoteTransferStatus': 1, 'error_message': "None", "status": data['status'], - 'backupsSent': 0} - json_data = json.dumps(data) - return HttpResponse(json_data) - else: - data = {'remoteTransferStatus': 0, 'error_message': data['error_message'], - 'backupsSent': 0} - json_data = json.dumps(data) - return HttpResponse(json_data) - except BaseException as msg: - data = {'remoteTransferStatus': 0, 'error_message': str(msg), 'backupsSent': 0} - json_data = json.dumps(data) - return HttpResponse(json_data) - - def remoteBackupRestore(self, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: - return ACLManager.loadErrorJson('remoteTransferStatus', 0) - - backupDir = data['backupDir'] - - backupDirComplete = "/home/backup/transfer-" + str(backupDir) - # adminEmail = admin.email - - ## - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/remoteTransferUtilities.py" - - execPath = execPath + " remoteBackupRestore --backupDirComplete " + backupDirComplete + " --backupDir " + str( - backupDir) - - subprocess.Popen(shlex.split(execPath)) - - time.sleep(3) - - data = {'remoteRestoreStatus': 1, 'error_message': 'None'} - json_data = json.dumps(data) - return HttpResponse(json_data) - - except BaseException as msg: - data = {'remoteRestoreStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data) - return HttpResponse(json_data) - - def localRestoreStatus(self, userID = None, data = None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: - return ACLManager.loadErrorJson('remoteTransferStatus', 0) - - backupDir = data['backupDir'] - - # admin = Administrator.objects.get(userName=username) - backupLogPath = "/home/backup/transfer-" + backupDir + "/" + "backup_log" - - removalPath = "/home/backup/transfer-" + str(backupDir) - - time.sleep(3) - - if os.path.isfile(backupLogPath): - command = "sudo cat " + backupLogPath - status = subprocess.check_output(shlex.split(command)).decode("utf-8") - - if status.find("completed[success]") > -1: - command = "sudo rm -rf " + removalPath - # subprocess.call(shlex.split(command)) - data_ret = {'remoteTransferStatus': 1, 'error_message': "None", "status": status, "complete": 1} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - elif status.find("[5010]") > -1: - command = "sudo rm -rf " + removalPath - # subprocess.call(shlex.split(command)) - data = {'remoteTransferStatus': 0, 'error_message': status, - "status": "None", "complete": 0} - json_data = json.dumps(data) - return HttpResponse(json_data) - else: - data_ret = {'remoteTransferStatus': 1, 'error_message': "None", "status": status, "complete": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'remoteTransferStatus': 0, 'error_message': "No such log found", "status": "None", - "complete": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException as msg: - data = {'remoteTransferStatus': 0, 'error_message': str(msg), "status": "None", "complete": 0} - json_data = json.dumps(data) - return HttpResponse(json_data) - - def cancelRemoteBackup(self, userID = None, data = None): - try: - - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: - return ACLManager.loadErrorJson('cancelStatus', 0) - - ipAddress = data['ipAddress'] - password = data['password'] - dir = data['dir'] - username = "admin" - - finalData = json.dumps({'dir': dir, "username": username, "password": password}) - r = requests.post("https://" + ipAddress + ":8090/api/cancelRemoteTransfer", data=finalData, - verify=False) - - data = json.loads(r.text) - - if data['cancelStatus'] == 1: - pass - else: - logging.CyberCPLogFileWriter.writeToFile( - "Some error cancelling at remote server, see the log file for remote server.") - - path = "/home/backup/transfer-" + str(dir) - pathpid = path + "/pid" - - command = "sudo cat " + pathpid - pid = subprocess.check_output(shlex.split(command)).decode("utf-8") - - command = "sudo kill -KILL " + pid - subprocess.call(shlex.split(command)) - - command = "sudo rm -rf " + path - subprocess.call(shlex.split(command)) - - data = {'cancelStatus': 1, 'error_message': "None"} - json_data = json.dumps(data) - return HttpResponse(json_data) - - except BaseException as msg: - data = {'cancelStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data) - return HttpResponse(json_data) diff --git a/plogical/backupUtilities.py b/plogical/backupUtilities.py index a2654ca8c..6df1ee58b 100755 --- a/plogical/backupUtilities.py +++ b/plogical/backupUtilities.py @@ -48,8 +48,8 @@ try: except: pass -VERSION = '2.0' -BUILD = 3 +VERSION = '2.1' +BUILD = 1 ## I am not the monster that you think I am.. @@ -1425,7 +1425,7 @@ class backupUtilities: self.cpu = backupUtilities.CPUDefault self.time = int(backupUtilities.time) - self.BackupPath = '/home/cyberpanel/backups/%s/backup-' % (self.extraArgs['domain']) + self.extraArgs['domain'] + "-" + time.strftime("%m.%d.%Y_%H-%M-%S") + self.BackupPath = self.extraArgs['path'] self.website = Websites.objects.get(domain=self.extraArgs['domain']) command = 'mkdir -p %s' % (self.BackupPath) @@ -1486,6 +1486,13 @@ class backupUtilities: command = 'chmod 600:600 %s' % (finalPath) ProcessUtilities.executioner(command) + if self.extraArgs['port'] != 0: + logging.CyberCPLogFileWriter.statusWriter(self.extraArgs['tempStatusPath'], + 'Sending file to destination server..,90') + + command = "scp -o StrictHostKeyChecking=no -P %s -i /root/.ssh/cyberpanel %s root@%s:/home/cyberpanel/backups/%s/" % (self.extraArgs['port'], finalPath, self.extraArgs['ip'], self.extraArgs['destinationDomain']) + ProcessUtilities.outputExecutioner(command) + logging.CyberCPLogFileWriter.statusWriter(self.extraArgs['tempStatusPath'], 'Completed [200].') return 1, self.BackupPath + '.tar.gz' @@ -1548,9 +1555,14 @@ class backupUtilities: command = 'rm -rf %s' % (homePath) ProcessUtilities.executioner(command) - command = 'mv %s/%s %s' % (self.dataPath, self.website.domain, '/home') + if self.extraArgs['sourceDomain'] == 'None': + command = 'mv %s/%s %s' % (self.dataPath, self.website.domain, '/home') + else: + command = 'mv %s/%s %s/%s' % (self.dataPath, self.extraArgs['sourceDomain'], '/home', self.extraArgs['domain']) + ProcessUtilities.executioner(command) + from filemanager.filemanager import FileManager fm = FileManager(None, None) @@ -1614,6 +1626,34 @@ class backupUtilities: mysqlUtilities.mysqlUtilities.restoreDatabaseBackup(db['databaseName'], self.databasesPath, db['password']) + if self.extraArgs['sourceDomain'] != 'None': + if self.extraArgs['sourceDomain'] != self.extraArgs['domain']: + + try: + command = 'wp --info' + outout = ProcessUtilities.outputExecutioner(command) + + if not outout.find('WP-CLI root dir:') > -1: + from plogical.applicationInstaller import ApplicationInstaller + ai = ApplicationInstaller(None, None) + ai.installWPCLI() + except subprocess.CalledProcessError: + from plogical.applicationInstaller import ApplicationInstaller + ai = ApplicationInstaller(None, None) + ai.installWPCLI() + + path = '/home/%s/public_html' % (self.extraArgs['domain']) + command = "wp search-replace '%s' '%s' --path=%s --allow-root" % (self.extraArgs['sourceDomain'], self.extraArgs['domain'], path) + ProcessUtilities.outputExecutioner(command) + + command = "wp search-replace 'www.%s' '%s' --path=%s --allow-root" % ( + self.extraArgs['sourceDomain'], self.extraArgs['domain'], path) + ProcessUtilities.outputExecutioner(command) + + command = "wp search-replace 'www.%s' '%s' --path=%s --allow-root" % ( + self.extraArgs['domain'], self.extraArgs['domain'], path) + ProcessUtilities.outputExecutioner(command) + command = 'rm -rf %s' % (self.extractedPath) ProcessUtilities.executioner(command) @@ -1661,10 +1701,18 @@ class backupUtilities: aws_access_key_id, aws_secret_access_key, region = self.fetchAWSKeys() - s3 = boto3.resource( + if region.find('http') > -1: + s3 = boto3.resource( 's3', aws_access_key_id=aws_access_key_id, - aws_secret_access_key=aws_secret_access_key + aws_secret_access_key=aws_secret_access_key, + endpoint_url=region + ) + else: + s3 = boto3.resource( + 's3', + aws_access_key_id=aws_access_key_id, + aws_secret_access_key=aws_secret_access_key, ) self.BackupPath = '/home/cyberpanel/backups/%s/%s' % (self.extraArgs['domain'], self.extraArgs['backupFile'].split('/')[-1]) @@ -2030,6 +2078,10 @@ def main(): parser.add_argument('--data', help='') parser.add_argument('--emails', help='') parser.add_argument('--databases', help='') + parser.add_argument('--path', help='') + parser.add_argument('--ip', help='') + parser.add_argument('--sourceDomain', help='') + parser.add_argument('--destinationDomain', help='') ## FOR S3 @@ -2059,13 +2111,19 @@ def main(): extraArgs['data'] = int(args.data) extraArgs['emails'] = int(args.emails) extraArgs['databases'] = int(args.databases) + extraArgs['path'] = args.path + extraArgs['port'] = args.port + extraArgs['ip'] = args.ip + extraArgs['destinationDomain'] = args.destinationDomain bu = backupUtilities(extraArgs) bu.CloudBackups() + elif args.function == 'SubmitCloudBackupRestore': extraArgs = {} extraArgs['domain'] = args.backupDomain extraArgs['tempStatusPath'] = args.tempStoragePath extraArgs['backupFile'] = args.backupFile + extraArgs['sourceDomain'] = args.sourceDomain bu = backupUtilities(extraArgs) bu.SubmitCloudBackupRestore() elif args.function == 'SubmitS3BackupRestore': @@ -2077,6 +2135,5 @@ def main(): bu = backupUtilities(extraArgs) bu.SubmitS3BackupRestore() - if __name__ == "__main__": main() diff --git a/plogical/dnsUtilities.py b/plogical/dnsUtilities.py index e63f66e9e..4120740c5 100755 --- a/plogical/dnsUtilities.py +++ b/plogical/dnsUtilities.py @@ -41,7 +41,7 @@ class DNS: self.status = data[2].rstrip('\n') return 1 else: - logging.CyberCPLogFileWriter.writeToFile('User %s does not have CoudFlare configured.' % (self.admin.userName)) + logging.CyberCPLogFileWriter.writeToFile('User %s does not have CloudFlare configured.' % (self.admin.userName)) return 0 def cfTemplate(self, zoneDomain, admin, enableCheck=None): @@ -637,8 +637,12 @@ class DNS: record.save() if ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu or ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu20: - command = 'sudo systemctl restart pdns' - ProcessUtilities.executioner(command) + command = 'ls -la /etc/systemd/system/multi-user.target.wants/pdns.service' + result = ProcessUtilities.outputExecutioner(command) + + if result.find('No such file') == -1: + command = 'sudo systemctl restart pdns' + ProcessUtilities.executioner(command) return @@ -656,8 +660,12 @@ class DNS: record.save() if ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu or ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu20: - command = 'sudo systemctl restart pdns' - ProcessUtilities.executioner(command) + command = 'ls -la /etc/systemd/system/multi-user.target.wants/pdns.service' + result = ProcessUtilities.outputExecutioner(command) + + if result.find('No such file') == -1: + command = 'sudo systemctl restart pdns' + ProcessUtilities.executioner(command) return if type == 'MX': @@ -673,8 +681,12 @@ class DNS: record.save() if ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu or ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu20: - command = 'sudo systemctl restart pdns' - ProcessUtilities.executioner(command) + command = 'ls -la /etc/systemd/system/multi-user.target.wants/pdns.service' + result = ProcessUtilities.outputExecutioner(command) + + if result.find('No such file') == -1: + command = 'sudo systemctl restart pdns' + ProcessUtilities.executioner(command) return if Records.objects.filter(name=name, type=type).count() == 0: @@ -689,8 +701,13 @@ class DNS: auth=1) record.save() if ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu or ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu20: - command = 'sudo systemctl restart pdns' - ProcessUtilities.executioner(command) + + command = 'ls -la /etc/systemd/system/multi-user.target.wants/pdns.service' + result = ProcessUtilities.outputExecutioner(command) + + if result.find('No such file') == -1: + command = 'sudo systemctl restart pdns' + ProcessUtilities.executioner(command) ## Add Record to CF if SYNC Enabled diff --git a/plogical/httpProc.py b/plogical/httpProc.py index 61518e85c..5b94b0ff9 100755 --- a/plogical/httpProc.py +++ b/plogical/httpProc.py @@ -4,10 +4,45 @@ from django.shortcuts import render, HttpResponse import json class httpProc: - def __init__(self, request, templateName, data = None): + def __init__(self, request, templateName, data = None, function = None): self.request = request self.templateName = templateName self.data = data + self.function = function + + + def render(self): + try: + from loginSystem.models import Administrator + from plogical.acl import ACLManager + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + ### Permissions Check + + if self.function != None: + if not currentACL['admin']: + if not currentACL[self.function]: + templateName = 'baseTemplate/error.html' + return render(self.request, templateName, {'error_message': 'You are not authorized to access %s' % (self.function)}) + + ### + + if self.data == None: + self.data = {} + + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + self.data['ipAddress'] = ipAddress + + self.data.update(currentACL) + + return render(self.request, self.templateName, self.data) + except BaseException as msg: + templateName = 'baseTemplate/error.html' + return render(self.request, templateName, {'error_message': str(msg)}) def renderPre(self): if self.data == None: @@ -42,3 +77,6 @@ class httpProc: final_json = json.dumps(final_dic) return HttpResponse(final_json) + + + diff --git a/plogical/mysqlUtilities.py b/plogical/mysqlUtilities.py index 81c8fb9ac..71e75a7b0 100755 --- a/plogical/mysqlUtilities.py +++ b/plogical/mysqlUtilities.py @@ -960,6 +960,27 @@ skip-name-resolve logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[addUserToDB]") return 0 + @staticmethod + def UpdateWPTempPassword(dbname, password): + try: + + ## + + connection, cursor = mysqlUtilities.setupConnection() + + if connection == 0: + return 0 + + cursor.execute("use %s" % (dbname)) + cursor.execute("UPDATE `wp_users` SET `user_pass`= MD5('%s') WHERE `user_login`='usman'" % (password)) + connection.close() + + return 1 + + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[deleteDatabase]") + return str(msg) + def main(): parser = argparse.ArgumentParser(description='CyberPanel') parser.add_argument('function', help='Specific a function to call!') diff --git a/plogical/sslUtilities.py b/plogical/sslUtilities.py index 961afa096..af96da488 100755 --- a/plogical/sslUtilities.py +++ b/plogical/sslUtilities.py @@ -64,6 +64,14 @@ class sslUtilities: @staticmethod def installSSLForDomain(virtualHostName, adminEmail='usman@cyberpersons.com'): + + try: + website = Websites.objects.get(domain=virtualHostName) + adminEmail = website.adminEmail + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile('%s [installSSLForDomain:72]' % (str(msg))) + + if ProcessUtilities.decideServer() == ProcessUtilities.OLS: confPath = sslUtilities.Server_root + "/conf/vhosts/" + virtualHostName completePathToConfigFile = confPath + "/vhost.conf" diff --git a/plogical/test.py b/plogical/test.py old mode 100755 new mode 100644 diff --git a/plogical/test1.py b/plogical/test1.py old mode 100755 new mode 100644 diff --git a/plogical/upgrade.py b/plogical/upgrade.py index 5ddd6d4d2..a30ad69dc 100755 --- a/plogical/upgrade.py +++ b/plogical/upgrade.py @@ -2,6 +2,7 @@ import os import os.path import sys import argparse + sys.path.append('/usr/local/CyberCP') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") import shlex @@ -13,17 +14,50 @@ from CyberCP import settings import random import string -VERSION = '2.0' -BUILD = 3 +VERSION = '2.1' +BUILD = 1 CENTOS7 = 0 CENTOS8 = 1 +Ubuntu18 = 2 +Ubuntu20 = 3 +CloudLinux7 = 4 +CloudLinux8 = 5 + class Upgrade: logPath = "/usr/local/lscp/logs/upgradeLog" cdn = 'cdn.cyberpanel.sh' installedOutput = '' CentOSPath = '/etc/redhat-release' + UbuntuPath = '/etc/lsb-release' + + AdminACL = '{"adminStatus":1, "versionManagement": 1, "createNewUser": 1, "listUsers": 1, "deleteUser":1 , "resellerCenter": 1, ' \ + '"changeUserACL": 1, "createWebsite": 1, "modifyWebsite": 1, "suspendWebsite": 1, "deleteWebsite": 1, ' \ + '"createPackage": 1, "listPackages": 1, "deletePackage": 1, "modifyPackage": 1, "createDatabase": 1, "deleteDatabase": 1, ' \ + '"listDatabases": 1, "createNameServer": 1, "createDNSZone": 1, "deleteZone": 1, "addDeleteRecords": 1, ' \ + '"createEmail": 1, "listEmails": 1, "deleteEmail": 1, "emailForwarding": 1, "changeEmailPassword": 1, ' \ + '"dkimManager": 1, "createFTPAccount": 1, "deleteFTPAccount": 1, "listFTPAccounts": 1, "createBackup": 1,' \ + ' "restoreBackup": 1, "addDeleteDestinations": 1, "scheDuleBackups": 1, "remoteBackups": 1, "googleDriveBackups": 1, "manageSSL": 1, ' \ + '"hostnameSSL": 1, "mailServerSSL": 1 }' + + ResellerACL = '{"adminStatus":0, "versionManagement": 1, "createNewUser": 1, "listUsers": 1, "deleteUser": 1 , "resellerCenter": 1, ' \ + '"changeUserACL": 0, "createWebsite": 1, "modifyWebsite": 1, "suspendWebsite": 1, "deleteWebsite": 1, ' \ + '"createPackage": 1, "listPackages": 1, "deletePackage": 1, "modifyPackage": 1, "createDatabase": 1, "deleteDatabase": 1, ' \ + '"listDatabases": 1, "createNameServer": 1, "createDNSZone": 1, "deleteZone": 1, "addDeleteRecords": 1, ' \ + '"createEmail": 1, "listEmails": 1, "deleteEmail": 1, "emailForwarding": 1, "changeEmailPassword": 1, ' \ + '"dkimManager": 1, "createFTPAccount": 1, "deleteFTPAccount": 1, "listFTPAccounts": 1, "createBackup": 1,' \ + ' "restoreBackup": 1, "addDeleteDestinations": 0, "scheDuleBackups": 0, "remoteBackups": 0, "googleDriveBackups": 1, "manageSSL": 1, ' \ + '"hostnameSSL": 0, "mailServerSSL": 0 }' + + UserACL = '{"adminStatus":0, "versionManagement": 1, "createNewUser": 0, "listUsers": 0, "deleteUser": 0 , "resellerCenter": 0, ' \ + '"changeUserACL": 0, "createWebsite": 0, "modifyWebsite": 0, "suspendWebsite": 0, "deleteWebsite": 0, ' \ + '"createPackage": 0, "listPackages": 0, "deletePackage": 0, "modifyPackage": 0, "createDatabase": 1, "deleteDatabase": 1, ' \ + '"listDatabases": 1, "createNameServer": 0, "createDNSZone": 1, "deleteZone": 1, "addDeleteRecords": 1, ' \ + '"createEmail": 1, "listEmails": 1, "deleteEmail": 1, "emailForwarding": 1, "changeEmailPassword": 1, ' \ + '"dkimManager": 1, "createFTPAccount": 1, "deleteFTPAccount": 1, "listFTPAccounts": 1, "createBackup": 1,' \ + ' "restoreBackup": 0, "addDeleteDestinations": 0, "scheDuleBackups": 0, "remoteBackups": 0, "googleDriveBackups": 1, "manageSSL": 1, ' \ + '"hostnameSSL": 0, "mailServerSSL": 0 }' @staticmethod def decideCentosVersion(): @@ -33,6 +67,25 @@ class Upgrade: else: return CENTOS7 + @staticmethod + def FindOperatingSytem(): + + if os.path.exists(Upgrade.CentOSPath): + result = open(Upgrade.CentOSPath, 'r').read() + + if result.find('CentOS Linux release 8') > -1 or result.find('CloudLinux release 8') > -1: + return CENTOS8 + else: + return CENTOS7 + else: + result = open(Upgrade.UbuntuPath, 'r').read() + + if result.find('20.04') > -1: + return Ubuntu20 + else: + return Ubuntu18 + + @staticmethod def stdOut(message, do_exit=0): print("\n\n") @@ -615,6 +668,28 @@ imap_folder_list_limit = 0 except: pass + try: + cursor.execute('ALTER TABLE loginSystem_acl ADD config longtext') + except: + pass + + try: + cursor.execute("UPDATE loginSystem_acl SET config = '%s' where name = 'admin'" % (Upgrade.AdminACL)) + except BaseException as msg: + print(str(msg)) + import sleep + sleep(10) + + try: + cursor.execute("UPDATE loginSystem_acl SET config = '%s' where name = 'reseller'" % (Upgrade.ResellerACL)) + except: + pass + + try: + cursor.execute("UPDATE loginSystem_acl SET config = '%s' where name = 'user'" % (Upgrade.UserACL)) + except: + pass + try: cursor.execute("alter table loginSystem_administrator drop initUserAccountsLimit") except: @@ -635,6 +710,11 @@ imap_folder_list_limit = 0 except: pass + try: + cursor.execute('ALTER TABLE websiteFunctions_websites ADD config longtext') + except: + pass + try: cursor.execute("ALTER TABLE websiteFunctions_websites MODIFY externalApp varchar(30)") except: @@ -655,7 +735,6 @@ imap_folder_list_limit = 0 except: pass - try: cursor.execute("ALTER TABLE loginSystem_acl ADD COLUMN listUsers INT DEFAULT 0;") except: @@ -677,6 +756,19 @@ imap_folder_list_limit = 0 `config` longtext NOT NULL, PRIMARY KEY (`id`) )""" + try: + cursor.execute(query) + except: + pass + + query = """CREATE TABLE `cloudAPI_wpdeployments` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `config` longtext NOT NULL, + `owner_id` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `cloudAPI_wpdeploymen_owner_id_506ddf01_fk_websiteFu` (`owner_id`), + CONSTRAINT `cloudAPI_wpdeploymen_owner_id_506ddf01_fk_websiteFu` FOREIGN KEY (`owner_id`) REFERENCES `websiteFunctions_websites` (`id`) +)""" try: cursor.execute(query) @@ -698,7 +790,6 @@ imap_folder_list_limit = 0 except: pass - query = """CREATE TABLE `websiteFunctions_normalbackupsites` ( `id` int(11) NOT NULL AUTO_INCREMENT, `domain_id` int(11) NOT NULL, @@ -715,7 +806,6 @@ imap_folder_list_limit = 0 except: pass - query = """CREATE TABLE `websiteFunctions_normalbackupjoblogs` ( `id` int(11) NOT NULL AUTO_INCREMENT, `status` int(11) NOT NULL, @@ -1192,6 +1282,16 @@ imap_folder_list_limit = 0 except: pass + try: + cursor.execute('ALTER TABLE loginSystem_administrator ADD config longtext') + except: + pass + + try: + cursor.execute('ALTER TABLE loginSystem_acl ADD config longtext') + except: + pass + try: cursor.execute('ALTER TABLE dockerManager_containers ADD volumes longtext') except: @@ -1302,6 +1402,11 @@ imap_folder_list_limit = 0 except: pass + try: + cursor.execute('ALTER TABLE `manageServices_pdnsstatus` CHANGE `type` `type` VARCHAR(6) NULL;') + except: + pass + query = '''CREATE TABLE `databases_dbmeta` ( `id` int(11) NOT NULL AUTO_INCREMENT, `key` varchar(200) NOT NULL, @@ -1461,7 +1566,6 @@ imap_folder_list_limit = 0 except: pass - query = """CREATE TABLE `websiteFunctions_backupjoblogs` ( `id` int(11) NOT NULL AUTO_INCREMENT, `message` longtext NOT NULL, @@ -1607,7 +1711,8 @@ imap_folder_list_limit = 0 command = 'git status' currentBranch = subprocess.check_output(shlex.split(command)).decode() - if currentBranch.find('On branch %s' % (branch)) > -1 and currentBranch.find('On branch %s-dev' % (branch)) == -1: + if currentBranch.find('On branch %s' % (branch)) > -1 and currentBranch.find( + 'On branch %s-dev' % (branch)) == -1: command = 'git stash' Upgrade.executioner(command, command, 1) @@ -1641,7 +1746,6 @@ imap_folder_list_limit = 0 command = 'git pull' Upgrade.executioner(command, command, 1) - ## Copy settings file settingsData = open(settingsFile, 'r').readlines() @@ -1883,9 +1987,12 @@ echo $oConfig->Save() ? 'Done' : 'Error'; command = 'chmod +x /usr/local/CyberCP/CLManager/CLPackages.py' Upgrade.executioner(command, command, 0) - clScripts = ['/usr/local/CyberCP/CLScript/panel_info.py', '/usr/local/CyberCP/CLScript/CloudLinuxPackages.py', - '/usr/local/CyberCP/CLScript/CloudLinuxUsers.py', '/usr/local/CyberCP/CLScript/CloudLinuxDomains.py' - ,'/usr/local/CyberCP/CLScript/CloudLinuxResellers.py', '/usr/local/CyberCP/CLScript/CloudLinuxAdmins.py', + clScripts = ['/usr/local/CyberCP/CLScript/panel_info.py', + '/usr/local/CyberCP/CLScript/CloudLinuxPackages.py', + '/usr/local/CyberCP/CLScript/CloudLinuxUsers.py', + '/usr/local/CyberCP/CLScript/CloudLinuxDomains.py' + , '/usr/local/CyberCP/CLScript/CloudLinuxResellers.py', + '/usr/local/CyberCP/CLScript/CloudLinuxAdmins.py', '/usr/local/CyberCP/CLScript/CloudLinuxDB.py', '/usr/local/CyberCP/CLScript/UserInfo.py'] for items in clScripts: @@ -1914,7 +2021,6 @@ echo $oConfig->Save() ? 'Done' : 'Error'; command = '/usr/local/lsws/lsphp72/bin/php /usr/local/CyberCP/public/rainloop.php' Upgrade.executioner(command, 0) - Upgrade.stdOut("Permissions updated.") except BaseException as msg: @@ -1993,7 +2099,7 @@ echo $oConfig->Save() ? 'Done' : 'Error'; command = 'cp -pR %s %s' % (postfixConfPath, configbackups) Upgrade.executioner(command, 0) - if os.path.exists(CentOSPath): + if Upgrade.FindOperatingSytem() == CENTOS8 or Upgrade.FindOperatingSytem() == CENTOS7: command = "yum makecache -y" Upgrade.executioner(command, 0) @@ -2001,14 +2107,13 @@ echo $oConfig->Save() ? 'Done' : 'Error'; command = "yum update -y" Upgrade.executioner(command, 0) - if Upgrade.decideCentosVersion() == CENTOS8: + if Upgrade.FindOperatingSytem() == CENTOS8: command = 'dnf remove dovecot23 dovecot23-mysql -y' Upgrade.executioner(command, 0) command = 'dnf install --enablerepo=gf-plus dovecot23 dovecot23-mysql -y' Upgrade.executioner(command, 0) - import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") django.setup() @@ -2033,14 +2138,14 @@ echo $oConfig->Save() ? 'Done' : 'Error'; command = 'yum clean all' Upgrade.executioner(command, 0) - if Upgrade.decideCentosVersion() == CENTOS7: + if Upgrade.FindOperatingSytem() == CENTOS7: command = 'yum makecache fast' else: command = 'yum makecache -y' Upgrade.executioner(command, 0) - if Upgrade.decideCentosVersion() == CENTOS7: + if Upgrade.FindOperatingSytem() == CENTOS7: command = 'yum install --enablerepo=gf-plus -y postfix3 postfix3-ldap postfix3-mysql postfix3-pcre' else: command = 'dnf install --enablerepo=gf-plus postfix3 postfix3-mysql -y' @@ -2057,97 +2162,38 @@ echo $oConfig->Save() ? 'Done' : 'Error'; ## Restored - command = 'systemctl restart postfix' Upgrade.executioner(command, 0) + elif Upgrade.FindOperatingSytem() == Ubuntu20: - else: - if Upgrade.installedOutput.find('dovecot-mysql/bionic,now 2:2.3.10-2') == -1: - - command = 'curl https://repo.dovecot.org/DOVECOT-REPO-GPG | gpg --import' - subprocess.call(command, shell=True) - - command = 'gpg --export ED409DA1 > /etc/apt/trusted.gpg.d/dovecot.gpg' - subprocess.call(command, shell=True) - - debPath = '/etc/apt/sources.list.d/dovecot.list' - writeToFile = open(debPath, 'w') - writeToFile.write('deb https://repo.dovecot.org/ce-2.3-latest/ubuntu/bionic bionic main\n') - writeToFile.close() - - try: - command = 'apt update -y' - Upgrade.executioner(command, 0) - except: - pass - - try: - command = 'DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical sudo apt-get -q -y -o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold" --only-upgrade install dovecot-mysql -y' - subprocess.call(command, shell=True) - - command = 'dpkg --configure -a' - Upgrade.executioner(command, 0) - - command = 'apt --fix-broken install -y' - Upgrade.executioner(command, 0) - - command = 'DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical sudo apt-get -q -y -o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold" --only-upgrade install dovecot-mysql -y' - subprocess.call(command, shell=True) - except: - pass - - ### Restore dovecot/postfix conf - - command = 'cp -pR %s/dovecot/ /etc/' % (configbackups) - Upgrade.executioner(command, 0) - - command = 'cp -pR %s/postfix/ /etc/' % (configbackups) - Upgrade.executioner(command, 0) - - ## Restored - - ## Remove Default Password Scheme - - path = '/etc/dovecot/dovecot-sql.conf.ext' - - data = open(path, 'r').readlines() - - updatePasswords = 0 - - writeToFile = open(path, 'w') - for items in data: - if items.find('default_pass_scheme') > -1: - updatePasswords = 1 - continue - else: - writeToFile.writelines(items) - + debPath = '/etc/apt/sources.list.d/dovecot.list' + writeToFile = open(debPath, 'w') + writeToFile.write('deb https://repo.dovecot.org/ce-2.3-latest/ubuntu/focal focal main\n') writeToFile.close() - Upgrade.stdOut("Upgrading passwords...") + command = "apt update -y" + Upgrade.executioner(command, command) + + command = 'dpkg --configure -a' + subprocess.call(command, shell=True) + + command = 'apt --fix-broken install -y' + subprocess.call(command, shell=True) + + command = 'DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical apt -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" upgrade -y' + subprocess.call(command, shell=True) + - import django - os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") - django.setup() - from mailServer.models import EUsers - for items in EUsers.objects.all(): - if items.password.find('CRYPT') > -1: - continue - command = 'doveadm pw -p %s' % (items.password) - items.password = subprocess.check_output(shlex.split(command)).decode("utf-8").strip('\n') - items.save() - command = "systemctl restart dovecot" - Upgrade.executioner(command, 0) dovecotConf = '/etc/dovecot/dovecot.conf' dovecotContent = open(dovecotConf, 'r').read() if dovecotContent.find('service stats') == -1: - writeToFile = open(dovecotConf, 'a') + writeToFile = open(dovecotConf, 'a') content = """\nservice stats { unix_listener stats-reader { @@ -2233,7 +2279,6 @@ service_port = 9000 writeToFile.write(content) writeToFile.close() - command = 'mkdir -p /etc/cagefs/exclude' Upgrade.executioner(command, command, 0) @@ -2324,6 +2369,30 @@ vmail command = 'chmod 600 %s' % (cronPath) Upgrade.executioner(command, 0) + @staticmethod + def UpdateConfigOfCustomACL(): + sys.path.append('/usr/local/CyberCP') + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") + import django + django.setup() + from loginSystem.models import ACL + for acl in ACL.objects.all(): + if acl.name == 'admin' or acl.name == 'reseller' or acl.name == 'user': + continue + elif acl.config == '{}': + acl.config = '{"adminStatus":%s, "versionManagement": %s, "createNewUser": %s, "listUsers": %s, "deleteUser": %s, "resellerCenter": %s, "changeUserACL": %s, "createWebsite": %s, "modifyWebsite": %s, "suspendWebsite": %s, "deleteWebsite": %s, "createPackage": %s, "listPackages": %s, "deletePackage": %s, "modifyPackage": %s, "createDatabase": %s, "deleteDatabase": %s, "listDatabases": %s, "createNameServer": %s, "createDNSZone": %s, "deleteZone": %s, "addDeleteRecords": %s, "createEmail": %s, "listEmails": %s, "deleteEmail": %s, "emailForwarding": %s, "changeEmailPassword": %s, "dkimManager": %s, "createFTPAccount": %s, "deleteFTPAccount": %s, "listFTPAccounts": %s, "createBackup": %s, "restoreBackup": %s, "addDeleteDestinations": %s, "scheDuleBackups": %s, "remoteBackups": %s, "googleDriveBackups": %s, "manageSSL": %s, "hostnameSSL": %s, "mailServerSSL": %s }' \ + % (str(acl.adminStatus), str(acl.versionManagement), str(acl.createNewUser), + str(acl.listUsers), str(acl.deleteUser), str(acl.resellerCenter), str(acl.changeUserACL), + str(acl.createWebsite), str(acl.modifyWebsite), str(acl.suspendWebsite), str(acl.deleteWebsite), + str(acl.createPackage), str(acl.listPackages), str(acl.deletePackage), str(acl.modifyPackage), + str(acl.createDatabase), str(acl.deleteDatabase), str(acl.listDatabases), str(acl.createNameServer), + str(acl.createDNSZone), str(acl.deleteZone), str(acl.addDeleteRecords), str(acl.createEmail), + str(acl.listEmails), str(acl.deleteEmail), str(acl.emailForwarding), str(acl.changeEmailPassword), + str(acl.dkimManager), str(acl.createFTPAccount), str(acl.deleteFTPAccount), str(acl.listFTPAccounts), + str(acl.createBackup), str(acl.restoreBackup), str(acl.addDeleteDestinations), str(acl.scheDuleBackups), str(acl.remoteBackups), '1', + str(acl.manageSSL), str(acl.hostnameSSL), str(acl.mailServerSSL)) + acl.save() + @staticmethod def upgrade(branch): @@ -2337,11 +2406,9 @@ vmail command = 'apt list' Upgrade.installedOutput = subprocess.check_output(shlex.split(command)).decode() - command = 'systemctl stop cpssh' Upgrade.executioner(command, 'fix csf if there', 0) - ## Add LSPHP7.4 TO LSWS Ent configs if not os.path.exists('/usr/local/lsws/bin/openlitespeed'): @@ -2351,8 +2418,8 @@ vmail command = 'wget https://raw.githubusercontent.com/usmannasir/cyberpanel/stable/install/litespeed/httpd_config.xml' Upgrade.executioner(command, command, 0) - #os.remove('/usr/local/lsws/conf/httpd_config.xml') - #shutil.copy('httpd_config.xml', '/usr/local/lsws/conf/httpd_config.xml') + # os.remove('/usr/local/lsws/conf/httpd_config.xml') + # shutil.copy('httpd_config.xml', '/usr/local/lsws/conf/httpd_config.xml') postfixPath = '/home/cyberpanel/postfix' pdns = '/home/cyberpanel/pdns' @@ -2367,7 +2434,6 @@ vmail ## Current Version - command = "systemctl stop lscpd" Upgrade.executioner(command, 'stop lscpd', 0) @@ -2402,11 +2468,16 @@ vmail ## - #Upgrade.setupVirtualEnv() + # Upgrade.setupVirtualEnv() ## Upgrade.applyLoginSystemMigrations() + + ## Put function here to update custom ACLs + + Upgrade.UpdateConfigOfCustomACL() + Upgrade.s3BackupMigrations() Upgrade.containerMigrations() Upgrade.manageServiceMigrations() @@ -2417,7 +2488,7 @@ vmail Upgrade.someDirectories() Upgrade.installLSCPD(branch) Upgrade.GeneralMigrations() - #Upgrade.p3() + # Upgrade.p3() if os.path.exists(postfixPath): Upgrade.upgradeDovecot() @@ -2444,14 +2515,12 @@ vmail command = 'cp /usr/local/lsws/lsphp73/bin/lsphp %s' % (phpPath) Upgrade.executioner(command, 0) - try: command = "systemctl start lscpd" Upgrade.executioner(command, 'Start LSCPD', 0) except: pass - command = 'csf -uf' Upgrade.executioner(command, 'fix csf if there', 0) command = 'systemctl start cpssh' @@ -2477,6 +2546,7 @@ vmail Upgrade.stdOut("Upgrade Completed.") + def main(): parser = argparse.ArgumentParser(description='CyberPanel Installer') parser.add_argument('branch', help='Install from branch name.') diff --git a/plogical/vhost.py b/plogical/vhost.py index 5e6b3b24c..78f39b980 100755 --- a/plogical/vhost.py +++ b/plogical/vhost.py @@ -721,11 +721,13 @@ class vhost: if not os.path.exists("/home/" + domainName + "/logs"): print("0,0") + return 0,0 bwmeta = "/home/" + domainName + "/logs/bwmeta" if not os.path.exists(path): print("0,0") + return 0, 0 if os.path.exists(bwmeta): try: @@ -741,19 +743,24 @@ class vhost: percentage = float(percentage) * float(inMB) except: print("0,0") + return 0, 0 if percentage > 100.0: percentage = 100 print(str(inMB) + "," + str(percentage)) + return str(inMB), str(percentage) else: print("0,0") + return 0, 0 except OSError as msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [findDomainBW]") print("0,0") + return 0, 0 except ValueError as msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [findDomainBW]") print("0,0") + return 0, 0 @staticmethod def permissionControl(path): diff --git a/plogical/virtualHostUtilities.py b/plogical/virtualHostUtilities.py old mode 100755 new mode 100644 index 899814849..cd875c093 --- a/plogical/virtualHostUtilities.py +++ b/plogical/virtualHostUtilities.py @@ -261,7 +261,7 @@ class virtualHostUtilities: CLPath = '/etc/sysconfig/cloudlinux' if os.path.exists(CLPath): - command = '/usr/share/cloudlinux/hooks/post_modify_user.py create --username %s --owner %s' % (virtualHostUser, virtualHostUser) + command = '/usr/share/cloudlinux/hooks/post_modify_user.py create --username %s --owner %s' % (virtualHostUser, admin.userName) ProcessUtilities.executioner(command) ### For autodiscover of mail clients. @@ -1308,8 +1308,7 @@ class virtualHostUtilities: def getDiskUsage(path, totalAllowed): try: - totalUsageInMB = ProcessUtilities.outputExecutioner(["sudo", "du", "-hs", path, "--block-size=1M"]).split()[ - 0] + totalUsageInMB = subprocess.check_output('du -hs %s --block-size=1M' % (path), shell=True).decode("utf-8").split()[0] percentage = float(100) / float(totalAllowed) @@ -1347,6 +1346,24 @@ class virtualHostUtilities: except BaseException as msg: logging.CyberCPLogFileWriter.writeToFile(str(msg)) + @staticmethod + def FindStats(website): + + import json + try: + config = json.loads(website.config) + DiskUsage = config['DiskUsage'] + DiskUsagePercentage = config['DiskUsagePercentage'] + bwInMB = config['bwInMB'] + bwUsage = config['bwUsage'] + except: + DiskUsage = 0 + DiskUsagePercentage = 0 + bwInMB = 0 + bwUsage = 0 + + return DiskUsage, DiskUsagePercentage, bwInMB, bwUsage + def main(): parser = argparse.ArgumentParser(description='CyberPanel Installer') diff --git a/plogical/website.py b/plogical/website.py deleted file mode 100755 index ae1216d7b..000000000 --- a/plogical/website.py +++ /dev/null @@ -1,2333 +0,0 @@ -#!/usr/local/CyberCP/bin/python -import os -import os.path -import sys -import django - -sys.path.append('/usr/local/CyberCP') -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") -django.setup() -import json -from plogical.acl import ACLManager -from plogical import CyberCPLogFileWriter as logging -from websiteFunctions.models import Websites, ChildDomains -from plogical.virtualHostUtilities import virtualHostUtilities -import subprocess -import shlex -from plogical.installUtilities import installUtilities -from django.shortcuts import HttpResponse, render -from loginSystem.models import Administrator, ACL -from packages.models import Package -from plogical.mailUtilities import mailUtilities -from random import randint -import time -import re -from plogical.childDomain import ChildDomainManager -from math import ceil -from plogical.alias import AliasManager -from plogical.applicationInstaller import ApplicationInstaller -from databases.models import Databases -from plogical import randomPassword as randomPassword -import hashlib -from plogical.mysqlUtilities import mysqlUtilities -from plogical import hashPassword -from emailMarketing.emACL import emACL -from plogical.processUtilities import ProcessUtilities -from managePHP.phpManager import PHPManager -from ApachController.ApacheVhosts import ApacheVhost -from plogical.vhostConfs import vhostConfs -from plogical.cronUtil import CronUtil -from re import match,I,M - - -class WebsiteManager: - apache = 1 - ols = 2 - lsws = 3 - - def __init__(self, domain=None, childDomain=None): - self.domain = domain - self.childDomain = childDomain - - def createWebsite(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: - return ACLManager.loadError() - - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} - return render(request, 'websiteFunctions/createWebsite.html', Data) - - except BaseException as msg: - return HttpResponse(str(msg)) - - def modifyWebsite(self, request=None, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: - return ACLManager.loadError() - - websitesName = ACLManager.findAllSites(currentACL, userID) - phps = PHPManager.findPHPVersions() - - return render(request, 'websiteFunctions/modifyWebsite.html', {'websiteList': websitesName, 'phps': phps}) - except BaseException as msg: - return HttpResponse(str(msg)) - - def deleteWebsite(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'deleteWebsite') == 0: - return ACLManager.loadError() - - websitesName = ACLManager.findAllSites(currentACL, userID) - - return render(request, 'websiteFunctions/deleteWebsite.html', {'websiteList': websitesName}) - except BaseException as msg: - return HttpResponse(str(msg)) - - def siteState(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'suspendWebsite') == 0: - return ACLManager.loadError() - - websitesName = ACLManager.findAllSites(currentACL, userID) - - return render(request, 'websiteFunctions/suspendWebsite.html', {'websiteList': websitesName}) - except BaseException as msg: - return HttpResponse(str(msg)) - - def listWebsites(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - pagination = self.websitePagination(currentACL, userID) - - return render(request, 'websiteFunctions/listWebsites.html', {"pagination": pagination}) - except BaseException as msg: - return HttpResponse(str(msg)) - - def listCron(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - websitesName = ACLManager.findAllSites(currentACL, userID) - return render(request, 'websiteFunctions/listCron.html', {'websiteList': websitesName}) - except BaseException as msg: - return HttpResponse(str(msg)) - - def domainAlias(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - aliasManager = AliasManager(self.domain) - noAlias, finalAlisList = aliasManager.fetchAlisForDomains() - - path = "/home/" + self.domain + "/public_html" - - return render(request, 'websiteFunctions/domainAlias.html', { - 'masterDomain': self.domain, - 'aliases': finalAlisList, - 'path': path, - 'noAlias': noAlias - }) - except BaseException as msg: - return HttpResponse(str(msg)) - - def submitWebsiteCreation(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) - - domain = data['domainName'] - adminEmail = data['adminEmail'] - phpSelection = data['phpSelection'] - packageName = data['package'] - websiteOwner = data['websiteOwner'] - - if not match(r'^[a-zA-Z0-9-]*[a-zA-Z0-9-]{0,61}[a-zA-Z0-9-](?:\.[a-zA-Z0-9-]{2,})+$', domain, - M | I): - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if not match(r'\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b', adminEmail, - M | I): - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid email."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - try: - HA = data['HA'] - externalApp = 'nobody' - except: - externalApp = "".join(re.findall("[a-zA-Z]+", domain))[:7] - - try: - counter = 0 - while 1: - tWeb = Websites.objects.get(externalApp=externalApp) - externalApp = '%s%s' % (tWeb.externalApp, str(counter)) - counter = counter + 1 - except: - pass - - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - try: - apacheBackend = str(data['apacheBackend']) - except: - apacheBackend = "0" - - ## Create Configurations - - execPath = "sudo /usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " createVirtualHost --virtualHostName " + domain + \ - " --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + \ - "' --virtualHostUser " + externalApp + " --ssl " + str(data['ssl']) + " --dkimCheck " \ - + str(data['dkimCheck']) + " --openBasedir " + str(data['openBasedir']) + \ - ' --websiteOwner ' + websiteOwner + ' --package ' + packageName + ' --tempStatusPath ' + tempStatusPath + " --apache " + apacheBackend - - ProcessUtilities.popenExecutioner(execPath) - time.sleep(2) - - data_ret = {'status': 1, 'createWebSiteStatus': 1, 'error_message': "None", - 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitDomainCreation(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - masterDomain = data['masterDomain'] - domain = data['domainName'] - phpSelection = data['phpSelection'] - path = data['path'] - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if not match(r'^[a-zA-Z0-9-]*[a-zA-Z0-9-]{0,61}[a-zA-Z0-9-](?:\.[a-zA-Z0-9-]{2,})+$', domain, - M | I): - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if ACLManager.checkOwnership(masterDomain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) - - if currentACL['admin'] != 1: - data['openBasedir'] = 1 - - if len(path) > 0: - path = path.lstrip("/") - path = "/home/" + masterDomain + "/public_html/" + path - else: - path = "/home/" + masterDomain + "/public_html/" + domain - - try: - apacheBackend = str(data['apacheBackend']) - except: - apacheBackend = "0" - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \ - " --phpVersion '" + phpSelection + "' --ssl " + str(data['ssl']) + " --dkimCheck " + str( - data['dkimCheck']) \ - + " --openBasedir " + str(data['openBasedir']) + ' --path ' + path + ' --websiteOwner ' \ - + admin.userName + ' --tempStatusPath ' + tempStatusPath + " --apache " + apacheBackend - - ProcessUtilities.popenExecutioner(execPath) - time.sleep(2) - - data_ret = {'status': 1, 'createWebSiteStatus': 1, 'error_message': "None", - 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def fetchDomains(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - masterDomain = data['masterDomain'] - - if ACLManager.checkOwnership(masterDomain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('fetchStatus', 0) - - cdManager = ChildDomainManager(masterDomain) - json_data = cdManager.findChildDomainsJson() - - final_json = json.dumps({'status': 1, 'fetchStatus': 1, 'error_message': "None", "data": json_data}) - return HttpResponse(final_json) - - except BaseException as msg: - final_dic = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - def searchWebsites(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - try: - json_data = self.searchWebsitesJson(currentACL, userID, data['patternAdded']) - except BaseException as msg: - tempData = {} - tempData['page'] = 1 - return self.getFurtherAccounts(userID, tempData) - - pagination = self.websitePagination(currentACL, userID) - final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, - 'pagination': pagination} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except BaseException as msg: - dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def getFurtherAccounts(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - pageNumber = int(data['page']) - json_data = self.findWebsitesJson(currentACL, userID, pageNumber) - pagination = self.websitePagination(currentACL, userID) - final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, - 'pagination': pagination} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except BaseException as msg: - dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def submitWebsiteDeletion(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'deleteWebsite') == 0: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - websiteName = data['websiteName'] - - admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - ## Deleting master domain - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName " + websiteName - ProcessUtilities.popenExecutioner(execPath) - - data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'websiteDeleteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitDomainDeletion(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - websiteName = data['websiteName'] - - if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " deleteDomain --virtualHostName " + websiteName - ProcessUtilities.outputExecutioner(execPath) - - data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'websiteDeleteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitWebsiteStatus(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'suspendWebsite') == 0: - return ACLManager.loadErrorJson('websiteStatus', 0) - - websiteName = data['websiteName'] - state = data['state'] - - website = Websites.objects.get(domain=websiteName) - - if state == "Suspend": - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName - command = "sudo mv " + confPath + " " + confPath + "-suspended" - ProcessUtilities.popenExecutioner(command) - installUtilities.reStartLiteSpeedSocket() - website.state = 0 - else: - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName - - command = "sudo mv " + confPath + "-suspended" + " " + confPath - ProcessUtilities.executioner(command) - - command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath - ProcessUtilities.popenExecutioner(command) - - installUtilities.reStartLiteSpeedSocket() - website.state = 1 - - website.save() - - data_ret = {'websiteStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - - data_ret = {'websiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def submitWebsiteModify(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: - return ACLManager.loadErrorJson('modifyStatus', 0) - - admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(data['websiteToBeModified'], admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - packs = ACLManager.loadPackages(userID, currentACL) - admins = ACLManager.loadAllUsers(userID) - - ## Get packs name - - json_data = "[" - checker = 0 - - for items in packs: - dic = {"pack": items} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - ### Get admin names - - admin_data = "[" - checker = 0 - - for items in admins: - dic = {"adminNames": items} - - if checker == 0: - admin_data = admin_data + json.dumps(dic) - checker = 1 - else: - admin_data = admin_data + ',' + json.dumps(dic) - - admin_data = admin_data + ']' - - websiteToBeModified = data['websiteToBeModified'] - - modifyWeb = Websites.objects.get(domain=websiteToBeModified) - - email = modifyWeb.adminEmail - currentPack = modifyWeb.package.packageName - owner = modifyWeb.admin.userName - - data_ret = {'status': 1, 'modifyStatus': 1, 'error_message': "None", "adminEmail": email, - "packages": json_data, "current_pack": currentPack, "adminNames": admin_data, - 'currentAdmin': owner} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - except BaseException as msg: - dic = {'status': 0, 'modifyStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def fetchWebsiteDataJSON(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) - - packs = ACLManager.loadPackages(userID, currentACL) - admins = ACLManager.loadAllUsers(userID) - - ## Get packs name - - json_data = "[" - checker = 0 - - for items in packs: - dic = {"pack": items} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - ### Get admin names - - admin_data = "[" - checker = 0 - - for items in admins: - dic = {"adminNames": items} - - if checker == 0: - admin_data = admin_data + json.dumps(dic) - checker = 1 - else: - admin_data = admin_data + ',' + json.dumps(dic) - - admin_data = admin_data + ']' - - data_ret = {'status': 1, 'error_message': "None", - "packages": json_data, "adminNames": admin_data} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - except BaseException as msg: - dic = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def saveWebsiteChanges(self, userID=None, data=None): - try: - domain = data['domain'] - package = data['packForWeb'] - email = data['email'] - phpVersion = data['phpVersion'] - newUser = data['admin'] - - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: - return ACLManager.loadErrorJson('saveStatus', 0) - - admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + domain - completePathToConfigFile = confPath + "/vhost.conf" - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile - ProcessUtilities.popenExecutioner(execPath) - - #### - - newOwner = Administrator.objects.get(userName=newUser) - - modifyWeb = Websites.objects.get(domain=domain) - webpack = Package.objects.get(packageName=package) - - modifyWeb.package = webpack - modifyWeb.adminEmail = email - modifyWeb.phpSelection = phpVersion - modifyWeb.admin = newOwner - - modifyWeb.save() - - data_ret = {'status': 1, 'saveStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'saveStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def loadDomainHome(self, request=None, userID=None, data=None): - - if Websites.objects.filter(domain=self.domain).exists(): - - currentACL = ACLManager.loadedACL(userID) - website = Websites.objects.get(domain=self.domain) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - Data = {} - - marketingStatus = emACL.checkIfEMEnabled(admin.userName) - - Data['marketingStatus'] = marketingStatus - Data['ftpTotal'] = website.package.ftpAccounts - Data['ftpUsed'] = website.users_set.all().count() - - Data['databasesUsed'] = website.databases_set.all().count() - Data['databasesTotal'] = website.package.dataBases - - Data['domain'] = self.domain - - diskUsageDetails = virtualHostUtilities.getDiskUsage("/home/" + self.domain, website.package.diskSpace) - - ## bw usage calculation - - try: - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " findDomainBW --virtualHostName " + self.domain + " --bandwidth " + str( - website.package.bandwidth) - - output = ProcessUtilities.outputExecutioner(execPath) - bwData = output.split(",") - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - bwData = [0, 0] - - ## bw usage calculations - - Data['bwInMBTotal'] = website.package.bandwidth - Data['bwInMB'] = bwData[0] - Data['bwUsage'] = bwData[1] - - if diskUsageDetails != None: - if diskUsageDetails[1] > 100: - diskUsageDetails[1] = 100 - - Data['diskUsage'] = diskUsageDetails[1] - Data['diskInMB'] = diskUsageDetails[0] - Data['diskInMBTotal'] = website.package.diskSpace - else: - Data['diskUsage'] = 0 - Data['diskInMB'] = 0 - Data['diskInMBTotal'] = website.package.diskSpace - - Data['phps'] = PHPManager.findPHPVersions() - - servicePath = '/home/cyberpanel/postfix' - if os.path.exists(servicePath): - Data['email'] = 1 - else: - Data['email'] = 0 - - servicePath = '/home/cyberpanel/pureftpd' - if os.path.exists(servicePath): - Data['ftp'] = 1 - else: - Data['ftp'] = 0 - - return render(request, 'websiteFunctions/website.html', Data) - - else: - return render(request, 'websiteFunctions/website.html', - {"error": 1, "domain": "This domain does not exists."}) - - def launchChild(self, request=None, userID=None, data=None): - - if ChildDomains.objects.filter(domain=self.childDomain).exists(): - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - website = Websites.objects.get(domain=self.domain) - - Data = {} - - Data['ftpTotal'] = website.package.ftpAccounts - Data['ftpUsed'] = website.users_set.all().count() - - Data['databasesUsed'] = website.databases_set.all().count() - Data['databasesTotal'] = website.package.dataBases - - Data['domain'] = self.domain - Data['childDomain'] = self.childDomain - - diskUsageDetails = virtualHostUtilities.getDiskUsage("/home/" + self.domain, website.package.diskSpace) - - ## bw usage calculation - - try: - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " findDomainBW --virtualHostName " + self.domain + " --bandwidth " + str( - website.package.bandwidth) - - output = ProcessUtilities.outputExecutioner(execPath) - bwData = output.split(",") - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - bwData = [0, 0] - - ## bw usage calculations - - Data['bwInMBTotal'] = website.package.bandwidth - Data['bwInMB'] = bwData[0] - Data['bwUsage'] = bwData[1] - - if diskUsageDetails != None: - if diskUsageDetails[1] > 100: - diskUsageDetails[1] = 100 - - Data['diskUsage'] = diskUsageDetails[1] - Data['diskInMB'] = diskUsageDetails[0] - Data['diskInMBTotal'] = website.package.diskSpace - else: - Data['diskUsage'] = 0 - Data['diskInMB'] = 0 - Data['diskInMBTotal'] = website.package.diskSpace - - Data['phps'] = PHPManager.findPHPVersions() - - servicePath = '/home/cyberpanel/postfix' - if os.path.exists(servicePath): - Data['email'] = 1 - else: - Data['email'] = 0 - - servicePath = '/home/cyberpanel/pureftpd' - if os.path.exists(servicePath): - Data['ftp'] = 1 - else: - Data['ftp'] = 0 - - return render(request, 'websiteFunctions/launchChild.html', Data) - else: - return render(request, 'websiteFunctions/launchChild.html', - {"error": 1, "domain": "This child domain does not exists"}) - - def getDataFromLogFile(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - logType = data['logType'] - self.domain = data['virtualHost'] - page = data['page'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('logstatus', 0) - - if logType == 1: - fileName = "/home/" + self.domain + "/logs/" + self.domain + ".access_log" - else: - fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" - - ## get Logs - website = Websites.objects.get(domain=self.domain) - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " getAccessLogs --path " + fileName + " --page " + str(page) - output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - if output.find("1,None") > -1: - final_json = json.dumps( - {'status': 0, 'logstatus': 0, 'error_message': "Not able to fetch logs, see CyberPanel main log file!"}) - return HttpResponse(final_json) - - ## get log ends here. - - data = output.split("\n") - - json_data = "[" - checker = 0 - - for items in reversed(data): - if len(items) > 10: - logData = items.split(" ") - domain = logData[0].strip('"') - ipAddress = logData[1] - time = (logData[4]).strip("[").strip("]") - resource = logData[7].strip('"') - size = logData[10].replace('"', '') - - dic = {'domain': domain, - 'ipAddress': ipAddress, - 'time': time, - 'resource': resource, - 'size': size, - } - - 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, 'logstatus': 1, 'error_message': "None", "data": json_data}) - return HttpResponse(final_json) - - def fetchErrorLogs(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['virtualHost'] - page = data['page'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('logstatus', 0) - - fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" - - ## get Logs - website = Websites.objects.get(domain=self.domain) - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " getErrorLogs --path " + fileName + " --page " + str(page) - - output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - if output.find("1,None") > -1: - final_json = json.dumps( - {'status': 0, 'logstatus': 0, 'error_message': "Not able to fetch logs, see CyberPanel main log file!"}) - return HttpResponse(final_json) - - ## get log ends here. - - final_json = json.dumps({'status': 1, 'logstatus': 1, 'error_message': "None", "data": output}) - return HttpResponse(final_json) - - def getDataFromConfigFile(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('configstatus', 0) - - filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" - - command = 'sudo cat ' + filePath - configData = ProcessUtilities.outputExecutioner(command, 'lsadm') - - if len(configData) == 0: - status = {'status': 0, "configstatus": 0, "error_message": "Configuration file is currently empty!"} - - final_json = json.dumps(status) - return HttpResponse(final_json) - - status = {'status': 1, "configstatus": 1, "configData": configData} - final_json = json.dumps(status) - return HttpResponse(final_json) - - def saveConfigsToFile(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] != 1: - return ACLManager.loadErrorJson('configstatus', 0) - - configData = data['configData'] - self.domain = data['virtualHost'] - - mailUtilities.checkHome() - - tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - vhost = open(tempPath, "w") - - vhost.write(configData) - - vhost.close() - - ## writing data temporary to file - - filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" - - ## save configuration data - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " saveVHostConfigs --path " + filePath + " --tempPath " + tempPath - - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - status = {"configstatus": 1} - - final_json = json.dumps(status) - return HttpResponse(final_json) - else: - data_ret = {'configstatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## save configuration data ends - - def getRewriteRules(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('rewriteStatus', 0) - - try: - childDom = ChildDomains.objects.get(domain=self.domain) - filePath = childDom.path + '/.htaccess' - except: - filePath = "/home/" + self.domain + "/public_html/.htaccess" - - try: - rewriteRules = open(filePath, "r").read() - - if len(rewriteRules) == 0: - status = {"rewriteStatus": 1, "error_message": "Rules file is currently empty"} - final_json = json.dumps(status) - return HttpResponse(final_json) - - status = {"rewriteStatus": 1, "rewriteRules": rewriteRules} - - final_json = json.dumps(status) - return HttpResponse(final_json) - - except IOError: - status = {"rewriteStatus": 1, "error_message": "none", "rewriteRules": ""} - final_json = json.dumps(status) - return HttpResponse(final_json) - - def saveRewriteRules(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - rewriteRules = data['rewriteRules'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('rewriteStatus', 0) - - ## writing data temporary to file - - mailUtilities.checkHome() - tempPath = "/tmp/" + str(randint(1000, 9999)) - vhost = open(tempPath, "w") - vhost.write(rewriteRules) - vhost.close() - - ## writing data temporary to file - - try: - childDomain = ChildDomains.objects.get(domain=self.domain) - filePath = childDomain.path + '/.htaccess' - externalApp = childDomain.master.externalApp - except: - filePath = "/home/" + self.domain + "/public_html/.htaccess" - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp - - ## save configuration data - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " saveRewriteRules --virtualHostName " + self.domain + " --path " + filePath + " --tempPath " + tempPath - - output = ProcessUtilities.outputExecutioner(execPath, externalApp) - - if output.find("1,None") > -1: - installUtilities.reStartLiteSpeedSocket() - status = {"rewriteStatus": 1, 'error_message': output} - final_json = json.dumps(status) - return HttpResponse(final_json) - else: - data_ret = {'rewriteStatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def saveSSL(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['virtualHost'] - key = data['key'] - cert = data['cert'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('sslStatus', 0) - - mailUtilities.checkHome() - - ## writing data temporary to file - - tempKeyPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - vhost = open(tempKeyPath, "w") - vhost.write(key) - vhost.close() - - tempCertPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - vhost = open(tempCertPath, "w") - vhost.write(cert) - vhost.close() - - ## writing data temporary to file - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " saveSSL --virtualHostName " + self.domain + " --tempKeyPath " + tempKeyPath + " --tempCertPath " + tempCertPath - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - data_ret = {'sslStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - logging.CyberCPLogFileWriter.writeToFile( - output) - data_ret = {'sslStatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def changePHP(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['childDomain'] - phpVersion = data['phpSelection'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('changePHP', 0) - - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + self.domain - completePathToConfigFile = confPath + "/vhost.conf" - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile - ProcessUtilities.popenExecutioner(execPath) - - data_ret = {'status': 1, 'changePHP': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def getWebsiteCron(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('getWebsiteCron', 0) - - website = Websites.objects.get(domain=self.domain) - - if Websites.objects.filter(domain=self.domain).exists(): - pass - else: - dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - CronUtil.CronPrem(1) - - crons = [] - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp - - f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - CronUtil.CronPrem(0) - - if f.find("0,CyberPanel,") > -1: - data_ret = {'getWebsiteCron': 0, "user": website.externalApp, "crons": {}} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - counter = 0 - for line in f.split("\n"): - if line: - split = line.split(" ", 5) - if len(split) == 6: - counter += 1 - crons.append({"line": counter, - "minute": split[0], - "hour": split[1], - "monthday": split[2], - "month": split[3], - "weekday": split[4], - "command": split[5]}) - - data_ret = {'getWebsiteCron': 1, "user": website.externalApp, "crons": crons} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - dic = {'getWebsiteCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def getCronbyLine(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - line = data['line'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('getWebsiteCron', 0) - - if Websites.objects.filter(domain=self.domain).exists(): - pass - else: - dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - line -= 1 - website = Websites.objects.get(domain=self.domain) - - try: - CronUtil.CronPrem(1) - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp - - f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - CronUtil.CronPrem(0) - except subprocess.CalledProcessError as error: - dic = {'getWebsiteCron': 0, 'error_message': 'Unable to access Cron file'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - f = f.split("\n") - cron = f[line] - - cron = cron.split(" ", 5) - if len(cron) != 6: - dic = {'getWebsiteCron': 0, 'error_message': 'Cron line incorrect'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - data_ret = {"getWebsiteCron": 1, - "user": website.externalApp, - "cron": { - "minute": cron[0], - "hour": cron[1], - "monthday": cron[2], - "month": cron[3], - "weekday": cron[4], - "command": cron[5], - }, - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - except BaseException as msg: - print(msg) - dic = {'getWebsiteCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def saveCronChanges(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - line = data['line'] - - minute = data['minute'] - hour = data['hour'] - monthday = data['monthday'] - month = data['month'] - weekday = data['weekday'] - command = data['cronCommand'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('getWebsiteCron', 0) - - website = Websites.objects.get(domain=self.domain) - - finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) - - CronUtil.CronPrem(1) - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " saveCronChanges --externalApp " + website.externalApp + " --line " + str( - line) + " --finalCron '" + finalCron + "'" - output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - CronUtil.CronPrem(0) - - if output.find("1,") > -1: - data_ret = {"getWebsiteCron": 1, - "user": website.externalApp, - "cron": finalCron, - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - else: - dic = {'getWebsiteCron': 0, 'error_message': output} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - except BaseException as msg: - dic = {'getWebsiteCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def remCronbyLine(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - line = data['line'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('addNewCron', 0) - - website = Websites.objects.get(domain=self.domain) - - CronUtil.CronPrem(1) - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " remCronbyLine --externalApp " + website.externalApp + " --line " + str( - line) - output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - CronUtil.CronPrem(0) - - if output.find("1,") > -1: - data_ret = {"remCronbyLine": 1, - "user": website.externalApp, - "removeLine": output.split(',')[1], - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - else: - dic = {'remCronbyLine': 0, 'error_message': output} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - - except BaseException as msg: - dic = {'remCronbyLine': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def addNewCron(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - minute = data['minute'] - hour = data['hour'] - monthday = data['monthday'] - month = data['month'] - weekday = data['weekday'] - command = data['cronCommand'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('addNewCron', 0) - - website = Websites.objects.get(domain=self.domain) - - CronPath = '/var/spool/cron/%s' % (website.externalApp) - - commandT = 'touch %s' % (CronPath) - ProcessUtilities.executioner(commandT, 'root') - commandT = 'chown %s:%s %s' % (website.externalApp, website.externalApp, CronPath) - ProcessUtilities.executioner(commandT, 'root') - - CronUtil.CronPrem(1) - - finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" - execPath = execPath + " addNewCron --externalApp " + website.externalApp + " --finalCron '" + finalCron + "'" - output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) - - CronUtil.CronPrem(0) - - if output.find("1,") > -1: - - data_ret = {"addNewCron": 1, - "user": website.externalApp, - "cron": finalCron} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - else: - dic = {'addNewCron': 0, 'error_message': output} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - - except BaseException as msg: - dic = {'addNewCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - def submitAliasCreation(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['masterDomain'] - aliasDomain = data['aliasDomain'] - ssl = data['ssl'] - - if not match(r'^[a-zA-Z0-9-]*[a-zA-Z0-9-]{0,61}[a-zA-Z0-9-](?:\.[a-zA-Z0-9-]{2,})+$', aliasDomain, - M | I): - data_ret = {'status': 0, 'createAliasStatus': 0, 'error_message': "Invalid domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('createAliasStatus', 0) - - sslpath = "/home/" + self.domain + "/public_html" - - ## Create Configurations - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " createAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --ssl " + str( - ssl) + " --sslPath " + sslpath + " --administratorEmail " + admin.email + ' --websiteOwner ' + admin.userName - - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - pass - else: - data_ret = {'createAliasStatus': 0, 'error_message': output, "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Create Configurations ends here - - data_ret = {'createAliasStatus': 1, 'error_message': "None", "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - - except BaseException as msg: - data_ret = {'createAliasStatus': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def issueAliasSSL(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['masterDomain'] - aliasDomain = data['aliasDomain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('sslStatus', 0) - - sslpath = "/home/" + self.domain + "/public_html" - - ## Create Configurations - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " issueAliasSSL --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --sslPath " + sslpath + " --administratorEmail " + admin.email - - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - data_ret = {'sslStatus': 1, 'error_message': "None", "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'sslStatus': 0, 'error_message': output, "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'sslStatus': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def delateAlias(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['masterDomain'] - aliasDomain = data['aliasDomain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('deleteAlias', 0) - - ## Create Configurations - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " deleteAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: - data_ret = {'deleteAlias': 1, 'error_message': "None", "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'deleteAlias': 0, 'error_message': output, "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'deleteAlias': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def changeOpenBasedir(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - - self.domain = data['domainName'] - openBasedirValue = data['openBasedirValue'] - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('changeOpenBasedir', 0) - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changeOpenBasedir --virtualHostName '" + self.domain + "' --openBasedirValue " + openBasedirValue - output = ProcessUtilities.popenExecutioner(execPath) - - data_ret = {'status': 1, 'changeOpenBasedir': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'changeOpenBasedir': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def wordpressInstall(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - return render(request, 'websiteFunctions/installWordPress.html', {'domainName': self.domain}) - - except BaseException as msg: - return HttpResponse(str(msg)) - - def installWordpress(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['blogTitle'] = data['blogTitle'] - extraArgs['adminUser'] = data['adminUser'] - extraArgs['adminPassword'] = data['passwordByPass'] - extraArgs['adminEmail'] = data['adminEmail'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - background = ApplicationInstaller('wordpress', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def installWordpressStatus(self, userID=None, data=None): - try: - statusFile = data['statusFile'] - - statusData = ProcessUtilities.outputExecutioner("sudo cat " + statusFile).splitlines() - - lastLine = statusData[-1] - - if lastLine.find('[200]') > -1: - command = 'sudo rm -f ' + statusFile - subprocess.call(shlex.split(command)) - data_ret = {'abort': 1, 'installStatus': 1, 'installationProgress': "100", - 'currentStatus': 'Successfully Installed.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - elif lastLine.find('[404]') > -1: - data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "0", - 'error_message': lastLine} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - progress = lastLine.split(',') - currentStatus = progress[0] - try: - installationProgress = progress[1] - except: - installationProgress = 0 - data_ret = {'abort': 0, 'installStatus': 0, 'installationProgress': installationProgress, - 'currentStatus': currentStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "0", 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def joomlaInstall(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - return render(request, 'websiteFunctions/installJoomla.html', {'domainName': self.domain}) - except BaseException as msg: - return HttpResponse(str(msg)) - - def installJoomla(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - domainName = data['domain'] - home = data['home'] - - sitename = data['sitename'] - username = data['username'] - password = data['passwordByPass'] - prefix = data['prefix'] - - mailUtilities.checkHome() - - tempStatusPath = "/tmp/" + str(randint(1000, 9999)) - - statusFile = open(tempStatusPath, 'w') - statusFile.writelines('Setting up paths,0') - statusFile.close() - os.chmod(tempStatusPath, 0o777) - - finalPath = "" - - admin = Administrator.objects.get(pk=userID) - - ## DB Creation - - statusFile = open(tempStatusPath, 'w') - statusFile.writelines('Creating database..,10') - statusFile.close() - - dbName = randomPassword.generate_pass() - dbUser = dbName - dbPassword = randomPassword.generate_pass() - - if Databases.objects.filter(dbName=dbName).exists() or Databases.objects.filter( - dbUser=dbUser).exists(): - data_ret = {'status': 0, 'installStatus': 0, - 'error_message': "0,This database or user is already taken."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - result = mysqlUtilities.createDatabase(dbName, dbUser, dbPassword) - - if result == 1: - pass - else: - data_ret = {'status': 0, 'installStatus': 0, - 'error_message': "0,Not able to create database."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## - - try: - website = ChildDomains.objects.get(domain=domainName) - externalApp = website.master.externalApp - - if website.master.package.dataBases > website.master.databases_set.all().count(): - pass - else: - data_ret = {'status': 0, 'installStatus': 0, - 'error_message': "0,Maximum database limit reached for this website."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if home == '0': - path = data['path'] - finalPath = website.path.rstrip('/') + "/" + path + "/" - else: - finalPath = website.path + "/" - - db = Databases(website=website.master, dbName=dbName, dbUser=dbUser) - db.save() - - except: - website = Websites.objects.get(domain=domainName) - externalApp = website.externalApp - - if website.package.dataBases > website.databases_set.all().count(): - pass - else: - data_ret = {'status': 0, 'installStatus': 0, - 'error_message': "0,Maximum database limit reached for this website."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if home == '0': - path = data['path'] - finalPath = "/home/" + domainName + "/public_html/" + path + "/" - else: - finalPath = "/home/" + domainName + "/public_html/" - - db = Databases(website=website, dbName=dbName, dbUser=dbUser) - db.save() - - if finalPath.find("..") > -1: - data_ret = {'status': 0, 'installStatus': 0, - 'error_message': "Specified path must be inside virtual host home!"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Installation - salt = randomPassword.generate_pass(32) - # return salt - password_hash = hashlib.md5((password + salt).encode('utf-8')).hexdigest() - password = password_hash + ":" + salt - - statusFile = open(tempStatusPath, 'w') - statusFile.writelines('Downloading Joomla Core..,20') - statusFile.close() - - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " installJoomla --virtualHostName " + domainName + \ - " --virtualHostUser " + externalApp + " --path " + finalPath + " --dbName " + dbName + \ - " --dbUser " + dbUser + " --dbPassword " + dbPassword + " --username " + username + \ - " --password " + password + " --prefix " + prefix + " --sitename '" + sitename + "'" \ - + " --tempStatusPath " + tempStatusPath - - # return execPath - - ProcessUtilities.popenExecutioner(execPath, externalApp) - - data_ret = {'status': 1, "installStatus": 1, 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Installation ends - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def setupGit(self, request=None, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - website = Websites.objects.get(domain=self.domain) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - path = '/home/cyberpanel/' + self.domain + '.git' - - if os.path.exists(path): - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - - port = ProcessUtilities.fetchCurrentPort() - - webhookURL = 'https://' + ipAddress + ':%s/websites/' % (port) + self.domain + '/gitNotify' - - return render(request, 'websiteFunctions/setupGit.html', - {'domainName': self.domain, 'installed': 1, 'webhookURL': webhookURL}) - else: - - command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.domain, website.externalApp) - ProcessUtilities.executioner(command, website.externalApp) - - ### - - configContent = """Host github.com -IdentityFile /home/%s/.ssh/%s -""" % (self.domain, website.externalApp) - - path = "/home/cyberpanel/config" - writeToFile = open(path, 'w') - writeToFile.writelines(configContent) - writeToFile.close() - - command = 'mv %s /home/%s/.ssh/config' % (path, self.domain) - ProcessUtilities.executioner(command) - - command = 'sudo chown %s:%s /home/%s/.ssh/config' % (website.externalApp, website.externalApp, self.domain) - ProcessUtilities.executioner(command) - - command = 'cat /home/%s/.ssh/%s.pub' % (self.domain, website.externalApp) - deploymentKey = ProcessUtilities.outputExecutioner(command, website.externalApp) - - return render(request, 'websiteFunctions/setupGit.html', - {'domainName': self.domain, 'deploymentKey': deploymentKey, 'installed': 0}) - except BaseException as msg: - return HttpResponse(str(msg)) - - def setupGitRepo(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['username'] = data['username'] - extraArgs['reponame'] = data['reponame'] - extraArgs['branch'] = data['branch'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - extraArgs['defaultProvider'] = data['defaultProvider'] - - background = ApplicationInstaller('git', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def gitNotify(self, userID=None, data=None): - try: - - extraArgs = {} - extraArgs['domain'] = self.domain - - background = ApplicationInstaller('pull', extraArgs) - background.start() - - data_ret = {'pulled': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'pulled': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def detachRepo(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['domainName'] = data['domain'] - extraArgs['admin'] = admin - - background = ApplicationInstaller('detach', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def changeBranch(self, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['domainName'] = data['domain'] - extraArgs['githubBranch'] = data['githubBranch'] - extraArgs['admin'] = admin - - background = ApplicationInstaller('changeBranch', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException as msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def installPrestaShop(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - return render(request, 'websiteFunctions/installPrestaShop.html', {'domainName': self.domain}) - except BaseException as msg: - return HttpResponse(str(msg)) - - def prestaShopInstall(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['shopName'] = data['shopName'] - extraArgs['firstName'] = data['firstName'] - extraArgs['lastName'] = data['lastName'] - extraArgs['databasePrefix'] = data['databasePrefix'] - extraArgs['email'] = data['email'] - extraArgs['password'] = data['passwordByPass'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - background = ApplicationInstaller('prestashop', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'installStatus': 1, 'error_message': 'None', - 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Installation ends - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def createWebsiteAPI(self, data=None): - try: - - adminUser = data['adminUser'] - adminPass = data['adminPass'] - adminEmail = data['ownerEmail'] - websiteOwner = data['websiteOwner'] - ownerPassword = data['ownerPassword'] - data['ssl'] = 0 - data['dkimCheck'] = 0 - data['openBasedir'] = 1 - data['adminEmail'] = data['ownerEmail'] - data['phpSelection'] = "PHP 7.0" - data['package'] = data['packageName'] - - admin = Administrator.objects.get(userName=adminUser) - - if hashPassword.check_password(admin.password, adminPass): - - if adminEmail is None: - data['adminEmail'] = "usman@cyberpersons.com" - - try: - acl = ACL.objects.get(name='user') - websiteOwn = Administrator(userName=websiteOwner, - password=hashPassword.hash_password(ownerPassword), - email=adminEmail, type=3, owner=admin.pk, - initWebsitesLimit=1, acl=acl, api=1) - websiteOwn.save() - except BaseException: - pass - - else: - data_ret = {"existsStatus": 0, 'createWebSiteStatus': 0, - 'error_message': "Could not authorize access to API"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - return self.submitWebsiteCreation(admin.pk, data) - - except BaseException as msg: - data_ret = {'createWebSiteStatus': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def searchWebsitesJson(self, currentlACL, userID, searchTerm): - - websites = ACLManager.searchWebsiteObjects(currentlACL, userID, searchTerm) - - json_data = "[" - checker = 0 - - try: - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) - ipAddress = "192.168.100.1" - - for items in websites: - if items.state == 0: - state = "Suspended" - else: - state = "Active" - dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, - 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - return json_data - - def findWebsitesJson(self, currentACL, userID, pageNumber): - finalPageNumber = ((pageNumber * 10)) - 10 - endPageNumber = finalPageNumber + 10 - websites = ACLManager.findWebsiteObjects(currentACL, userID)[finalPageNumber:endPageNumber] - - json_data = "[" - checker = 0 - - try: - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) - ipAddress = "192.168.100.1" - - for items in websites: - if items.state == 0: - state = "Suspended" - else: - state = "Active" - dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, - 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - return json_data - - def websitePagination(self, currentACL, userID): - websites = ACLManager.findAllSites(currentACL, userID) - - pages = float(len(websites)) / float(10) - pagination = [] - - if pages <= 1.0: - pages = 1 - pagination.append('
  • ') - else: - pages = ceil(pages) - finalPages = int(pages) + 1 - - for i in range(1, finalPages): - pagination.append('
  • ' + str(i) + '
  • ') - - return pagination - - def getSwitchStatus(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - try: - globalData = data['global'] - - data = {} - data['status'] = 1 - - if os.path.exists('/etc/httpd'): - data['server'] = 1 - else: - data['server'] = 0 - - json_data = json.dumps(data) - return HttpResponse(json_data) - except: - pass - - self.domain = data['domainName'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - if ProcessUtilities.decideServer() == ProcessUtilities.OLS: - finalConfPath = ApacheVhost.configBasePath + self.domain + '.conf' - - if os.path.exists(finalConfPath): - - phpPath = ApacheVhost.whichPHPExists(self.domain) - command = 'sudo cat ' + phpPath - phpConf = ProcessUtilities.outputExecutioner(command).splitlines() - pmMaxChildren = phpConf[8].split(' ')[2] - pmStartServers = phpConf[9].split(' ')[2] - pmMinSpareServers = phpConf[10].split(' ')[2] - pmMaxSpareServers = phpConf[11].split(' ')[2] - - data = {} - data['status'] = 1 - - data['server'] = WebsiteManager.apache - data['pmMaxChildren'] = pmMaxChildren - data['pmStartServers'] = pmStartServers - data['pmMinSpareServers'] = pmMinSpareServers - data['pmMaxSpareServers'] = pmMaxSpareServers - data['phpPath'] = phpPath - else: - data = {} - data['status'] = 1 - data['server'] = WebsiteManager.ols - - else: - data = {} - data['status'] = 1 - data['server'] = WebsiteManager.lsws - - json_data = json.dumps(data) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'saveStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def switchServer(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - domainName = data['domainName'] - phpVersion = data['phpSelection'] - server = data['server'] - - if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " switchServer --phpVersion '" + phpVersion + "' --server " + str( - server) + " --virtualHostName " + domainName + " --tempStatusPath " + tempStatusPath - ProcessUtilities.popenExecutioner(execPath) - - time.sleep(3) - - data_ret = {'status': 1, 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def tuneSettings(self, userID=None, data=None): - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - domainName = data['domainName'] - pmMaxChildren = data['pmMaxChildren'] - pmStartServers = data['pmStartServers'] - pmMinSpareServers = data['pmMinSpareServers'] - pmMaxSpareServers = data['pmMaxSpareServers'] - phpPath = data['phpPath'] - - if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() - - if int(pmStartServers) < int(pmMinSpareServers) or int(pmStartServers) > int(pmMinSpareServers): - data_ret = {'status': 0, - 'error_message': 'pm.start_servers must not be less than pm.min_spare_servers and not greater than pm.max_spare_servers.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if int(pmMinSpareServers) > int(pmMaxSpareServers): - data_ret = {'status': 0, - 'error_message': 'pm.max_spare_servers must not be less than pm.min_spare_servers'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - try: - website = Websites.objects.get(domain=domainName) - externalApp = website.externalApp - except: - website = ChildDomains.objects.get(domain=domainName) - externalApp = website.master.externalApp - - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - phpFPMConf = vhostConfs.phpFpmPoolReplace - phpFPMConf = phpFPMConf.replace('{externalApp}', externalApp) - phpFPMConf = phpFPMConf.replace('{pmMaxChildren}', pmMaxChildren) - phpFPMConf = phpFPMConf.replace('{pmStartServers}', pmStartServers) - phpFPMConf = phpFPMConf.replace('{pmMinSpareServers}', pmMinSpareServers) - phpFPMConf = phpFPMConf.replace('{pmMaxSpareServers}', pmMaxSpareServers) - phpFPMConf = phpFPMConf.replace('{www}', "".join(re.findall("[a-zA-Z]+", domainName))[:7]) - phpFPMConf = phpFPMConf.replace('{Sock}', domainName) - - writeToFile = open(tempStatusPath, 'w') - writeToFile.writelines(phpFPMConf) - writeToFile.close() - - command = 'sudo mv %s %s' % (tempStatusPath, phpPath) - ProcessUtilities.executioner(command) - - phpPath = phpPath.split('/') - - if phpPath[1] == 'etc': - phpVersion = phpPath[4][3] + phpPath[4][4] - else: - phpVersion = phpPath[3][3] + phpPath[3][4] - - command = "systemctl stop php%s-php-fpm" % (phpVersion) - ProcessUtilities.executioner(command) - - command = "systemctl restart php%s-php-fpm" % (phpVersion) - ProcessUtilities.executioner(command) - - data_ret = {'status': 1} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - def sshAccess(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp - - return render(request, 'websiteFunctions/sshAccess.html', - {'domainName': self.domain, 'externalApp': externalApp}) - except BaseException as msg: - return HttpResponse(str(msg)) - - def saveSSHAccessChanges(self, userID=None, data=None): - try: - - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - self.domain = data['domain'] - - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson('status', 0) - - website = Websites.objects.get(domain=self.domain) - - if website.externalApp != data['externalApp']: - data_ret = {'status': 0, 'error_message': 'External app mis-match.'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - command = 'echo "%s" | passwd --stdin %s' % (data['password'], data['externalApp']) - ProcessUtilities.executioner(command) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException as msg: - data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) diff --git a/s3Backups/s3Backups.py b/s3Backups/s3Backups.py index 12036eac4..cdf5922b4 100755 --- a/s3Backups/s3Backups.py +++ b/s3Backups/s3Backups.py @@ -148,15 +148,21 @@ class S3Backups(multi.Thread): if currentACL['admin'] == 0: return proc.ajax(0, 'Only administrators can use AWS S3 Backups.') - aws_access_key_id, aws_secret_access_key, region = self.fetchAWSKeys() - s3 = boto3.resource( - 's3', - aws_access_key_id = aws_access_key_id, - aws_secret_access_key = aws_secret_access_key, - region_name=region - ) + if region.find('http') > -1: + s3 = boto3.resource( + 's3', + aws_access_key_id=aws_access_key_id, + aws_secret_access_key=aws_secret_access_key, + endpoint_url=region, + ) + else: + s3 = boto3.resource( + 's3', + aws_access_key_id=aws_access_key_id, + aws_secret_access_key=aws_secret_access_key, + ) json_data = "[" checker = 0 diff --git a/serverLogs/views.py b/serverLogs/views.py index c376fb36a..425eb2bfb 100755 --- a/serverLogs/views.py +++ b/serverLogs/views.py @@ -1,117 +1,45 @@ # -*- coding: utf-8 -*- - -from django.shortcuts import render,redirect -from loginSystem.views import loadLoginPage from django.http import HttpResponse import json import plogical.CyberCPLogFileWriter as logging +from plogical.httpProc import httpProc from plogical.installUtilities import installUtilities -import subprocess -import shlex from plogical.virtualHostUtilities import virtualHostUtilities from plogical.acl import ACLManager from plogical.processUtilities import ProcessUtilities import os # Create your views here. - def logsHome(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - except KeyError: - return redirect(loadLoginPage) - - return render(request,'serverLogs/index.html') + proc = httpProc(request, 'serverLogs/index.html', + None, 'admin') + return proc.render() def accessLogs(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - return render(request,'serverLogs/accessLogs.html') - - except KeyError as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[accessLogs]") - return redirect(loadLoginPage) + proc = httpProc(request, 'serverLogs/accessLogs.html', + None, 'admin') + return proc.render() def errorLogs(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - - return render(request,'serverLogs/errorLogs.html') - - except KeyError as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[accessLogs]") - return redirect(loadLoginPage) + proc = httpProc(request, 'serverLogs/errorLogs.html', + None, 'admin') + return proc.render() def ftplogs(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - return render(request,'serverLogs/ftplogs.html') - - except KeyError as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[accessLogs]") - return redirect(loadLoginPage) + proc = httpProc(request, 'serverLogs/ftplogs.html', + None, 'admin') + return proc.render() def emailLogs(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - - return render(request,'serverLogs/emailLogs.html') - - except KeyError as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[accessLogs]") - return redirect(loadLoginPage) + proc = httpProc(request, 'serverLogs/emailLogs.html', + None, 'admin') + return proc.render() def modSecAuditLogs(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - return render(request,'serverLogs/modSecAuditLog.html') - - except KeyError as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[accessLogs]") - return redirect(loadLoginPage) + proc = httpProc(request, 'serverLogs/modSecAuditLog.html', + None, 'admin') + return proc.render() def getLogsFromFile(request): try: @@ -205,30 +133,19 @@ def clearLogFile(request): return HttpResponse(json_data) def serverMail(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + smtpPath = '/home/cyberpanel/smtpDetails' + data = {} - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() + if os.path.exists(smtpPath): + mailSettings = json.loads(open(smtpPath, 'r').read()) + data['smtpHost'] = mailSettings['smtpHost'] + data['smtpPort'] = mailSettings['smtpPort'] + data['smtpUserName'] = mailSettings['smtpUserName'] + data['smtpPassword'] = mailSettings['smtpPassword'] - smtpPath = '/home/cyberpanel/smtpDetails' - data = {} - - if os.path.exists(smtpPath): - mailSettings = json.loads(open(smtpPath, 'r').read()) - data['smtpHost'] = mailSettings['smtpHost'] - data['smtpPort'] = mailSettings['smtpPort'] - data['smtpUserName'] = mailSettings['smtpUserName'] - data['smtpPassword'] = mailSettings['smtpPassword'] - - return render(request,'serverLogs/serverMail.html', data) - - except KeyError as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[accessLogs]") - return redirect(loadLoginPage) + proc = httpProc(request, 'serverLogs/serverMail.html', + data, 'admin') + return proc.render() def saveSMTPSettings(request): try: diff --git a/serverStatus/views.py b/serverStatus/views.py index a5b144866..62d1d3f7e 100755 --- a/serverStatus/views.py +++ b/serverStatus/views.py @@ -1,12 +1,11 @@ # -*- coding: utf-8 -*- - from django.shortcuts import render, redirect from django.http import HttpResponse import plogical.CyberCPLogFileWriter as logging from loginSystem.views import loadLoginPage import json -import subprocess, shlex +import subprocess import psutil import socket from plogical.acl import ACLManager @@ -18,7 +17,6 @@ from plogical.processUtilities import ProcessUtilities from plogical.httpProc import httpProc from plogical.installUtilities import installUtilities - # Create your views here. NOTHING = 0 @@ -27,15 +25,13 @@ EXPIRE = 3 ### Version -VERSION = '2.0' -BUILD = 3 +VERSION = '2.1' +BUILD = 1 def serverStatusHome(request): - try: - userID = request.session['userID'] - return render(request, 'serverStatus/index.html') - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'serverStatus/index.html', + None, 'admin') + return proc.render() def litespeedStatus(request): @@ -43,11 +39,6 @@ def litespeedStatus(request): userID = request.session['userID'] currentACL = ACLManager.loadedACL(userID) - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - processList = ProcessUtilities.getLitespeedProcessNumber() OLS = 0 @@ -82,17 +73,21 @@ def litespeedStatus(request): except BaseException as msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[litespeedStatus]") - return render(request, "serverStatus/litespeedStatus.html", {"processList": processList, - "liteSpeedVersionStatus": "For some reaons not able to load version details, see CyberCP main log file.", - 'OLS': OLS , 'message': message}) + proc = httpProc(request, 'serverStatus/litespeedStatus.html', + {"processList": processList, + "liteSpeedVersionStatus": "For some reaons not able to load version details, see CyberCP main log file.", + 'OLS': OLS, 'message': message}, 'admin') + return proc.render() if (processList != 0): dataForHtml = {"processList": processList, "lsversion": lsversion, "modules": modules, "loadedModules": loadedModules, 'OLS': OLS, 'message': message} - return render(request, "serverStatus/litespeedStatus.html", dataForHtml) + proc = httpProc(request, 'serverStatus/litespeedStatus.html', dataForHtml, 'admin') + return proc.render() else: dataForHtml = {"lsversion": lsversion, "modules": modules, "loadedModules": loadedModules, 'OLS': OLS, 'message': message} - return render(request, "serverStatus/litespeedStatus.html", dataForHtml) + proc = httpProc(request, 'serverStatus/litespeedStatus.html', dataForHtml, 'admin') + return proc.render() except KeyError as msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[litespeedStatus]") @@ -132,21 +127,8 @@ def stopOrRestartLitespeed(request): return HttpResponse("Not Logged in as admin") def cyberCPMainLogFile(request): - try: - userID = request.session['userID'] - - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - return render(request, 'serverStatus/cybercpmainlogfile.html') - - except KeyError as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[cyberCPMainLogFile]") - return redirect(loadLoginPage) + proc = httpProc(request, 'serverStatus/cybercpmainlogfile.html', None, 'admin') + return proc.render() def getFurtherDataFromLogFile(request): try: @@ -173,30 +155,21 @@ def getFurtherDataFromLogFile(request): def services(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + data = {} - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - data = {} + if ProcessUtilities.decideServer() == ProcessUtilities.OLS: + data['serverName'] = 'OpenLiteSpeed' + else: + data['serverName'] = 'LiteSpeed Ent' - if ProcessUtilities.decideServer() == ProcessUtilities.OLS: - data['serverName'] = 'OpenLiteSpeed' - else: - data['serverName'] = 'LiteSpeed Ent' + dockerInstallPath = '/usr/bin/docker' + if not os.path.exists(dockerInstallPath): + data['isDocker'] = False + else: + data['isDocker'] = True - dockerInstallPath = '/usr/bin/docker' - if not os.path.exists(dockerInstallPath): - data['isDocker'] = False - else: - data['isDocker'] = True - - return render(request, 'serverStatus/services.html', data) - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'serverStatus/services.html', data, 'admin') + return proc.render() def servicesStatus(request): try: @@ -536,22 +509,8 @@ def changeLicense(request): def topProcesses(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - templateName = "serverStatus/topProcesses.html" - proc = httpProc(request, templateName) - return proc.renderPre() - - except KeyError as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[litespeedStatus]") - return redirect(loadLoginPage) + proc = httpProc(request, "serverStatus/topProcesses.html", None, 'admin') + return proc.render() def topProcessesStatus(request): try: @@ -764,22 +723,8 @@ def killProcess(request): return HttpResponse(final_json) def packageManager(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - templateName = "serverStatus/packageManager.html" - proc = httpProc(request, templateName) - return proc.renderPre() - - except KeyError as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[packageManager]") - return redirect(loadLoginPage) + proc = httpProc(request, "serverStatus/packageManager.html", None, 'admin') + return proc.render() def fetchPackages(request): try: @@ -1181,23 +1126,9 @@ def lockStatus(request): def CyberPanelPort(request): - try: - userID = request.session['userID'] - - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - port = ProcessUtilities.fetchCurrentPort() - - return render(request, 'serverStatus/changeCyberPanelPort.html', {'port': port}) - - except KeyError as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[CyberPanelPort]") - return redirect(loadLoginPage) + port = ProcessUtilities.fetchCurrentPort() + proc = httpProc(request, "serverStatus/changeCyberPanelPort.html", {'port': port}, 'admin') + return proc.render() def submitPortChange(request): 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!', diff --git a/static/backup/backup.js b/static/backup/backup.js index 9105a96c5..49980c5f9 100644 --- a/static/backup/backup.js +++ b/static/backup/backup.js @@ -6,6 +6,21 @@ app.controller('backupWebsiteControl', function ($scope, $http, $timeout) { + $(document).ready(function () { + $(".destinationHide").hide(); + $('#create-backup-select').select2(); + }); + + $('#create-backup-select').on('select2:select', function (e) { + var data = e.params.data; + $scope.websiteToBeBacked = data.text; + $(".destinationHide").show(); + getBackupStatus(); + populateCurrentRecords(); + $scope.destination = false; + $scope.runningBackup = true; + }); + $scope.destination = true; $scope.backupButton = true; $scope.backupLoading = true; @@ -43,7 +58,6 @@ app.controller('backupWebsiteControl', function ($scope, $http, $timeout) { }; - function getBackupStatus() { $scope.backupLoadingBottom = false; @@ -111,12 +125,10 @@ app.controller('backupWebsiteControl', function ($scope, $http, $timeout) { }; - $scope.destinationSelection = function () { $scope.backupButton = false; }; - function populateCurrentRecords() { var websiteToBeBacked = $scope.websiteToBeBacked; @@ -152,7 +164,6 @@ app.controller('backupWebsiteControl', function ($scope, $http, $timeout) { }; - $scope.createBackup = function () { var websiteToBeBacked = $scope.websiteToBeBacked; @@ -189,10 +200,8 @@ app.controller('backupWebsiteControl', function ($scope, $http, $timeout) { }; - $scope.deleteBackup = function (id) { - url = "/backup/deleteBackup"; var data = { diff --git a/static/baseTemplate/assets/finalBase/favicon.png b/static/baseTemplate/assets/finalBase/favicon.png new file mode 100644 index 000000000..f72790ed5 Binary files /dev/null and b/static/baseTemplate/assets/finalBase/favicon.png differ diff --git a/static/baseTemplate/assets/finalLoginPageCSS/allCss.css b/static/baseTemplate/assets/finalLoginPageCSS/allCss.css index 5c059ba8c..71f8dae4d 100644 --- a/static/baseTemplate/assets/finalLoginPageCSS/allCss.css +++ b/static/baseTemplate/assets/finalLoginPageCSS/allCss.css @@ -1642,4 +1642,4 @@ border-style: none; @media (max-width: 720px) { .text-center-sm { text-align: center; -} \ No newline at end of file +} diff --git a/static/baseTemplate/custom-js/system-status.js b/static/baseTemplate/custom-js/system-status.js index 41680df3f..1f6fe8d9d 100644 --- a/static/baseTemplate/custom-js/system-status.js +++ b/static/baseTemplate/custom-js/system-status.js @@ -98,6 +98,23 @@ app.filter('getwebsitename', function () { }; }); +function getWebsiteName(domain){ + if (domain !== undefined) { + + domain = domain.replace(/-/g, ''); + + var domainName = domain.split("."); + + var finalDomainName = domainName[0]; + + if (finalDomainName.length > 5) { + finalDomainName = finalDomainName.substring(0, 4); + } + + return finalDomainName; + } +} + app.controller('systemStatusInfo', function ($scope, $http, $timeout) { //getStuff(); diff --git a/static/databases/databases.js b/static/databases/databases.js index d42958142..7b10cf48a 100644 --- a/static/databases/databases.js +++ b/static/databases/databases.js @@ -6,25 +6,31 @@ /* Java script code to create database */ app.controller('createDatabase', function ($scope, $http) { - $scope.createDatabaseLoading = true; - $scope.dbDetails = true; - $scope.databaseCreationFailed = true; - $scope.databaseCreated = true; - $scope.couldNotConnect = true; - $scope.generatedPasswordView = true; + $(document).ready(function () { + $(".dbDetails").hide(); + $(".generatedPasswordDetails").hide(); + $('#create-database-select').select2(); + }); + + $('#create-database-select').on('select2:select', function (e) { + var data = e.params.data; + $scope.databaseWebsite = data.text; + $(".dbDetails").show(); + $("#domainDatabase").text(getWebsiteName(data.text)); + $("#domainUsername").text(getWebsiteName(data.text)); + }); $scope.showDetailsBoxes = function () { $scope.dbDetails = false; - }; + } + + $scope.createDatabaseLoading = true; $scope.createDatabase = function () { $scope.createDatabaseLoading = false; $scope.dbDetails = false; - $scope.databaseCreationFailed = true; - $scope.databaseCreated = true; - $scope.couldNotConnect = true; var databaseWebsite = $scope.databaseWebsite; @@ -65,26 +71,24 @@ app.controller('createDatabase', function ($scope, $http) { function ListInitialDatas(response) { - if (response.data.createDBStatus == 1) { + if (response.data.createDBStatus === 1) { $scope.createDatabaseLoading = true; $scope.dbDetails = false; - $scope.databaseCreationFailed = true; - $scope.databaseCreated = false; - $scope.couldNotConnect = true; - - - } - - else { - + new PNotify({ + title: 'Success!', + text: 'Database successfully created.', + type: 'success' + }); + } else { $scope.createDatabaseLoading = true; $scope.dbDetails = false; - $scope.databaseCreationFailed = false; - $scope.databaseCreated = true; - $scope.couldNotConnect = true; - $scope.errorMessage = response.data.error_message; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); } @@ -96,21 +100,23 @@ app.controller('createDatabase', function ($scope, $http) { $scope.createDatabaseLoading = true; $scope.dbDetails = true; - $scope.databaseCreationFailed = true; - $scope.databaseCreated = true; - $scope.couldNotConnect = false; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); } }; $scope.generatePassword = function () { - $scope.generatedPasswordView = false; + $(".generatedPasswordDetails").show(); $scope.dbPassword = randomPassword(16); }; $scope.usePassword = function () { - $scope.generatedPasswordView = true; + $(".generatedPasswordDetails").hide(); }; }); @@ -170,9 +176,7 @@ app.controller('deleteDatabase', function ($scope, $http) { $scope.couldNotConnect = true; - } - - else { + } else { $scope.deleteDatabaseLoading = true; $scope.fetchedDatabases = true; $scope.databaseDeletionFailed = false; @@ -240,9 +244,7 @@ app.controller('deleteDatabase', function ($scope, $http) { $scope.couldNotConnect = true; - } - - else { + } else { $scope.deleteDatabaseLoading = true; $scope.fetchedDatabases = true; $scope.databaseDeletionFailed = false; @@ -344,8 +346,7 @@ app.controller('listDBs', function ($scope, $http) { $scope.dbLoading = true; $scope.domainFeteched = $scope.selectedDomain; - } - else { + } else { $scope.notificationsBox = false; $scope.canNotChangePassword = false; $scope.dbLoading = true; @@ -411,8 +412,7 @@ app.controller('listDBs', function ($scope, $http) { $scope.domainFeteched = $scope.selectedDomain; - } - else { + } else { $scope.recordsFetched = true; $scope.passwordChanged = true; $scope.canNotChangePassword = true; @@ -481,8 +481,7 @@ app.controller('listDBs', function ($scope, $http) { $scope.dbHost = response.data.dbHost; - } - else { + } else { new PNotify({ title: 'Operation Failed!', text: response.data.error_message, @@ -537,8 +536,7 @@ app.controller('listDBs', function ($scope, $http) { type: 'success' }); - } - else { + } else { new PNotify({ title: 'Operation Failed!', text: response.data.error_message, @@ -570,7 +568,7 @@ app.controller('listDBs', function ($scope, $http) { app.controller('phpMyAdmin', function ($scope, $http, $window) { $scope.cyberPanelLoading = true; - $scope.generateAccess = function() { + $scope.generateAccess = function () { $scope.cyberPanelLoading = false; @@ -593,12 +591,14 @@ app.controller('phpMyAdmin', function ($scope, $http, $window) { if (response.data.status === 1) { var rUrl = '/phpmyadmin/phpmyadminsignin.php?username=' + response.data.username + '&token=' + response.data.token; $window.location.href = rUrl; + } else { } - else {} } - function cantLoadInitialDatas(response) {$scope.cyberPanelLoading = true;} + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + } } diff --git a/static/ftp/ftp.js b/static/ftp/ftp.js index a80377e6b..113845c8f 100644 --- a/static/ftp/ftp.js +++ b/static/ftp/ftp.js @@ -6,22 +6,22 @@ /* Java script code to create account */ app.controller('createFTPAccount', function ($scope, $http) { + + + $(document).ready(function () { + $( ".ftpDetails" ).hide(); + $( ".ftpPasswordView" ).hide(); + $('.create-ftp-acct-select').select2(); + }); + + $('.create-ftp-acct-select').on('select2:select', function (e) { + var data = e.params.data; + $scope.ftpDomain = data.text; + $( ".ftpDetails" ).show(); + + }); + $scope.ftpLoading = true; - $scope.ftpDetails = true; - $scope.canNotCreate = true; - $scope.successfullyCreated = true; - $scope.couldNotConnect = true; - - $scope.showFTPDetails = function () { - - $scope.ftpLoading = true; - $scope.ftpDetails = false; - $scope.canNotCreate = true; - $scope.successfullyCreated = true; - $scope.couldNotConnect = true; - - - }; $scope.createFTPAccount = function () { @@ -62,37 +62,35 @@ app.controller('createFTPAccount', function ($scope, $http) { function ListInitialDatas(response) { - if (response.data.creatFTPStatus == 1) { - + if (response.data.creatFTPStatus === 1) { $scope.ftpLoading = true; - $scope.ftpDetails = false; - $scope.canNotCreate = true; - $scope.successfullyCreated = false; - $scope.couldNotConnect = true; + new PNotify({ + title: 'Success!', + text: 'FTP account successfully created.', + type: 'success' + }); } else { $scope.ftpLoading = true; - $scope.ftpDetails = false; - $scope.canNotCreate = false; - $scope.successfullyCreated = true; - $scope.couldNotConnect = true; - - $scope.errorMessage = response.data.error_message; + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); } - } - function cantLoadInitialDatas(response) { $scope.ftpLoading = true; - $scope.ftpDetails = false; - $scope.canNotCreate = true; - $scope.successfullyCreated = true; - $scope.couldNotConnect = false; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); } @@ -109,15 +107,13 @@ app.controller('createFTPAccount', function ($scope, $http) { /// - $scope.generatedPasswordView = true; - $scope.generatePassword = function () { - $scope.generatedPasswordView = false; + $( ".ftpPasswordView" ).show(); $scope.ftpPassword = randomPassword(16); }; $scope.usePassword = function () { - $scope.generatedPasswordView = true; + $(".ftpPasswordView" ).hide(); }; }); diff --git a/static/loginSystem/login-system.js b/static/loginSystem/login-system.js new file mode 100644 index 000000000..d5681e4a8 --- /dev/null +++ b/static/loginSystem/login-system.js @@ -0,0 +1,110 @@ +/** + * Created by usman on 7/24/17. + */ + +/* Utilities */ + + +function getCookie(name) { + var cookieValue = null; + if (document.cookie && document.cookie !== '') { + var cookies = document.cookie.split(';'); + for (var i = 0; i < cookies.length; i++) { + var cookie = jQuery.trim(cookies[i]); + // Does this cookie string begin with the name we want? + if (cookie.substring(0, name.length + 1) === (name + '=')) { + cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); + break; + } + } + } + return cookieValue; +} + +/* Utilities ends here */ + + +/* Java script code to Check Login status */ +$("#verifyingLogin").hide(); +$("#loginFailed").hide(); + + +var application = angular.module('loginSystem', []); + +application.config(['$interpolateProvider', + + function ($interpolateProvider) { + $interpolateProvider.startSymbol('{$'); + $interpolateProvider.endSymbol('$}'); + } +]); + +application.controller('loginSystem', function ($scope, $http, $window) { + + $scope.verifyCode = true; + + $scope.verifyLoginCredentials = function () { + + $("#verifyingLogin").show(); + + + var username = $scope.username; + var password = $scope.password; + var languageSelection = $scope.languageSelection; + + + url = "/verifyLogin"; + + var data = { + username: username, + password: password, + languageSelection: languageSelection, + twofa: $scope.twofa + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + + if (response.data.loginStatus === 0) { + $scope.errorMessage = response.data.error_message; + $("#loginFailed").fadeIn(); + }else if(response.data.loginStatus === 2){ + $scope.verifyCode = false; + } + else { + $("#loginFailed").hide(); + $window.location.href = '/base/'; + } + + + $("#verifyingLogin").hide(); + } + + function cantLoadInitialData(response) { + } + + + }; + + $scope.initiateLogin = function ($event) { + var keyCode = $event.which || $event.keyCode; + if (keyCode === 13) { + $scope.verifyLoginCredentials(); + + } + + }; + + +}); + + +/* Java script code to to Check Login status ends here */ diff --git a/static/userManagment/userManagment.js b/static/userManagment/userManagment.js index 2dfc503b2..221d0e34b 100644 --- a/static/userManagment/userManagment.js +++ b/static/userManagment/userManagment.js @@ -458,6 +458,7 @@ app.controller('deleteUser', function ($scope, $http) { /* Java script code to create acl */ + app.controller('createACLCTRL', function ($scope, $http) { $scope.aclLoading = true; @@ -520,11 +521,13 @@ app.controller('createACLCTRL', function ($scope, $http) { // Backup Management $scope.createBackup = true; + $scope.googleDriveBackups = true; $scope.restoreBackup = false; $scope.addDeleteDestinations = false; $scope.scheDuleBackups = false; $scope.remoteBackups = false; + // SSL Management $scope.manageSSL = true; @@ -599,6 +602,7 @@ app.controller('createACLCTRL', function ($scope, $http) { // Backup Management createBackup: $scope.createBackup, + googleDriveBackups: $scope.googleDriveBackups, restoreBackup: $scope.restoreBackup, addDeleteDestinations: $scope.addDeleteDestinations, scheDuleBackups: $scope.scheDuleBackups, @@ -976,6 +980,7 @@ app.controller('modifyACLCtrl', function ($scope, $http) { // Backup Management $scope.createBackup = Boolean(response.data.createBackup); + $scope.googleDriveBackups = Boolean(response.data.googleDriveBackups); $scope.restoreBackup = Boolean(response.data.restoreBackup); $scope.addDeleteDestinations = Boolean(response.data.addDeleteDestinations); $scope.scheDuleBackups = Boolean(response.data.scheDuleBackups); @@ -1076,6 +1081,7 @@ app.controller('modifyACLCtrl', function ($scope, $http) { // Backup Management createBackup: $scope.createBackup, + googleDriveBackups: $scope.googleDriveBackups, restoreBackup: $scope.restoreBackup, addDeleteDestinations: $scope.addDeleteDestinations, scheDuleBackups: $scope.scheDuleBackups, diff --git a/static/websiteFunctions/websiteFunctions.js b/static/websiteFunctions/websiteFunctions.js index d1f948405..ca0fed440 100644 --- a/static/websiteFunctions/websiteFunctions.js +++ b/static/websiteFunctions/websiteFunctions.js @@ -2830,6 +2830,8 @@ app.controller('manageCronController', function ($scope, $http) { $("#cronEditSuccess").hide(); $("#fetchCronFailure").hide(); + $scope.websiteToBeModified = $("#domain").text(); + $scope.fetchWebsites = function () { $("#manageCronLoading").show(); @@ -2880,6 +2882,7 @@ app.controller('manageCronController', function ($scope, $http) { $("#cronEditSuccess").hide(); } }; + $scope.fetchWebsites(); $scope.fetchCron = function (cronLine) { @@ -3033,7 +3036,6 @@ app.controller('manageCronController', function ($scope, $http) { } }; - $scope.removeCron = function (line) { $("#manageCronLoading").show(); diff --git a/tuning/tuning.py b/tuning/tuning.py index 74eedbeed..8afff2e2d 100755 --- a/tuning/tuning.py +++ b/tuning/tuning.py @@ -2,10 +2,13 @@ import os.path import sys import django + +from plogical.httpProc import httpProc + sys.path.append('/usr/local/CyberCP') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") django.setup() -from django.shortcuts import render,redirect +from django.shortcuts import redirect from django.http import HttpResponse import json import plogical.CyberCPLogFileWriter as logging @@ -18,52 +21,28 @@ from plogical.processUtilities import ProcessUtilities class tuningManager: def loadTuningHome(self, request, userID): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - return render(request, 'tuning/index.html', {}) - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'tuning/index.html', + None, 'admin') + return proc.render() def liteSpeedTuning(self, request, userID): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - return render(request, 'tuning/liteSpeedTuning.html', {}) - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'tuning/liteSpeedTuning.html', + None, 'admin') + return proc.render() def phpTuning(self, request, userID): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - if ProcessUtilities.decideServer() == ProcessUtilities.OLS: - websitesName = ACLManager.findAllSites(currentACL, userID) - OLS = 1 - return render(request, 'tuning/phpTuning.html', {'websiteList': websitesName, 'OLS': OLS}) - else: - OLS = 0 - return render(request, 'tuning/phpTuning.html', {'OLS': OLS}) - - except KeyError: - return redirect(loadLoginPage) + currentACL = ACLManager.loadedACL(userID) + if ProcessUtilities.decideServer() == ProcessUtilities.OLS: + websitesName = ACLManager.findAllSites(currentACL, userID) + OLS = 1 + proc = httpProc(request, 'tuning/phpTuning.html', + {'websiteList': websitesName, 'OLS': OLS}, 'admin') + return proc.render() + else: + OLS = 0 + proc = httpProc(request, 'tuning/phpTuning.html', + {'OLS': OLS}, 'admin') + return proc.render() def tuneLitespeed(self, userID, data): try: diff --git a/tuning/views.py b/tuning/views.py index 0e86d44ff..61d97ba27 100755 --- a/tuning/views.py +++ b/tuning/views.py @@ -1,6 +1,5 @@ # -*- coding: utf-8 -*- - from django.shortcuts import redirect import json from loginSystem.views import loadLoginPage diff --git a/userManagment/static/userManagment/userManagment.js b/userManagment/static/userManagment/userManagment.js index 2dfc503b2..221d0e34b 100755 --- a/userManagment/static/userManagment/userManagment.js +++ b/userManagment/static/userManagment/userManagment.js @@ -458,6 +458,7 @@ app.controller('deleteUser', function ($scope, $http) { /* Java script code to create acl */ + app.controller('createACLCTRL', function ($scope, $http) { $scope.aclLoading = true; @@ -520,11 +521,13 @@ app.controller('createACLCTRL', function ($scope, $http) { // Backup Management $scope.createBackup = true; + $scope.googleDriveBackups = true; $scope.restoreBackup = false; $scope.addDeleteDestinations = false; $scope.scheDuleBackups = false; $scope.remoteBackups = false; + // SSL Management $scope.manageSSL = true; @@ -599,6 +602,7 @@ app.controller('createACLCTRL', function ($scope, $http) { // Backup Management createBackup: $scope.createBackup, + googleDriveBackups: $scope.googleDriveBackups, restoreBackup: $scope.restoreBackup, addDeleteDestinations: $scope.addDeleteDestinations, scheDuleBackups: $scope.scheDuleBackups, @@ -976,6 +980,7 @@ app.controller('modifyACLCtrl', function ($scope, $http) { // Backup Management $scope.createBackup = Boolean(response.data.createBackup); + $scope.googleDriveBackups = Boolean(response.data.googleDriveBackups); $scope.restoreBackup = Boolean(response.data.restoreBackup); $scope.addDeleteDestinations = Boolean(response.data.addDeleteDestinations); $scope.scheDuleBackups = Boolean(response.data.scheDuleBackups); @@ -1076,6 +1081,7 @@ app.controller('modifyACLCtrl', function ($scope, $http) { // Backup Management createBackup: $scope.createBackup, + googleDriveBackups: $scope.googleDriveBackups, restoreBackup: $scope.restoreBackup, addDeleteDestinations: $scope.addDeleteDestinations, scheDuleBackups: $scope.scheDuleBackups, diff --git a/userManagment/templates/userManagment/createACL.html b/userManagment/templates/userManagment/createACL.html index 298adf867..111cc9deb 100755 --- a/userManagment/templates/userManagment/createACL.html +++ b/userManagment/templates/userManagment/createACL.html @@ -353,6 +353,17 @@
    + + +
    +
    + +
    +
    +
    diff --git a/userManagment/templates/userManagment/modifyACL.html b/userManagment/templates/userManagment/modifyACL.html index e2043cedc..9c1f3156d 100755 --- a/userManagment/templates/userManagment/modifyACL.html +++ b/userManagment/templates/userManagment/modifyACL.html @@ -357,6 +357,17 @@
    + + +
    +
    + +
    +
    +
    diff --git a/userManagment/views.py b/userManagment/views.py index 3c5b8c56a..c59d9277b 100755 --- a/userManagment/views.py +++ b/userManagment/views.py @@ -7,8 +7,8 @@ from loginSystem.views import loadLoginPage from loginSystem.models import Administrator, ACL import json from plogical import hashPassword -from plogical import CyberCPLogFileWriter as logging from plogical.acl import ACLManager +from plogical.httpProc import httpProc from plogical.virtualHostUtilities import virtualHostUtilities from CyberCP.secMiddleware import secMiddleware from CyberCP.SecurityLevel import SecurityLevel @@ -16,81 +16,67 @@ from CyberCP.SecurityLevel import SecurityLevel # Create your views here. def loadUserHome(request): - try: - val = request.session['userID'] - try: - admin = Administrator.objects.get(pk=val) - currentACL = ACLManager.loadedACL(val) - if currentACL['admin'] == 1: - listUsers = 1 - else: - listUsers = currentACL['listUsers'] - return render(request, 'userManagment/index.html', {"type": admin.type, 'listUsers': listUsers}) - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse(str(msg)) - except KeyError: - return redirect(loadLoginPage) + val = request.session['userID'] + admin = Administrator.objects.get(pk=val) + currentACL = ACLManager.loadedACL(val) + + if currentACL['admin'] == 1: + listUsers = 1 + else: + listUsers = currentACL['listUsers'] + + proc = httpProc(request, 'userManagment/index.html', + {"type": admin.type, 'listUsers': listUsers}, 'listUsers') + return proc.render() def viewProfile(request): - try: - userID = request.session['userID'] + userID = request.session['userID'] + admin = Administrator.objects.get(pk=userID) - admin = Administrator.objects.get(pk=userID) + AdminData = {} - AdminData = {} + AdminData['userName'] = admin.userName + AdminData['firstName'] = admin.firstName + AdminData['lastName'] = admin.lastName + AdminData['websitesLimit'] = admin.initWebsitesLimit + AdminData['email'] = admin.email + AdminData['accountACL'] = admin.acl.name - AdminData['userName'] = admin.userName - AdminData['firstName'] = admin.firstName - AdminData['lastName'] = admin.lastName - AdminData['websitesLimit'] = admin.initWebsitesLimit - AdminData['email'] = admin.email - AdminData['accountACL'] = admin.acl.name - - return render(request, 'userManagment/userProfile.html', AdminData) - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'userManagment/userProfile.html', + AdminData) + return proc.render() def createUser(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) - if currentACL['admin'] == 1: - aclNames = ACLManager.unFileteredACLs() - return render(request, 'userManagment/createUser.html', - {'aclNames': aclNames, 'securityLevels': SecurityLevel.list()}) - elif currentACL['changeUserACL'] == 1: - aclNames = ACLManager.unFileteredACLs() - return render(request, 'userManagment/createUser.html', - {'aclNames': aclNames, 'securityLevels': SecurityLevel.list()}) - elif currentACL['createNewUser'] == 1: - aclNames = ['user'] - return render(request, 'userManagment/createUser.html', - {'aclNames': aclNames, 'securityLevels': SecurityLevel.list()}) - else: - return ACLManager.loadError() - - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return redirect(loadLoginPage) + if currentACL['admin'] == 1: + aclNames = ACLManager.unFileteredACLs() + proc = httpProc(request, 'userManagment/createUser.html', + {'aclNames': aclNames, 'securityLevels': SecurityLevel.list()}) + return proc.render() + elif currentACL['changeUserACL'] == 1: + aclNames = ACLManager.unFileteredACLs() + proc = httpProc(request, 'userManagment/createUser.html', + {'aclNames': aclNames, 'securityLevels': SecurityLevel.list()}) + return proc.render() + elif currentACL['createNewUser'] == 1: + aclNames = ['user'] + proc = httpProc(request, 'userManagment/createUser.html', + {'aclNames': aclNames, 'securityLevels': SecurityLevel.list()}) + return proc.render() + else: + return ACLManager.loadError() def apiAccess(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - adminNames = ACLManager.loadDeletionUsers(userID, currentACL) - adminNames.append("admin") - return render(request, 'userManagment/apiAccess.html', {'acctNames': adminNames}) - else: - return ACLManager.loadError() - - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return redirect(loadLoginPage) + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadDeletionUsers(userID, currentACL) + adminNames.append("admin") + proc = httpProc(request, 'userManagment/apiAccess.html', + {'acctNames': adminNames}, 'admin') + return proc.render() def saveChangesAPIAccess(request): try: @@ -250,13 +236,11 @@ def submitUserCreation(request): def modifyUsers(request): - try: - userID = request.session['userID'] - userNames = ACLManager.loadAllUsers(userID) - return render(request, 'userManagment/modifyUser.html', - {"acctNames": userNames, 'securityLevels': SecurityLevel.list()}) - except KeyError: - return redirect(loadLoginPage) + userID = request.session['userID'] + userNames = ACLManager.loadAllUsers(userID) + proc = httpProc(request, 'userManagment/modifyUser.html', + {"acctNames": userNames, 'securityLevels': SecurityLevel.list()}) + return proc.render() def fetchUserDetails(request): try: @@ -405,22 +389,21 @@ def saveModifications(request): return HttpResponse(json_data) def deleteUser(request): - try: - userID = request.session['userID'] + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - adminNames = ACLManager.loadDeletionUsers(userID, currentACL) - return render(request, 'userManagment/deleteUser.html', {"acctNames": adminNames}) - elif currentACL['deleteUser'] == 1: - adminNames = ACLManager.loadDeletionUsers(userID, currentACL) - return render(request, 'userManagment/deleteUser.html', {"acctNames": adminNames}) - else: - return ACLManager.loadError() - - except KeyError: - return redirect(loadLoginPage) + if currentACL['admin'] == 1: + adminNames = ACLManager.loadDeletionUsers(userID, currentACL) + proc = httpProc(request, 'userManagment/deleteUser.html', + {"acctNames": adminNames}) + return proc.render() + elif currentACL['deleteUser'] == 1: + adminNames = ACLManager.loadDeletionUsers(userID, currentACL) + proc = httpProc(request, 'userManagment/deleteUser.html', + {"acctNames": adminNames}) + return proc.render() + else: + return ACLManager.loadError() def submitUserDeletion(request): @@ -492,16 +475,9 @@ def submitUserDeletion(request): return HttpResponse(json_data) def createNewACL(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - return render(request, 'userManagment/createACL.html') - else: - return ACLManager.loadError() - except KeyError: - return redirect(loadLoginPage) + proc = httpProc(request, 'userManagment/createACL.html', + None, 'admin') + return proc.render() def createACLFunc(request): try: @@ -514,74 +490,12 @@ def createACLFunc(request): ## Version Management - newACL = ACL(name=data['aclName'], - adminStatus=int(data['makeAdmin']), + if data['makeAdmin']: + data['adminStatus'] = 1 + else: + data['adminStatus'] = 0 - versionManagement=int(data['versionManagement']), - - ## User Management - createNewUser=int(data['createNewUser']), - listUsers=int(data['listUsers']), - resellerCenter=int(data['resellerCenter']), - deleteUser=int(data['deleteUser']), - changeUserACL=int(data['changeUserACL']), - - ## Website Management - - createWebsite=int(data['createWebsite']), - modifyWebsite=int(data['modifyWebsite']), - suspendWebsite=int(data['suspendWebsite']), - deleteWebsite=int(data['deleteWebsite']), - - ## Package Management - - createPackage=int(data['createPackage']), - listPackages=int(data['listPackages']), - deletePackage=int(data['deletePackage']), - modifyPackage=int(data['modifyPackage']), - - ## Database Management - - createDatabase=int(data['createDatabase']), - deleteDatabase=int(data['deleteDatabase']), - listDatabases=int(data['listDatabases']), - - ## DNS Management - - createNameServer=int(data['createNameServer']), - createDNSZone=int(data['createDNSZone']), - deleteZone=int(data['deleteZone']), - addDeleteRecords=int(data['addDeleteRecords']), - - ## Email Management - - createEmail=int(data['createEmail']), - listEmails=int(data['listEmails']), - deleteEmail=int(data['deleteEmail']), - emailForwarding=int(data['emailForwarding']), - changeEmailPassword=int(data['changeEmailPassword']), - dkimManager=int(data['dkimManager']), - - ## FTP Management - - createFTPAccount=int(data['createFTPAccount']), - deleteFTPAccount=int(data['deleteFTPAccount']), - listFTPAccounts=int(data['listFTPAccounts']), - - ## Backup Management - - createBackup=int(data['createBackup']), - restoreBackup=int(data['restoreBackup']), - addDeleteDestinations=int(data['addDeleteDestinations']), - scheDuleBackups=int(data['scheDuleBackups']), - remoteBackups=int(data['remoteBackups']), - - ## SSL Management - - manageSSL=int(data['manageSSL']), - hostnameSSL=int(data['hostnameSSL']), - mailServerSSL=int(data['mailServerSSL']), - ) + newACL = ACL(name=data['aclName'],config=json.dumps(data)) newACL.save() finalResponse = {'status': 1} @@ -596,17 +510,10 @@ def createACLFunc(request): return HttpResponse(json_data) def deleteACL(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - aclNames = ACLManager.findAllACLs() - return render(request, 'userManagment/deleteACL.html', {'aclNames': aclNames}) - else: - return ACLManager.loadError() - except KeyError: - return redirect(loadLoginPage) + aclNames = ACLManager.findAllACLs() + proc = httpProc(request, 'userManagment/deleteACL.html', + {'aclNames': aclNames}, 'admin') + return proc.render() def deleteACLFunc(request): try: @@ -635,17 +542,10 @@ def deleteACLFunc(request): return HttpResponse(json_data) def modifyACL(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - aclNames = ACLManager.findAllACLs() - return render(request, 'userManagment/modifyACL.html', {'aclNames': aclNames}) - else: - return ACLManager.loadError() - except KeyError: - return redirect(loadLoginPage) + aclNames = ACLManager.findAllACLs() + proc = httpProc(request, 'userManagment/modifyACL.html', + {'aclNames': aclNames}, 'admin') + return proc.render() def fetchACLDetails(request): try: @@ -658,75 +558,8 @@ def fetchACLDetails(request): ## Version Management finalResponse = {} - acl = ACL.objects.get(name=data['aclToModify']) - finalResponse['versionManagement'] = acl.versionManagement - finalResponse['adminStatus'] = acl.adminStatus - - ## User Management - - finalResponse['createNewUser'] = acl.createNewUser - finalResponse['listUsers'] = acl.listUsers - finalResponse['resellerCenter'] = acl.resellerCenter - finalResponse['deleteUser'] = acl.deleteUser - finalResponse['changeUserACL'] = acl.changeUserACL - - ## Website Management - - finalResponse['createWebsite'] = acl.createWebsite - finalResponse['modifyWebsite'] = acl.modifyWebsite - finalResponse['suspendWebsite'] = acl.suspendWebsite - finalResponse['deleteWebsite'] = acl.deleteWebsite - - ## Package Management - - finalResponse['createPackage'] = acl.createPackage - finalResponse['listPackages'] = acl.listPackages - finalResponse['deletePackage'] = acl.deletePackage - finalResponse['modifyPackage'] = acl.modifyPackage - - ## Database Management - - finalResponse['createDatabase'] = acl.createDatabase - finalResponse['deleteDatabase'] = acl.deleteDatabase - finalResponse['listDatabases'] = acl.listDatabases - - ## DNS Management - - finalResponse['createNameServer'] = acl.createNameServer - finalResponse['createDNSZone'] = acl.createDNSZone - finalResponse['deleteZone'] = acl.deleteZone - finalResponse['addDeleteRecords'] = acl.addDeleteRecords - - ## Email Management - - finalResponse['createEmail'] = acl.createEmail - finalResponse['listEmails'] = acl.listEmails - finalResponse['deleteEmail'] = acl.deleteEmail - finalResponse['emailForwarding'] = acl.emailForwarding - finalResponse['changeEmailPassword'] = acl.changeEmailPassword - finalResponse['dkimManager'] = acl.dkimManager - - ## FTP Management - - finalResponse['createFTPAccount'] = acl.createFTPAccount - finalResponse['deleteFTPAccount'] = acl.deleteFTPAccount - finalResponse['listFTPAccounts'] = acl.listFTPAccounts - - ## Backup Management - - finalResponse['createBackup'] = acl.createBackup - finalResponse['restoreBackup'] = acl.restoreBackup - finalResponse['addDeleteDestinations'] = acl.addDeleteDestinations - finalResponse['scheDuleBackups'] = acl.scheDuleBackups - finalResponse['remoteBackups'] = acl.remoteBackups - - ## SSL Management - - finalResponse['manageSSL'] = acl.manageSSL - finalResponse['hostnameSSL'] = acl.hostnameSSL - finalResponse['mailServerSSL'] = acl.mailServerSSL - + finalResponse = json.loads(acl.config) finalResponse['status'] = 1 else: return ACLManager.loadErrorJson() @@ -750,73 +583,7 @@ def submitACLModifications(request): ## Version Management acl = ACL.objects.get(name=data['aclToModify']) - acl.adminStatus = int(data['adminStatus']) - acl.versionManagement = int(data['versionManagement']) - - ## User Management - - acl.createNewUser = int(data['createNewUser']) - acl.listUsers = int(data['listUsers']) - acl.resellerCenter = int(data['resellerCenter']) - acl.deleteUser = int(data['deleteUser']) - acl.changeUserACL = int(data['changeUserACL']) - - ## Website Management - - acl.createWebsite = int(data['createWebsite']) - acl.modifyWebsite = int(data['modifyWebsite']) - acl.suspendWebsite = int(data['suspendWebsite']) - acl.deleteWebsite = int(data['deleteWebsite']) - - ## Package Management - - acl.createPackage = int(data['createPackage']) - acl.listPackages = int(data['listPackages']) - acl.deletePackage = int(data['deletePackage']) - acl.modifyPackage = int(data['modifyPackage']) - - ## Database Management - - acl.createDatabase = int(data['createDatabase']) - acl.deleteDatabase = int(data['deleteDatabase']) - acl.listDatabases = int(data['listDatabases']) - - ## DNS Management - - acl.createNameServer = int(data['createNameServer']) - acl.createDNSZone = int(data['createDNSZone']) - acl.deleteZone = int(data['deleteZone']) - acl.addDeleteRecords = int(data['addDeleteRecords']) - - ## Email Management - - acl.createEmail = int(data['createEmail']) - acl.listEmails = int(data['listEmails']) - acl.deleteEmail = int(data['deleteEmail']) - acl.emailForwarding = int(data['emailForwarding']) - acl.changeEmailPassword = int(data['changeEmailPassword']) - acl.dkimManager = int(data['dkimManager']) - - ## FTP Management - - acl.createFTPAccount = int(data['createFTPAccount']) - acl.deleteFTPAccount = int(data['deleteFTPAccount']) - acl.listFTPAccounts = int(data['listFTPAccounts']) - - ## Backup Management - - acl.createBackup = int(data['createBackup']) - acl.restoreBackup = int(data['restoreBackup']) - acl.addDeleteDestinations = int(data['addDeleteDestinations']) - acl.scheDuleBackups = int(data['scheDuleBackups']) - acl.remoteBackups = int(data['remoteBackups']) - - ## SSL Management - - acl.manageSSL = int(data['manageSSL']) - acl.hostnameSSL = int(data['hostnameSSL']) - acl.mailServerSSL = int(data['mailServerSSL']) - + acl.config=json.dumps(data) acl.save() if int(data['adminStatus']) == 1: @@ -844,25 +611,23 @@ def submitACLModifications(request): return HttpResponse(json_data) def changeUserACL(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) - if currentACL['admin'] == 1: - aclNames = ACLManager.unFileteredACLs() - userNames = ACLManager.findAllUsers() - return render(request, 'userManagment/changeUserACL.html', {'aclNames': aclNames, 'usersList': userNames}) - elif currentACL['changeUserACL'] == 1: - aclNames = ACLManager.unFileteredACLs() - userNames = ACLManager.findAllUsers() - - return render(request, 'userManagment/changeUserACL.html', {'aclNames': aclNames, 'usersList': userNames}) - else: - return ACLManager.loadError() - - - except KeyError: - return redirect(loadLoginPage) + if currentACL['admin'] == 1: + aclNames = ACLManager.unFileteredACLs() + userNames = ACLManager.findAllUsers() + proc = httpProc(request, 'userManagment/changeUserACL.html', + {'aclNames': aclNames, 'usersList': userNames}, 'admin') + return proc.render() + elif currentACL['changeUserACL'] == 1: + aclNames = ACLManager.unFileteredACLs() + userNames = ACLManager.findAllUsers() + proc = httpProc(request, 'userManagment/changeUserACL.html', + {'aclNames': aclNames, 'usersList': userNames}) + return proc.render() + else: + return ACLManager.loadError() def changeACLFunc(request): try: @@ -905,26 +670,23 @@ def changeACLFunc(request): return HttpResponse(json_data) def resellerCenter(request): - try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) - if currentACL['admin'] == 1: - userNames = ACLManager.loadDeletionUsers(userID, currentACL) - resellerPrivUsers = ACLManager.userWithResellerPriv(userID) - return render(request, 'userManagment/resellerCenter.html', - {'userToBeModified': userNames, 'resellerPrivUsers': resellerPrivUsers}) - elif currentACL['resellerCenter'] == 1: - userNames = ACLManager.loadDeletionUsers(userID, currentACL) - resellerPrivUsers = ACLManager.userWithResellerPriv(userID) - return render(request, 'userManagment/resellerCenter.html', - {'userToBeModified': userNames, 'resellerPrivUsers': resellerPrivUsers}) - else: - return ACLManager.loadError() - - - except KeyError: - return redirect(loadLoginPage) + if currentACL['admin'] == 1: + userNames = ACLManager.loadDeletionUsers(userID, currentACL) + resellerPrivUsers = ACLManager.userWithResellerPriv(userID) + proc = httpProc(request, 'userManagment/resellerCenter.html', + {'userToBeModified': userNames, 'resellerPrivUsers': resellerPrivUsers}) + return proc.render() + elif currentACL['resellerCenter'] == 1: + userNames = ACLManager.loadDeletionUsers(userID, currentACL) + resellerPrivUsers = ACLManager.userWithResellerPriv(userID) + proc = httpProc(request, 'userManagment/resellerCenter.html', + {'userToBeModified': userNames, 'resellerPrivUsers': resellerPrivUsers}) + return proc.render() + else: + return ACLManager.loadError() def saveResellerChanges(request): try: @@ -983,36 +745,35 @@ def saveResellerChanges(request): return HttpResponse(json_data) def listUsers(request): - try: - userID = request.session['userID'] + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) - currentACL = ACLManager.loadedACL(userID) + if currentACL['admin'] == 1: + aclNames = ACLManager.unFileteredACLs() + elif currentACL['changeUserACL'] == 1: + aclNames = ACLManager.unFileteredACLs() + elif currentACL['createNewUser'] == 1: + aclNames = ['user'] + else: + aclNames = [] - if currentACL['admin'] == 1: - aclNames = ACLManager.unFileteredACLs() - elif currentACL['changeUserACL'] == 1: - aclNames = ACLManager.unFileteredACLs() - elif currentACL['createNewUser'] == 1: - aclNames = ['user'] - else: - aclNames = [] + if currentACL['admin'] == 1: + resellerPrivUsers = ACLManager.userWithResellerPriv(userID) + elif currentACL['resellerCenter'] == 1: + resellerPrivUsers = ACLManager.userWithResellerPriv(userID) + else: + resellerPrivUsers = [] - if currentACL['admin'] == 1: - resellerPrivUsers = ACLManager.userWithResellerPriv(userID) - elif currentACL['resellerCenter'] == 1: - resellerPrivUsers = ACLManager.userWithResellerPriv(userID) - else: - resellerPrivUsers = [] - - if currentACL['admin'] == 1: - return render(request, 'userManagment/listUsers.html', {'aclNames': aclNames, 'resellerPrivUsers': resellerPrivUsers}) - elif currentACL['listUsers'] == 1: - return render(request, 'userManagment/listUsers.html', {'aclNames': aclNames, 'resellerPrivUsers': resellerPrivUsers}) - else: - return ACLManager.loadError() - - except KeyError: - return redirect(loadLoginPage) + if currentACL['admin'] == 1: + proc = httpProc(request, 'userManagment/listUsers.html', + {'aclNames': aclNames, 'resellerPrivUsers': resellerPrivUsers}) + return proc.render() + elif currentACL['listUsers'] == 1: + proc = httpProc(request, 'userManagment/listUsers.html', + {'aclNames': aclNames, 'resellerPrivUsers': resellerPrivUsers}) + return proc.render() + else: + return ACLManager.loadError() def fetchTableUsers(request): try: @@ -1035,11 +796,12 @@ def fetchTableUsers(request): for items in users: - diskUsage = 0 + diskUsageCurrent = 0 for webs in items.websites_set.all(): - #diskUsage = virtualHostUtilities.getDiskUsage("/home/" + webs.domain, webs.package.diskSpace)[0] + diskUsage - diskUsage = 1 + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(webs) + diskUsageCurrent = DiskUsage + diskUsageCurrent + owner = Administrator.objects.get(pk=items.owner) @@ -1047,7 +809,7 @@ def fetchTableUsers(request): 'name': items.userName, 'owner': owner.userName, 'acl': items.acl.name, - 'diskUsage': '%sMB' % str(diskUsage), + 'diskUsage': '%sMB' % str(diskUsageCurrent), 'websites': items.initWebsitesLimit, 'state': items.state } diff --git a/websiteFunctions/StagingSetup.py b/websiteFunctions/StagingSetup.py index df6979ca6..7e68fe7f6 100644 --- a/websiteFunctions/StagingSetup.py +++ b/websiteFunctions/StagingSetup.py @@ -36,21 +36,43 @@ class StagingSetup(multi.Thread): website = Websites.objects.get(domain=masterDomain) - masterPath = '/home/%s/public_html' % (masterDomain) + try: + import json + from cloudAPI.models import WPDeployments + wpd = WPDeployments.objects.get(owner=website) + path = json.loads(wpd.config)['path'] + masterPath = '/home/%s/public_html/%s' % (masterDomain, path) + replaceDomain = '%s/%s' % (masterDomain, path) + except: + masterPath = '/home/%s/public_html' % (masterDomain) + replaceDomain = masterDomain + + configPath = '%s/wp-config.php' % (masterPath) + + ## Check if WP Detected on Main Site + + command = 'ls -la %s' % (configPath) + output = ProcessUtilities.outputExecutioner(command) + + if output.find('No such file or') > -1: + logging.statusWriter(tempStatusPath, 'WordPress is not detected. [404]') + return 0 + + ## command = 'chmod 755 %s' % (masterPath) ProcessUtilities.executioner(command) ## Creating Child Domain - path = "/home/" + masterDomain + "/public_html/" + domain + path = "/home/" + masterDomain + "/" + domain logging.statusWriter(tempStatusPath, 'Creating domain for staging environment..,5') - phpSelection = 'PHP 7.2' + phpSelection = website.phpSelection execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \ - " --phpVersion '" + phpSelection + "' --ssl 0 --dkimCheck 0 --openBasedir 0 --path " + path + ' --websiteOwner ' \ + " --phpVersion '" + phpSelection + "' --ssl 1 --dkimCheck 0 --openBasedir 0 --path " + path + ' --websiteOwner ' \ + admin.userName + ' --tempStatusPath %s' % (tempStatusPath + '1') + " --apache 0" ProcessUtilities.executioner(execPath) @@ -67,127 +89,48 @@ class StagingSetup(multi.Thread): logging.statusWriter(tempStatusPath, 'Domain successfully created..,15') - ## Copying Data + ## Creating WP Site and setting Database - ## Fetch child domain path - - childDomainPaths = [] - - for childs in website.childdomains_set.all(): - childDomainPaths.append(childs.path) - - filesAndFolder = os.listdir(masterPath) - - for items in filesAndFolder: - completePath = '%s/%s' % (masterPath, items) - - if completePath in childDomainPaths: - continue - else: - command = 'cp -r %s %s/' % (completePath, path) - ProcessUtilities.executioner(command, website.externalApp) - - foldersToBeRemoved = ['%s/.git' % (path), '%s/wp-content/backups' % (path), '%s/wp-content/updraft' % (path), '%s/wp-content/cache' % (path), '%s/wp-content/plugins/litespeed-cache' % (path)] - - for rmv in foldersToBeRemoved: - command = 'rm -rf %s' % (rmv) - ProcessUtilities.executioner(command, website.externalApp) - - - logging.statusWriter(tempStatusPath, 'Data copied..,50') - - ## Creating Database + command = 'wp core download --path=%s' % (path) + ProcessUtilities.executioner(command, website.externalApp) logging.statusWriter(tempStatusPath, 'Creating and copying database..,50') dbNameRestore, dbUser, dbPassword = ApplicationInstaller(None, None).dbCreation(tempStatusPath, website) - # Create dump of existing database + command = 'wp core config --dbname=%s --dbuser=%s --dbpass=%s --path=%s' % (dbNameRestore, dbUser, dbPassword, path) + ProcessUtilities.executioner(command, website.externalApp) - configPath = '%s/wp-config.php' % (masterPath) + ## Exporting and importing database - command = 'ls -la %s' % (configPath) - output = ProcessUtilities.outputExecutioner(command) + command = 'wp --allow-root --path=%s db export %s/dbexport-stage.sql' % (masterPath, path) + ProcessUtilities.executioner(command) - if output.find('No such file or') > -1: - logging.statusWriter(tempStatusPath, 'WordPress is not detected. [404]') - return 0 + ## Import - command = 'cat %s' % (configPath) - data = ProcessUtilities.outputExecutioner(command).split('\n') - - for items in data: - if items.find('DB_NAME') > -1 and items[0] != '/': - try: - dbName = items.split("'")[3] - if mysqlUtilities.createDatabaseBackup(dbName, '/home/cyberpanel'): - break - else: - raise BaseException('Failed to create database backup.') - except: - dbName = items.split('"')[1] - if mysqlUtilities.createDatabaseBackup(dbName, '/home/cyberpanel'): - break - else: - raise BaseException('Failed to create database backup.') - - databasePath = '%s/%s.sql' % ('/home/cyberpanel', dbName) - - if not mysqlUtilities.restoreDatabaseBackup(dbNameRestore, '/home/cyberpanel', None, 1, dbName): - try: - os.remove(databasePath) - except: - pass - raise BaseException('Failed to restore database backup.') + command = 'wp --allow-root --path=%s --quiet db import %s/dbexport-stage.sql' % (path, path) + ProcessUtilities.executioner(command) try: - os.remove(databasePath) + command = 'rm -f %s/dbexport-stage.sql' % (path) + ProcessUtilities.executioner(command) except: pass - ## Update final config file + ## Sync WP-Content Folder - pathFinalConfig = '%s/wp-config.php' % (path) - - command = 'cat %s' % (configPath) - data = ProcessUtilities.outputExecutioner(command).split('\n') - - tmp = "/tmp/" + str(randint(1000, 9999)) - writeToFile = open(tmp, 'w') - - for items in data: - if items.find('DB_NAME') > -1: - writeToFile.write("\ndefine( 'DB_NAME', '%s' );\n" % (dbNameRestore)) - elif items.find('DB_USER') > -1: - writeToFile.write("\ndefine( 'DB_USER', '%s' );\n" % (dbUser)) - elif items.find('DB_PASSWORD') > -1: - writeToFile.write("\ndefine( 'DB_PASSWORD', '%s' );\n" % (dbPassword)) - elif items.find('WP_SITEURL') > -1: - continue - elif items.find("table_prefix") > -1: - writeToFile.writelines(items) - content = """ -define('WP_HOME','http://%s'); -define('WP_SITEURL','http://%s'); -""" % (domain, domain) - writeToFile.write(content) - else: - writeToFile.write(items + '\n') - - writeToFile.close() - - command = 'mv %s %s' % (tmp, pathFinalConfig) + command = 'rsync -avz %s/wp-content/ %s/wp-content/' % (masterPath, path) ProcessUtilities.executioner(command) - command = 'chown %s:%s %s' % (website.externalApp, website.externalApp, pathFinalConfig) + ## Search and replace url + + command = 'wp search-replace --allow-root --path=%s "%s" "%s"' % (path, replaceDomain, domain) ProcessUtilities.executioner(command) - logging.statusWriter(tempStatusPath, 'Database synced..,100') + command = 'wp search-replace --allow-root --path=%s "www.%s" "%s"' % (path, replaceDomain, domain) + ProcessUtilities.executioner(command) - try: - os.remove(databasePath) - except: - pass + logging.statusWriter(tempStatusPath, 'Fixing permissions..,90') from filemanager.filemanager import FileManager @@ -197,7 +140,7 @@ define('WP_SITEURL','http://%s'); from plogical.installUtilities import installUtilities installUtilities.reStartLiteSpeed() - logging.statusWriter(tempStatusPath, 'Data copied..,[200]') + logging.statusWriter(tempStatusPath, 'Completed,[200]') return 0 except BaseException as msg: @@ -208,12 +151,24 @@ define('WP_SITEURL','http://%s'); try: tempStatusPath = self.extraArgs['tempStatusPath'] childDomain = self.extraArgs['childDomain'] - eraseCheck = self.extraArgs['eraseCheck'] + #eraseCheck = self.extraArgs['eraseCheck'] dbCheck = self.extraArgs['dbCheck'] - copyChanged = self.extraArgs['copyChanged'] + #copyChanged = self.extraArgs['copyChanged'] + child = ChildDomains.objects.get(domain=childDomain) + try: + import json + from cloudAPI.models import WPDeployments + wpd = WPDeployments.objects.get(owner=child.master) + path = json.loads(wpd.config)['path'] + masterPath = '/home/%s/public_html/%s' % (child.master.domain, path) + replaceDomain = '%s/%s' % (child.master.domain, path) + except: + masterPath = '/home/%s/public_html' % (child.master.domain) + replaceDomain = child.master.domain + command = 'chmod 755 /home/%s/public_html' % (child.master.domain) ProcessUtilities.executioner(command) @@ -223,59 +178,38 @@ define('WP_SITEURL','http://%s'); logging.statusWriter(tempStatusPath, 'WordPress is not detected. [404]') return 0 - if dbCheck: - logging.statusWriter(tempStatusPath, 'Syncing databases..,10') + ## Restore db - ## Create backup of child-domain database + logging.statusWriter(tempStatusPath, 'Syncing databases..,10') - configPath = '%s/wp-config.php' % (child.path) + command = 'wp --allow-root --path=%s db export %s/dbexport-stage.sql' % (child.path, masterPath) + ProcessUtilities.executioner(command) - data = open(configPath, 'r').readlines() + ## Restore to master domain - for items in data: - if items.find('DB_NAME') > -1 and items[0] != '/': - dbName = items.split("'")[3] - if mysqlUtilities.createDatabaseBackup(dbName, '/home/cyberpanel'): - break - else: - raise BaseException('Failed to create database backup.') + command = 'wp --allow-root --path=%s --quiet db import %s/dbexport-stage.sql' % (masterPath, masterPath) + ProcessUtilities.executioner(command) - databasePath = '%s/%s.sql' % ('/home/cyberpanel', dbName) + try: + command = 'rm -f %s/dbexport-stage.sql' % (masterPath) + ProcessUtilities.executioner(command) + except: + pass - ## Restore to master domain + ## Sync WP-Content Folder - masterPath = '/home/%s/public_html' % (child.master.domain) + logging.statusWriter(tempStatusPath, 'Syncing data..,50') - configPath = '%s/wp-config.php' % (masterPath) + command = 'rsync -avz %s/wp-content/ %s/wp-content/' % (child.path, masterPath) + ProcessUtilities.executioner(command) - data = open(configPath, 'r').readlines() + ## Search and replace url - for items in data: - if items.find('DB_NAME') > -1 and items[0] != '/': - dbNameRestore = items.split("'")[3] - if not mysqlUtilities.restoreDatabaseBackup(dbNameRestore, '/home/cyberpanel', None, 1, dbName): - try: - os.remove(databasePath) - except: - pass - raise BaseException('Failed to restore database backup.') + command = 'wp search-replace --allow-root --path=%s "%s" "%s"' % (masterPath, child.domain, replaceDomain) + ProcessUtilities.executioner(command) - try: - os.remove(databasePath) - except: - pass - if eraseCheck: - sourcePath = child.path - destinationPath = '/home/%s/public_html' % (child.master.domain) - - command = 'rsync -avzh --exclude "wp-config.php" %s/ %s' % (sourcePath, destinationPath) - ProcessUtilities.executioner(command, child.master.externalApp) - elif copyChanged: - sourcePath = child.path - destinationPath = '/home/%s/public_html' % (child.master.domain) - - command = 'rsync -avzh --exclude "wp-config.php" %s/ %s' % (sourcePath, destinationPath) - ProcessUtilities.executioner(command, child.master.externalApp) + command = 'wp search-replace --allow-root --path=%s "www.%s" "%s"' % (masterPath, child.domain, replaceDomain) + ProcessUtilities.executioner(command) from filemanager.filemanager import FileManager @@ -285,7 +219,16 @@ define('WP_SITEURL','http://%s'); from plogical.installUtilities import installUtilities installUtilities.reStartLiteSpeed() - logging.statusWriter(tempStatusPath, 'Data copied..,[200]') + logging.statusWriter(tempStatusPath, 'Completed,[200]') + + http = [] + finalHTTP = [] + + for items in http: + if items.find('x-litespeed-cache') > -1 or items.find('x-lsadc-cache') > -1 or items.find('x-qc-cache') > -1: + finalHTTP.append('%s' % (items)) + else: + finalHTTP.append(items) return 0 except BaseException as msg: diff --git a/websiteFunctions/models.py b/websiteFunctions/models.py index 26f74956f..e6a705e98 100755 --- a/websiteFunctions/models.py +++ b/websiteFunctions/models.py @@ -17,6 +17,7 @@ class Websites(models.Model): ssl = models.IntegerField() state = models.IntegerField(default=1) externalApp = models.CharField(max_length=30, default=None) + config = models.TextField(default='') class ChildDomains(models.Model): master = models.ForeignKey(Websites,on_delete=models.CASCADE) diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index d1f948405..ca0fed440 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2830,6 +2830,8 @@ app.controller('manageCronController', function ($scope, $http) { $("#cronEditSuccess").hide(); $("#fetchCronFailure").hide(); + $scope.websiteToBeModified = $("#domain").text(); + $scope.fetchWebsites = function () { $("#manageCronLoading").show(); @@ -2880,6 +2882,7 @@ app.controller('manageCronController', function ($scope, $http) { $("#cronEditSuccess").hide(); } }; + $scope.fetchWebsites(); $scope.fetchCron = function (cronLine) { @@ -3033,7 +3036,6 @@ app.controller('manageCronController', function ($scope, $http) { } }; - $scope.removeCron = function (line) { $("#manageCronLoading").show(); diff --git a/websiteFunctions/templates/websiteFunctions/listCron.html b/websiteFunctions/templates/websiteFunctions/listCron.html old mode 100755 new mode 100644 index 44e9a1fd2..e03076a98 --- a/websiteFunctions/templates/websiteFunctions/listCron.html +++ b/websiteFunctions/templates/websiteFunctions/listCron.html @@ -16,27 +16,19 @@

    - {% trans "Cron Management" %} + {% trans "Cron Management" %} - {{ domain }}

    - -
    - -
    - -
    - - + +
    @@ -74,7 +66,6 @@
    -
    diff --git a/websiteFunctions/templates/websiteFunctions/listWebsites.html b/websiteFunctions/templates/websiteFunctions/listWebsites.html index 29ac71118..8fd9a21dd 100755 --- a/websiteFunctions/templates/websiteFunctions/listWebsites.html +++ b/websiteFunctions/templates/websiteFunctions/listWebsites.html @@ -57,7 +57,7 @@

    -- - /home/{$ web.domain $}/public_html + File Manager
    - - {% trans "Cron Jobs" %} diff --git a/websiteFunctions/views.py b/websiteFunctions/views.py index b9d74dcff..a03884740 100755 --- a/websiteFunctions/views.py +++ b/websiteFunctions/views.py @@ -1,22 +1,23 @@ # -*- coding: utf-8 -*- -from django.shortcuts import render,redirect +from django.shortcuts import redirect from django.http import HttpResponse from loginSystem.models import Administrator from loginSystem.views import loadLoginPage import json + +from plogical.httpProc import httpProc from websiteFunctions.website import WebsiteManager from websiteFunctions.pluginManager import pluginManager from django.views.decorators.csrf import csrf_exempt def loadWebsitesHome(request): - try: - val = request.session['userID'] - admin = Administrator.objects.get(pk=val) - return render(request,'websiteFunctions/index.html',{"type":admin.type}) - except KeyError: - return redirect(loadLoginPage) + val = request.session['userID'] + admin = Administrator.objects.get(pk=val) + proc = httpProc(request, 'websiteFunctions/index.html', + {"type": admin.type}) + return proc.render() def createWebsite(request): try: diff --git a/websiteFunctions/website.py b/websiteFunctions/website.py index 48115127b..527c6e2b7 100755 --- a/websiteFunctions/website.py +++ b/websiteFunctions/website.py @@ -4,6 +4,8 @@ import os.path import sys import django +from plogical.httpProc import httpProc + sys.path.append('/usr/local/CyberCP') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") django.setup() @@ -26,9 +28,6 @@ from plogical.childDomain import ChildDomainManager from math import ceil from plogical.alias import AliasManager from plogical.applicationInstaller import ApplicationInstaller -from databases.models import Databases -import hashlib -from plogical.mysqlUtilities import mysqlUtilities from plogical import hashPassword from emailMarketing.emACL import emACL from plogical.processUtilities import ProcessUtilities @@ -36,7 +35,6 @@ from managePHP.phpManager import PHPManager from ApachController.ApacheVhosts import ApacheVhost from plogical.vhostConfs import vhostConfs from plogical.cronUtil import CronUtil -from plogical import randomPassword from .StagingSetup import StagingSetup import validators @@ -51,115 +49,93 @@ class WebsiteManager: self.childDomain = childDomain def createWebsite(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: - return ACLManager.loadError() + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() - - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} - return render(request, 'websiteFunctions/createWebsite.html', Data) - - except BaseException as msg: - return HttpResponse(str(msg)) + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} + proc = httpProc(request, 'websiteFunctions/createWebsite.html', + Data, 'createWebsite') + return proc.render() def modifyWebsite(self, request=None, userID=None, data=None): - try: + currentACL = ACLManager.loadedACL(userID) - currentACL = ACLManager.loadedACL(userID) - - if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: - return ACLManager.loadError() - - websitesName = ACLManager.findAllSites(currentACL, userID) - phps = PHPManager.findPHPVersions() - - return render(request, 'websiteFunctions/modifyWebsite.html', {'websiteList': websitesName, 'phps': phps}) - except BaseException as msg: - return HttpResponse(str(msg)) + websitesName = ACLManager.findAllSites(currentACL, userID) + phps = PHPManager.findPHPVersions() + proc = httpProc(request, 'websiteFunctions/modifyWebsite.html', + {'websiteList': websitesName, 'phps': phps}, 'modifyWebsite') + return proc.render() def deleteWebsite(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'deleteWebsite') == 0: - return ACLManager.loadError() - - websitesName = ACLManager.findAllSites(currentACL, userID) - - return render(request, 'websiteFunctions/deleteWebsite.html', {'websiteList': websitesName}) - except BaseException as msg: - return HttpResponse(str(msg)) + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID) + proc = httpProc(request, 'websiteFunctions/deleteWebsite.html', + {'websiteList': websitesName}, 'deleteWebsite') + return proc.render() def siteState(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) + currentACL = ACLManager.loadedACL(userID) - if ACLManager.currentContextPermission(currentACL, 'suspendWebsite') == 0: - return ACLManager.loadError() + websitesName = ACLManager.findAllSites(currentACL, userID) - websitesName = ACLManager.findAllSites(currentACL, userID) - - return render(request, 'websiteFunctions/suspendWebsite.html', {'websiteList': websitesName}) - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'websiteFunctions/suspendWebsite.html', + {'websiteList': websitesName}, 'suspendWebsite') + return proc.render() def listWebsites(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - pagination = self.websitePagination(currentACL, userID) - - return render(request, 'websiteFunctions/listWebsites.html', {"pagination": pagination}) - except BaseException as msg: - return HttpResponse(str(msg)) + currentACL = ACLManager.loadedACL(userID) + pagination = self.websitePagination(currentACL, userID) + proc = httpProc(request, 'websiteFunctions/listWebsites.html', + {"pagination": pagination}) + return proc.render() def listChildDomains(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - pagination = self.websitePagination(currentACL, userID) - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - phps = PHPManager.findPHPVersions() + currentACL = ACLManager.loadedACL(userID) + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + phps = PHPManager.findPHPVersions() - Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} - - return render(request, 'websiteFunctions/listChildDomains.html', Data) - except BaseException as msg: - return HttpResponse(str(msg)) + Data = {'packageList': packagesName, "owernList": adminNames, 'phps': phps} + proc = httpProc(request, 'websiteFunctions/listChildDomains.html', + Data) + return proc.render() def listCron(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - websitesName = ACLManager.findAllSites(currentACL, userID) - return render(request, 'websiteFunctions/listCron.html', {'websiteList': websitesName}) - except BaseException as msg: - return HttpResponse(str(msg)) + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(request.GET.get('domain'), admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + proc = httpProc(request, 'websiteFunctions/listCron.html', + {'domain': request.GET.get('domain')}) + return proc.render() def domainAlias(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() - aliasManager = AliasManager(self.domain) - noAlias, finalAlisList = aliasManager.fetchAlisForDomains() + aliasManager = AliasManager(self.domain) + noAlias, finalAlisList = aliasManager.fetchAlisForDomains() - path = "/home/" + self.domain + "/public_html" + path = "/home/" + self.domain + "/public_html" - return render(request, 'websiteFunctions/domainAlias.html', { - 'masterDomain': self.domain, - 'aliases': finalAlisList, - 'path': path, - 'noAlias': noAlias - }) - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'websiteFunctions/domainAlias.html', { + 'masterDomain': self.domain, + 'aliases': finalAlisList, + 'path': path, + 'noAlias': noAlias + }) + return proc.render() def submitWebsiteCreation(self, userID=None, data=None): try: @@ -452,9 +428,9 @@ class WebsiteManager: else: state = "Active" - #diskUsed = "%sMB" % str(virtualHostUtilities.getDiskUsage("/home/" + items.domain, items.package.diskSpace)[0]) + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(items) + diskUsed = "%sMB" % str(DiskUsage) - diskUsed = '1MB' ## to be fixed later dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state, 'diskUsed': diskUsed} @@ -830,38 +806,20 @@ class WebsiteManager: Data['domain'] = self.domain - diskUsageDetails = virtualHostUtilities.getDiskUsage("/home/" + self.domain, website.package.diskSpace) - - ## bw usage calculation - - try: - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " findDomainBW --virtualHostName " + self.domain + " --bandwidth " + str( - website.package.bandwidth) - - output = ProcessUtilities.outputExecutioner(execPath) - bwData = output.split(",") - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - bwData = [0, 0] + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) ## bw usage calculations Data['bwInMBTotal'] = website.package.bandwidth - Data['bwInMB'] = bwData[0] - Data['bwUsage'] = bwData[1] + Data['bwInMB'] = bwInMB + Data['bwUsage'] = bwUsage - if diskUsageDetails != None: - if diskUsageDetails[1] > 100: - diskUsageDetails[1] = 100 + if DiskUsagePercentage > 100: + DiskUsagePercentage = 100 - Data['diskUsage'] = diskUsageDetails[1] - Data['diskInMB'] = diskUsageDetails[0] - Data['diskInMBTotal'] = website.package.diskSpace - else: - Data['diskUsage'] = 0 - Data['diskInMB'] = 0 - Data['diskInMBTotal'] = website.package.diskSpace + Data['diskUsage'] = DiskUsagePercentage + Data['diskInMB'] = DiskUsage + Data['diskInMBTotal'] = website.package.diskSpace Data['phps'] = PHPManager.findPHPVersions() @@ -902,11 +860,12 @@ class WebsiteManager: else: Data['ftp'] = 0 - return render(request, 'websiteFunctions/website.html', Data) - + proc = httpProc(request, 'websiteFunctions/website.html', Data) + return proc.render() else: - return render(request, 'websiteFunctions/website.html', + proc = httpProc(request, 'websiteFunctions/website.html', {"error": 1, "domain": "This domain does not exists."}) + return proc.render() def launchChild(self, request=None, userID=None, data=None): @@ -932,38 +891,20 @@ class WebsiteManager: Data['domain'] = self.domain Data['childDomain'] = self.childDomain - diskUsageDetails = virtualHostUtilities.getDiskUsage("/home/" + self.domain, website.package.diskSpace) - - ## bw usage calculation - - try: - execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " findDomainBW --virtualHostName " + self.domain + " --bandwidth " + str( - website.package.bandwidth) - - output = ProcessUtilities.outputExecutioner(execPath) - bwData = output.split(",") - except BaseException as msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - bwData = [0, 0] + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(website) ## bw usage calculations Data['bwInMBTotal'] = website.package.bandwidth - Data['bwInMB'] = bwData[0] - Data['bwUsage'] = bwData[1] + Data['bwInMB'] = bwInMB + Data['bwUsage'] = bwUsage - if diskUsageDetails != None: - if diskUsageDetails[1] > 100: - diskUsageDetails[1] = 100 + if DiskUsagePercentage > 100: + DiskUsagePercentage = 100 - Data['diskUsage'] = diskUsageDetails[1] - Data['diskInMB'] = diskUsageDetails[0] - Data['diskInMBTotal'] = website.package.diskSpace - else: - Data['diskUsage'] = 0 - Data['diskInMB'] = 0 - Data['diskInMBTotal'] = website.package.diskSpace + Data['diskUsage'] = DiskUsagePercentage + Data['diskInMB'] = DiskUsage + Data['diskInMBTotal'] = website.package.diskSpace Data['phps'] = PHPManager.findPHPVersions() @@ -1005,10 +946,12 @@ class WebsiteManager: logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return render(request, 'websiteFunctions/launchChild.html', Data) + proc = httpProc(request, 'websiteFunctions/launchChild.html', Data) + return proc.render() else: - return render(request, 'websiteFunctions/launchChild.html', + proc = httpProc(request, 'websiteFunctions/launchChild.html', {"error": 1, "domain": "This child domain does not exists"}) + return proc.render() def getDataFromLogFile(self, userID=None, data=None): @@ -1794,19 +1737,16 @@ class WebsiteManager: return HttpResponse(json_data) def wordpressInstall(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() - return render(request, 'websiteFunctions/installWordPress.html', {'domainName': self.domain}) - - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'websiteFunctions/installWordPress.html', {'domainName': self.domain}) + return proc.render() def installWordpress(self, userID=None, data=None): try: @@ -1899,18 +1839,16 @@ class WebsiteManager: return HttpResponse(json_data) def joomlaInstall(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() - return render(request, 'websiteFunctions/installJoomla.html', {'domainName': self.domain}) - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'websiteFunctions/installJoomla.html', {'domainName': self.domain}) + return proc.render() def installJoomla(self, userID=None, data=None): try: @@ -1957,61 +1895,59 @@ class WebsiteManager: return HttpResponse(json_data) def setupGit(self, request=None, userID=None, data=None): - try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + website = Websites.objects.get(domain=self.domain) - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - website = Websites.objects.get(domain=self.domain) + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadErrorJson() + path = '/home/cyberpanel/' + self.domain + '.git' - path = '/home/cyberpanel/' + self.domain + '.git' + if os.path.exists(path): + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] - if os.path.exists(path): - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] + port = ProcessUtilities.fetchCurrentPort() - port = ProcessUtilities.fetchCurrentPort() + webhookURL = 'https://' + ipAddress + ':%s/websites/' % (port) + self.domain + '/gitNotify' - webhookURL = 'https://' + ipAddress + ':%s/websites/' % (port) + self.domain + '/gitNotify' + proc = httpProc(request, 'websiteFunctions/setupGit.html', + {'domainName': self.domain, 'installed': 1, 'webhookURL': webhookURL}) + return proc.render() + else: - return render(request, 'websiteFunctions/setupGit.html', - {'domainName': self.domain, 'installed': 1, 'webhookURL': webhookURL}) - else: + command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.domain, website.externalApp) + ProcessUtilities.executioner(command, website.externalApp) - command = "ssh-keygen -f /home/%s/.ssh/%s -t rsa -N ''" % (self.domain, website.externalApp) - ProcessUtilities.executioner(command, website.externalApp) + ### - ### - - configContent = """Host github.com + configContent = """Host github.com IdentityFile /home/%s/.ssh/%s StrictHostKeyChecking no """ % (self.domain, website.externalApp) - path = "/home/cyberpanel/config" - writeToFile = open(path, 'w') - writeToFile.writelines(configContent) - writeToFile.close() + path = "/home/cyberpanel/config" + writeToFile = open(path, 'w') + writeToFile.writelines(configContent) + writeToFile.close() - command = 'mv %s /home/%s/.ssh/config' % (path, self.domain) - ProcessUtilities.executioner(command) + command = 'mv %s /home/%s/.ssh/config' % (path, self.domain) + ProcessUtilities.executioner(command) - command = 'chown %s:%s /home/%s/.ssh/config' % (website.externalApp, website.externalApp, self.domain) - ProcessUtilities.executioner(command) + command = 'chown %s:%s /home/%s/.ssh/config' % (website.externalApp, website.externalApp, self.domain) + ProcessUtilities.executioner(command) - command = 'cat /home/%s/.ssh/%s.pub' % (self.domain, website.externalApp) - deploymentKey = ProcessUtilities.outputExecutioner(command, website.externalApp) + command = 'cat /home/%s/.ssh/%s.pub' % (self.domain, website.externalApp) + deploymentKey = ProcessUtilities.outputExecutioner(command, website.externalApp) - return render(request, 'websiteFunctions/setupGit.html', - {'domainName': self.domain, 'deploymentKey': deploymentKey, 'installed': 0}) - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'websiteFunctions/setupGit.html', + {'domainName': self.domain, 'deploymentKey': deploymentKey, 'installed': 0}) + return proc.render() def setupGitRepo(self, userID=None, data=None): try: @@ -2138,32 +2074,28 @@ StrictHostKeyChecking no return HttpResponse(json_data) def installPrestaShop(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() - return render(request, 'websiteFunctions/installPrestaShop.html', {'domainName': self.domain}) - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'websiteFunctions/installPrestaShop.html', {'domainName': self.domain}) + return proc.render() def installMagento(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() - return render(request, 'websiteFunctions/installMagento.html', {'domainName': self.domain}) - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'websiteFunctions/installMagento.html', {'domainName': self.domain}) + return proc.render() def magentoInstall(self, userID=None, data=None): try: @@ -2213,18 +2145,16 @@ StrictHostKeyChecking no return HttpResponse(json_data) def installMautic(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() - return render(request, 'websiteFunctions/installMautic.html', {'domainName': self.domain}) - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'websiteFunctions/installMautic.html', {'domainName': self.domain}) + return proc.render() def mauticInstall(self, userID=None, data=None): try: @@ -2393,8 +2323,9 @@ StrictHostKeyChecking no else: state = "Active" - diskUsed = "%sMB" % str( - virtualHostUtilities.getDiskUsage("/home/" + items.domain, items.package.diskSpace)[0]) + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(items) + + diskUsed = "%sMB" % str(DiskUsage) dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state, 'diskUsed': diskUsed} @@ -2431,7 +2362,9 @@ StrictHostKeyChecking no else: state = "Active" - diskUsed = "%sMB" % str(virtualHostUtilities.getDiskUsage("/home/" + items.domain, items.package.diskSpace)[0]) + DiskUsage, DiskUsagePercentage, bwInMB, bwUsage = virtualHostUtilities.FindStats(items) + + diskUsed = "%sMB" % str(DiskUsage) dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state, 'diskUsed': diskUsed} @@ -2630,22 +2563,20 @@ StrictHostKeyChecking no return HttpResponse(json_data) def sshAccess(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp - return render(request, 'websiteFunctions/sshAccess.html', - {'domainName': self.domain, 'externalApp': externalApp}) - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'websiteFunctions/sshAccess.html', + {'domainName': self.domain, 'externalApp': externalApp}) + return proc.render() def saveSSHAccessChanges(self, userID=None, data=None): try: @@ -2687,22 +2618,20 @@ StrictHostKeyChecking no def setupStaging(self, request=None, userID=None, data=None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp - return render(request, 'websiteFunctions/setupStaging.html', - {'domainName': self.domain, 'externalApp': externalApp}) - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'websiteFunctions/setupStaging.html', + {'domainName': self.domain, 'externalApp': externalApp}) + return proc.render() def startCloning(self, userID=None, data=None): try: @@ -2712,7 +2641,6 @@ StrictHostKeyChecking no self.domain = data['masterDomain'] - if not validators.domain(self.domain): data_ret = {'status': 0, 'createWebSiteStatus': 0, 'error_message': "Invalid domain."} json_data = json.dumps(data_ret) @@ -2735,7 +2663,6 @@ StrictHostKeyChecking no extraArgs['masterDomain'] = data['masterDomain'] extraArgs['admin'] = admin - tempStatusPath = "/tmp/" + str(randint(1000, 9999)) writeToFile = open(tempStatusPath, 'a') message = 'Cloning process has started..,5' @@ -2757,22 +2684,20 @@ StrictHostKeyChecking no return HttpResponse(json_data) def syncToMaster(self, request=None, userID=None, data=None, childDomain = None): - try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() - website = Websites.objects.get(domain=self.domain) - externalApp = website.externalApp + website = Websites.objects.get(domain=self.domain) + externalApp = website.externalApp - return render(request, 'websiteFunctions/syncMaster.html', - {'domainName': self.domain, 'externalApp': externalApp, 'childDomain': childDomain}) - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'websiteFunctions/syncMaster.html', + {'domainName': self.domain, 'externalApp': externalApp, 'childDomain': childDomain}) + return proc.render() def startSync(self, userID=None, data=None): try: @@ -2851,43 +2776,39 @@ StrictHostKeyChecking no return HttpResponse(json_data) def manageGIT(self, request=None, userID=None, data=None): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + try: - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) + website = Websites.objects.get(domain=self.domain) + folders = ['/home/%s/public_html' % (self.domain), '/home/%s' % (self.domain), + '/home/vmail/%s' % (self.domain)] - if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() + databases = website.databases_set.all() - try: - website = Websites.objects.get(domain=self.domain) - folders = ['/home/%s/public_html' % (self.domain), '/home/%s' % (self.domain), '/home/vmail/%s' % (self.domain)] + for database in databases: + basePath = '/var/lib/mysql/' + folders.append('%s%s' % (basePath, database.dbName)) + except: - databases = website.databases_set.all() + self.childWebsite = ChildDomains.objects.get(domain=self.domain) - for database in databases: - basePath = '/var/lib/mysql/' - folders.append('%s%s' % (basePath, database.dbName)) + folders = [self.childWebsite.path] + databases = self.childWebsite.master.databases_set.all() - except: + for database in databases: + basePath = '/var/lib/mysql/' + folders.append('%s%s' % (basePath, database.dbName)) - self.childWebsite = ChildDomains.objects.get(domain=self.domain) - - folders = [self.childWebsite.path] - - databases = self.childWebsite.master.databases_set.all() - - for database in databases: - basePath = '/var/lib/mysql/' - folders.append('%s%s' % (basePath, database.dbName)) - - return render(request, 'websiteFunctions/manageGIT.html', - {'domainName': self.domain, 'folders': folders}) - - except BaseException as msg: - return HttpResponse(str(msg)) + proc = httpProc(request, 'websiteFunctions/manageGIT.html', + {'domainName': self.domain, 'folders': folders}) + return proc.render() def folderCheck(self):