diff --git a/CLManager/CLManagerMain.py b/CLManager/CLManagerMain.py new file mode 100644 index 000000000..6a58cbb64 --- /dev/null +++ b/CLManager/CLManagerMain.py @@ -0,0 +1,191 @@ +import threading as multi +from plogical.acl import ACLManager +import plogical.CyberCPLogFileWriter as logging +from plogical.processUtilities import ProcessUtilities +from django.shortcuts import render +import os +from serverStatus.serverStatusUtil import ServerStatusUtil +import json +from django.shortcuts import HttpResponse +from math import ceil +from websiteFunctions.models import Websites +from .models import CLPackages + + +class CLManagerMain(multi.Thread): + + def __init__(self, request=None, templateName=None, function=None, data=None): + multi.Thread.__init__(self) + self.request = request + self.templateName = templateName + self.function = function + self.data = data + + def run(self): + try: + if self.function == 'submitCageFSInstall': + self.submitCageFSInstall() + elif self.function == 'enableOrDisable': + self.enableOrDisable() + + except BaseException, 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() + + data = {} + data['CL'] = 0 + data['CAGEFS'] = 0 + CLPath = '/etc/sysconfig/cloudlinux' + CageFSPath = '/usr/sbin/cagefsctl' + + if os.path.exists(CLPath): + data['CL'] = 1 + + if os.path.exists(CageFSPath): + data['CAGEFS'] = 1 + + if data['CL'] == 0: + return render(self.request, 'CLManager/notAvailable.html', data) + elif data['CAGEFS'] == 0: + return render(self.request, 'CLManager/notAvailable.html', data) + else: + return render(self.request, self.templateName, self.data) + + def submitCageFSInstall(self): + try: + userID = self.request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, + 'Not authorized to install container packages. [404].', + 1) + return 0 + + execPath = "sudo python /usr/local/CyberCP/CLManager/CageFS.py" + execPath = execPath + " --function submitCageFSInstall" + ProcessUtilities.outputExecutioner(execPath) + + except BaseException, msg: + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, str(msg) + ' [404].', 1) + + def findWebsitesJson(self, currentACL, userID, pageNumber): + finalPageNumber = ((pageNumber * 10)) - 10 + endPageNumber = finalPageNumber + 10 + websites = ACLManager.findWebsiteObjects(currentACL, userID)[finalPageNumber:endPageNumber] + + json_data = "[" + checker = 0 + + command = '/usr/sbin/cagefsctl --list-enabled' + Enabled = ProcessUtilities.outputExecutioner(command) + + for items in websites: + if Enabled.find(items.externalApp) > -1: + status = 1 + else: + status = 0 + dic = {'domain': items.domain, 'externalApp': items.externalApp, '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 + ']' + + 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 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) + + cageFSPath = '/home/cyberpanel/cagefs' + + if os.path.exists(cageFSPath): + default = 'On' + else: + default = 'Off' + + final_dic = {'status': 1, 'listWebSiteStatus': 1, 'error_message': "None", "data": json_data, + 'pagination': pagination, 'default': default} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException, msg: + dic = {'status': 1, 'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def enableOrDisable(self): + try: + websites = Websites.objects.all() + if self.data['mode'] == 1: + for items in websites: + command = '/usr/sbin/cagefsctl --enable %s' % (items.externalApp) + ProcessUtilities.executioner(command) + else: + for items in websites: + command = '/usr/sbin/cagefsctl --disable %s' % (items.externalApp) + ProcessUtilities.executioner(command) + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + + def fetchPackages(self, currentACL): + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson() + + json_data = "[" + checker = 0 + + for items in CLPackages.objects.all(): + dic = {'name': items.name, 'SPEED': items.speed, 'VMEM': items.vmem, 'PMEM': items.pmem, 'IO': items.io, 'IOPS': items.iops, 'EP': items.ep, + 'NPROC': items.nproc, 'inodessoft': items.inodessoft, 'inodeshard': items.inodeshard} + + 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_dic = {'status': 1, 'error_message': "None", "data": json_data} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + diff --git a/CLManager/CLPackages.py b/CLManager/CLPackages.py new file mode 100755 index 000000000..951acbee7 --- /dev/null +++ b/CLManager/CLPackages.py @@ -0,0 +1,82 @@ +#!/usr/local/CyberCP/bin/python2 +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 argparse +from websiteFunctions.models import Websites +from CLManager.models import CLPackages +import pwd + +class CLinuxPackages: + + @staticmethod + def listAll(): + for items in Websites.objects.all(): + itemPackage = items.package + try: + clPackage = CLPackages.objects.get(owner=itemPackage) + statement = '%s %s' % (pwd.getpwnam(items.externalApp).pw_uid, clPackage.name) + print statement + except: + pass + + + @staticmethod + def listPackages(): + for items in CLPackages.objects.all(): + print items.name + + @staticmethod + def userIDPackage(user): + website = Websites.objects.get(externalApp=user) + itemPackage = website.package + try: + clPackage = CLPackages.objects.get(owner=itemPackage) + print clPackage + except: + pass + + + @staticmethod + def packageForUser(package): + for items in Websites.objects.all(): + itemPackage = items.package + try: + clPackage = CLPackages.objects.get(owner=itemPackage) + if clPackage.name == package: + print pwd.getpwnam(items.externalApp).pw_uid + except: + pass + +def main(): + + parser = argparse.ArgumentParser(description='CyberPanel Container Manager') + parser.add_argument('--userid', help='User ID') + parser.add_argument('--package', help='Package') + parser.add_argument('--function', help='Function') + parser.add_argument('--list-all', help='List all users/packages.', action='store_true') + parser.add_argument('--list-packages', help='List all packages.', action='store_true') + + + args = vars(parser.parse_args()) + + if args['userid']: + CLinuxPackages.userIDPackage(args['userid']) + elif args['package']: + CLinuxPackages.packageForUser(args['package']) + elif args['list_all']: + CLinuxPackages.listAll() + elif args['list_packages']: + CLinuxPackages.listPackages() + + + + + +if __name__ == "__main__": + main() + diff --git a/CLManager/CageFS.py b/CLManager/CageFS.py new file mode 100644 index 000000000..1fb87ff24 --- /dev/null +++ b/CLManager/CageFS.py @@ -0,0 +1,60 @@ +#!/usr/local/CyberCP/bin/python2 +import sys +sys.path.append('/usr/local/CyberCP') +import plogical.CyberCPLogFileWriter as logging +import argparse +from plogical.mailUtilities import mailUtilities +from serverStatus.serverStatusUtil import ServerStatusUtil + + +class CageFS: + packages = ['talksho'] + users = ['5001'] + + @staticmethod + def submitCageFSInstall(): + try: + + mailUtilities.checkHome() + + statusFile = open(ServerStatusUtil.lswsInstallStatusPath, 'w') + + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, + "Starting Packages Installation..\n", 1) + + command = 'sudo yum install cagefs -y' + ServerStatusUtil.executioner(command, statusFile) + + command = 'sudo /usr/sbin/cagefsctl --init' + ServerStatusUtil.executioner(command, statusFile) + + command = 'sudo /usr/sbin/cagefsctl --update-etc' + ServerStatusUtil.executioner(command, statusFile) + + command = 'sudo /usr/sbin/cagefsctl --force-update' + ServerStatusUtil.executioner(command, statusFile) + + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, + "Packages successfully installed.[200]\n", 1) + + except BaseException, msg: + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, str(msg) + ' [404].', 1) + +def main(): + + parser = argparse.ArgumentParser(description='CyberPanel CageFS Manager') + parser.add_argument('--function', help='Function') + + + args = vars(parser.parse_args()) + + if args["function"] == "submitCageFSInstall": + CageFS.submitCageFSInstall() + + + + + +if __name__ == "__main__": + main() + diff --git a/CLManager/__init__.py b/CLManager/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/CLManager/admin.py b/CLManager/admin.py new file mode 100644 index 000000000..13be29d96 --- /dev/null +++ b/CLManager/admin.py @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.contrib import admin + +# Register your models here. diff --git a/CLManager/apps.py b/CLManager/apps.py new file mode 100644 index 000000000..1f97e1e94 --- /dev/null +++ b/CLManager/apps.py @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.apps import AppConfig + + +class ClmanagerConfig(AppConfig): + name = 'CLManager' diff --git a/CLManager/migrations/__init__.py b/CLManager/migrations/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/CLManager/models.py b/CLManager/models.py new file mode 100644 index 000000000..cdbab13b0 --- /dev/null +++ b/CLManager/models.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models +from packages.models import Package + +# Create your models here. + +class CLPackages(models.Model): + owner = models.ForeignKey(Package) + name = models.CharField(max_length=50,unique=True) + speed = models.CharField(max_length=50) + vmem = models.CharField(max_length=50) + pmem = models.CharField(max_length=50) + io = models.CharField(max_length=50) + iops = models.CharField(max_length=50) + ep = models.CharField(max_length=50) + nproc = models.CharField(max_length=50) + inodessoft = models.CharField(max_length=50) + inodeshard = models.CharField(max_length=50) \ No newline at end of file diff --git a/CLManager/static/CLManager/CLManager.js b/CLManager/static/CLManager/CLManager.js new file mode 100644 index 000000000..547a407d5 --- /dev/null +++ b/CLManager/static/CLManager/CLManager.js @@ -0,0 +1,934 @@ +app.controller('installCageFS', function ($scope, $http, $timeout, $window) { + + $scope.installDockerStatus = true; + $scope.installBoxGen = true; + $scope.dockerInstallBTN = false; + + $scope.submitCageFSInstall = function () { + + $scope.installDockerStatus = false; + $scope.installBoxGen = true; + $scope.dockerInstallBTN = true; + + url = "/CloudLinux/submitCageFSInstall"; + + var data = {}; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + $scope.installBoxGen = false; + getRequestStatus(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + + function getRequestStatus() { + $scope.cyberPanelLoading = false; + + url = "/serverstatus/switchTOLSWSStatus"; + + var data = {}; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + if (response.data.abort === 0) { + $scope.requestData = response.data.requestStatus; + $timeout(getRequestStatus, 1000); + } else { + // Notifications + $scope.cyberPanelLoading = true; + $timeout.cancel(); + $scope.requestData = response.data.requestStatus; + if (response.data.installed === 1) { + $timeout(function () { + $window.location.reload(); + }, 3000); + } + + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + + + } + + } +}); + +app.controller('listWebsitesCage', function ($scope, $http) { + + var globalPageNumber; + $scope.getFurtherWebsitesFromDB = function (pageNumber) { + $scope.cyberPanelLoading = false; + globalPageNumber = pageNumber; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = {page: pageNumber}; + + + dataurl = "/CloudLinux/submitWebsiteListing"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + $scope.cyberPanelLoading = true; + if (response.data.listWebSiteStatus === 1) { + var finalData = JSON.parse(response.data.data); + $scope.WebSitesList = finalData; + $scope.pagination = response.data.pagination; + $scope.default = response.data.default; + $("#listFail").hide(); + } else { + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message; + console.log(response.data); + + } + } + + function cantLoadInitialData(response) { + $scope.cyberPanelLoading = true; + console.log("not good"); + } + + + }; + $scope.getFurtherWebsitesFromDB(1); + + $scope.cyberPanelLoading = true; + + $scope.searchWebsites = function () { + + $scope.cyberPanelLoading = false; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + patternAdded: $scope.patternAdded + }; + + dataurl = "/websites/searchWebsites"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + $scope.cyberPanelLoading = true; + if (response.data.listWebSiteStatus === 1) { + + var finalData = JSON.parse(response.data.data); + $scope.WebSitesList = finalData; + $("#listFail").hide(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + } + + function cantLoadInitialData(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Connect disrupted, refresh the page.', + type: 'error' + }); + } + + + }; + + $scope.enableOrDisable = function (domain, all, mode, toggle = 0) { + $scope.cyberPanelLoading = false; + + url = "/CloudLinux/enableOrDisable"; + + var data = { + domain: domain, + all: all, + mode: mode, + toggle: toggle + }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: response.data.success, + type: 'success' + }); + + if (all === 0) { + $scope.getFurtherWebsitesFromDB(globalPageNumber); + } + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + + $scope.refreshStatus = function () { + $scope.getFurtherWebsitesFromDB(globalPageNumber); + } + + +}); + +app.controller('createCLPackage', function ($scope, $http) { + + $scope.cyberPanelLoading = true; + $scope.modifyPackageForm = true; + $scope.toggleView = function () { + $scope.modifyPackageForm = false; + }; + + $scope.createPackage = function () { + $scope.cyberPanelLoading = false; + + url = "/CloudLinux/submitCreatePackage"; + + var data = { + selectedPackage: $scope.selectedPackage, + name: $scope.name, + SPEED: $scope.SPEED, + VMEM: $scope.VMEM, + PMEM: $scope.PMEM, + IO: $scope.IO, + IOPS: $scope.IOPS, + EP: $scope.EP, + NPROC: $scope.NPROC, + INODESsoft: $scope.INODESsoft, + INODEShard: $scope.INODEShard, + }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully created.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + +}); + +app.controller('listCloudLinuxPackages', function ($scope, $http) { + + $scope.cyberPanelLoading = true; + + $scope.fetchPackageas = function () { + $scope.cyberPanelLoading = false; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = {}; + + + dataurl = "/CloudLinux/fetchPackages"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + $scope.packages = JSON.parse(response.data.data); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialData(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + + }; + $scope.fetchPackageas(); + + $scope.deleteCLPackage = function (name) { + $scope.cyberPanelLoading = false; + + url = "/CloudLinux/deleteCLPackage"; + + var data = { + name: name + }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully deleted.', + type: 'success' + }); + $scope.fetchPackageas(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + $scope.populatePackage = function (name, speed, vmem, pmem, io, iops, ep, nproc, inodessoft, inodeshard) { + $scope.name = name; + $scope.SPEED = speed; + $scope.VMEM = vmem; + $scope.PMEM = pmem; + $scope.IO = io; + $scope.IOPS = iops; + $scope.EP = ep; + $scope.NPROC = nproc; + $scope.inodessoft = inodessoft; + $scope.inodeshard = inodeshard; + + }; + + $scope.saveSettings = function () { + $scope.cyberPanelLoading = false; + + url = "/CloudLinux/saveSettings"; + + var data = { + name: $scope.name, + SPEED: $scope.SPEED, + VMEM: $scope.VMEM, + PMEM: $scope.PMEM, + IO: $scope.IO, + IOPS: $scope.IOPS, + EP: $scope.EP, + NPROC: $scope.NPROC, + INODESsoft: $scope.inodessoft, + INODEShard: $scope.inodeshard, + }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Changes successfully applied.', + type: 'success' + }); + $scope.fetchPackageas(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + +}); + + +app.controller('websiteContainerLimitCL', function ($scope, $http, $timeout, $window) { + + + // Get CPU Usage of User + + var cpu = []; + var dataset; + var totalPoints = 100; + var updateInterval = 1000; + var now = new Date().getTime(); + + var options = { + series: { + lines: { + lineWidth: 1.2 + }, + bars: { + align: "center", + fillColor: {colors: [{opacity: 1}, {opacity: 1}]}, + barWidth: 500, + lineWidth: 1 + } + }, + xaxis: { + mode: "time", + tickSize: [5, "second"], + tickFormatter: function (v, axis) { + var date = new Date(v); + + if (date.getSeconds() % 20 == 0) { + var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); + var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); + var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); + + return hours + ":" + minutes + ":" + seconds; + } else { + return ""; + } + }, + axisLabel: "Time", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 10 + }, + yaxes: [ + { + min: 0, + max: 100, + tickSize: 5, + tickFormatter: function (v, axis) { + if (v % 10 == 0) { + return v + "%"; + } else { + return ""; + } + }, + axisLabel: "CPU loading", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + }, { + max: 5120, + position: "right", + axisLabel: "Disk", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + } + ], + legend: { + noColumns: 0, + position: "nw" + }, + grid: { + backgroundColor: {colors: ["#ffffff", "#EDF5FF"]} + } + }; + + function initData() { + for (var i = 0; i < totalPoints; i++) { + var temp = [now += updateInterval, 0]; + + cpu.push(temp); + } + } + + function GetData() { + + var data = { + domain: $("#domain").text() + }; + $.ajaxSetup({cache: false}); + + $.ajax({ + url: "/CloudLinux/getUsageData", + dataType: 'json', + success: update, + type: "POST", + headers: {'X-CSRFToken': getCookie('csrftoken')}, + contentType: "application/json", + data: JSON.stringify(data), // Our valid JSON string + error: function () { + setTimeout(GetData, updateInterval); + } + }); + } + + var temp; + + function update(_data) { + cpu.shift(); + + now += updateInterval; + + temp = [now, _data.cpu]; + cpu.push(temp); + + + dataset = [ + {label: "CPU:" + _data.cpu + "%", data: cpu, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"} + ]; + + $.plot($("#flot-placeholder1"), dataset, options); + setTimeout(GetData, updateInterval); + } + + // Memory Usage of User + + var memory = []; + var datasetMemory; + var totalPointsMemory = 100; + var updateIntervalMemory = 1000; + var nowMemory = new Date().getTime(); + + var optionsMemory = { + series: { + lines: { + lineWidth: 1.2 + }, + bars: { + align: "center", + fillColor: {colors: [{opacity: 1}, {opacity: 1}]}, + barWidth: 500, + lineWidth: 1 + } + }, + xaxis: { + mode: "time", + tickSize: [5, "second"], + tickFormatter: function (v, axis) { + var date = new Date(v); + + if (date.getSeconds() % 20 == 0) { + var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); + var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); + var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); + + return hours + ":" + minutes + ":" + seconds; + } else { + return ""; + } + }, + axisLabel: "Time", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 10 + }, + yaxes: [ + { + min: 0, + max: $scope.memory, + tickSize: 5, + tickFormatter: function (v, axis) { + if (v % 10 == 0) { + return v + "MB"; + } else { + return ""; + } + }, + axisLabel: "CPU loading", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + }, { + max: 5120, + position: "right", + axisLabel: "Disk", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + } + ], + legend: { + noColumns: 0, + position: "nw" + }, + grid: { + backgroundColor: {colors: ["#ffffff", "#EDF5FF"]} + } + }; + + function initDataMemory() { + for (var i = 0; i < totalPointsMemory; i++) { + var temp = [nowMemory += updateIntervalMemory, 0]; + + memory.push(temp); + } + } + + function GetDataMemory() { + + var data = { + domain: $("#domain").text(), + type: 'memory' + }; + $.ajaxSetup({cache: false}); + + $.ajax({ + url: "/CloudLinux/getUsageData", + dataType: 'json', + headers: {'X-CSRFToken': getCookie('csrftoken')}, + success: updateMemory, + type: "POST", + contentType: "application/json", + data: JSON.stringify(data), // Our valid JSON string + error: function () { + setTimeout(GetDataMemory, updateIntervalMemory); + } + }); + } + + var tempMemory; + + function updateMemory(_data) { + memory.shift(); + + nowMemory += updateIntervalMemory; + + tempMemory = [nowMemory, _data.memory]; + memory.push(tempMemory); + + + datasetMemory = [ + { + label: "Memory:" + _data.memory + "MB", + data: memory, + lines: {fill: true, lineWidth: 1.2}, + color: "#00FF00" + } + ]; + + $.plot($("#memoryUsage"), datasetMemory, optionsMemory); + setTimeout(GetDataMemory, updateIntervalMemory); + } + + // Disk Usage + + var readRate = [], writeRate = []; + var datasetDisk; + var totalPointsDisk = 100; + var updateIntervalDisk = 5000; + var now = new Date().getTime(); + + var optionsDisk = { + series: { + lines: { + lineWidth: 1.2 + }, + bars: { + align: "center", + fillColor: {colors: [{opacity: 1}, {opacity: 1}]}, + barWidth: 500, + lineWidth: 1 + } + }, + xaxis: { + mode: "time", + tickSize: [30, "second"], + tickFormatter: function (v, axis) { + var date = new Date(v); + + if (date.getSeconds() % 20 == 0) { + var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); + var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); + var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); + + return hours + ":" + minutes + ":" + seconds; + } else { + return ""; + } + }, + axisLabel: "Time", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 10 + }, + yaxes: [ + { + min: 0, + max: $scope.networkSpeed, + tickSize: 5, + tickFormatter: function (v, axis) { + if (v % 10 == 0) { + return v + "mb/sec"; + } else { + return ""; + } + }, + axisLabel: "CPU loading", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + }, { + max: 5120, + position: "right", + axisLabel: "Disk", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + } + ], + legend: { + noColumns: 0, + position: "nw" + }, + grid: { + backgroundColor: {colors: ["#ffffff", "#EDF5FF"]} + } + }; + + function initDataDisk() { + for (var i = 0; i < totalPointsDisk; i++) { + var temp = [now += updateIntervalDisk, 0]; + + readRate.push(temp); + writeRate.push(temp); + } + } + + function GetDataDisk() { + + var data = { + domain: $("#domain").text(), + type: 'io' + }; + + $.ajaxSetup({cache: false}); + + $.ajax({ + url: "/CloudLinux/getUsageData", + dataType: 'json', + headers: {'X-CSRFToken': getCookie('csrftoken')}, + success: updateDisk, + type: "POST", + contentType: "application/json", + data: JSON.stringify(data), // Our valid JSON string + error: function () { + setTimeout(GetDataMemory, updateIntervalMemory); + } + }); + } + + var tempDisk; + + function updateDisk(_data) { + readRate.shift(); + writeRate.shift(); + + now += updateIntervalDisk; + + tempDisk = [now, _data.readRate]; + readRate.push(tempDisk); + + tempDisk = [now, _data.readRate]; + writeRate.push(tempDisk); + + datasetDisk = [ + { + label: "Read IO/s " + _data.readRate + " mb/s ", + data: readRate, + lines: {fill: true, lineWidth: 1.2}, + color: "#00FF00" + }, + { + label: "Write IO/s " + _data.writeRate + " mb/s ", + data: writeRate, + lines: {lineWidth: 1.2}, + color: "#FF0000" + } + ]; + + $.plot($("#diskUsage"), datasetDisk, optionsDisk); + setTimeout(GetDataDisk, updateIntervalDisk); + } + + + $(document).ready(function () { + + // Report Memory Usage + + initDataMemory(); + + datasetMemory = [ + {label: "Memory", data: memory, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"} + ]; + + $.plot($("#memoryUsage"), datasetMemory, optionsMemory); + setTimeout(GetDataMemory, updateIntervalMemory); + + // Report CPU Usage + + initData(); + + dataset = [ + {label: "CPU", data: cpu, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"} + ]; + + $.plot($("#flot-placeholder1"), dataset, options); + setTimeout(GetData, updateInterval); + + // Report Disk Usage + + initDataDisk(); + + datasetDisk = [ + {label: "Read IO/s: ", data: readRate, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"}, + {label: "Write IO/s: ", data: writeRate, color: "#0044FF", bars: {show: true}, yaxis: 2} + ]; + + $.plot($("#diskUsage"), datasetDisk, optionsDisk); + setTimeout(GetDataDisk, updateIntervalDisk); + }); +}); \ No newline at end of file diff --git a/CLManager/templates/CLManager/createPackage.html b/CLManager/templates/CLManager/createPackage.html new file mode 100755 index 000000000..e7e0c2fba --- /dev/null +++ b/CLManager/templates/CLManager/createPackage.html @@ -0,0 +1,146 @@ +{% extends "baseTemplate/index.html" %} +{% load i18n %} +{% block title %}{% trans "Create Cloud Linux Package - CyberPanel" %}{% endblock %} +{% block content %} + + {% load static %} +
    +
    +

    {% trans "Create CloudLinux Package." %}

    +

    {% trans "Each CloudLinux package have one associated (owner) CyberPanel package. During website creation associated CloudLinux package will be assigned to website user." %}

    +
    +
    +
    +

    + {% trans "Create Package" %} +

    +
    + + +
    + + +
    + +
    + +
    +
    + + + + +
    + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    Ex 100%
    +
    + + +
    + +
    + +
    +
    Ex 256m or 1G
    +
    + +
    + +
    + +
    +
    Ex 256m or 1G
    +
    + + +
    + +
    + +
    +
    Ex 1024
    +
    + +
    + +
    + +
    +
    Ex 1024
    +
    + +
    + +
    + +
    +
    Ex 10
    +
    + +
    + +
    + +
    +
    Ex 10
    +
    + +
    + +
    + +
    +
    Ex 1024
    +
    + +
    + +
    + +
    +
    Ex 1024
    +
    + + +
    + + + + +
    + +
    + + +
    +
    + +
    + + +
    +
    +
    + + +
    + + +{% endblock %} diff --git a/CLManager/templates/CLManager/listPackages.html b/CLManager/templates/CLManager/listPackages.html new file mode 100755 index 000000000..c7442359c --- /dev/null +++ b/CLManager/templates/CLManager/listPackages.html @@ -0,0 +1,236 @@ +{% extends "baseTemplate/index.html" %} +{% load i18n %} +{% block title %}{% trans "Manage CloudLinux Packages - CyberPanel" %}{% endblock %} +{% block content %} + + {% load static %} + {% get_current_language as LANGUAGE_CODE %} + + + +
    + +
    +

    {% trans "Manage CloudLinux Packages" %}

    +

    {% trans "Manage/Delete CloudLinux Packages." %}

    +
    + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSPEEDVMEMPMEMIOIOPSEPNPROCINODES softINODES hardActions
    + Delete + Edit + +
    + +
    +

    {% trans "Cannot list websites. Error message:" %} {$ errorMessage $}

    +
    + +
    + +
    + + + + +
    + + +
    + +
    +
    +
    + +
    + + + +{% endblock %} \ No newline at end of file diff --git a/CLManager/templates/CLManager/listWebsites.html b/CLManager/templates/CLManager/listWebsites.html new file mode 100755 index 000000000..cd0e24528 --- /dev/null +++ b/CLManager/templates/CLManager/listWebsites.html @@ -0,0 +1,117 @@ +{% extends "baseTemplate/index.html" %} +{% load i18n %} +{% block title %}{% trans "CageFS - CyberPanel" %}{% endblock %} +{% block content %} + + {% load static %} + {% get_current_language as LANGUAGE_CODE %} + + + +
    + +
    +

    {% trans "List Websites" %}

    +

    {% trans "Enable/Disable and view CageFS status for websites." %}

    +
    + +
    +
    + +
    + + + + + + + + + + + + + + + + + + +
    Domain UserActions
    + Disable + Enable +
    + +
    +

    {% trans "Cannot list websites. Error message:" %} {$ errorMessage $}

    +
    + +
    + +
    + + + + +
    + + +
    + +
    +
    +
    + +
    + + + +{% endblock %} \ No newline at end of file diff --git a/CLManager/templates/CLManager/monitorUsage.html b/CLManager/templates/CLManager/monitorUsage.html new file mode 100755 index 000000000..8eccc09b8 --- /dev/null +++ b/CLManager/templates/CLManager/monitorUsage.html @@ -0,0 +1,87 @@ +{% extends "baseTemplate/index.html" %} +{% load i18n %} +{% block title %}{% trans "Monitor Usage - CyberPanel" %}{% endblock %} +{% block content %} + + {% load static %} + {% get_current_language as LANGUAGE_CODE %} + + + +
    + +
    +

    {% trans "List Websites" %}

    +

    {% trans "Monitor usage of your websites." %}

    +
    + +
    +
    +

    + {% trans "Websites" %} +

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    DomainLaunchIP AddressPackageOwnerStateEmail
    +
    + +
    +

    {% trans "Cannot list websites. Error message:" %} {$ errorMessage $}

    +
    + +
    + +
    + + + + +
    + + +
    + +
    +
    +
    + +
    + + + +{% endblock %} \ No newline at end of file diff --git a/CLManager/templates/CLManager/notAvailable.html b/CLManager/templates/CLManager/notAvailable.html new file mode 100755 index 000000000..c597c3827 --- /dev/null +++ b/CLManager/templates/CLManager/notAvailable.html @@ -0,0 +1,67 @@ +{% extends "baseTemplate/index.html" %} +{% load i18n %} +{% block title %}{% trans "Not available - CyberPanel" %}{% endblock %} +{% block content %} + + {% load static %} + {% get_current_language as LANGUAGE_CODE %} + + + +
    +
    +

    {% trans "Not available" %}

    +

    {% trans "Either CageFS is not installed or you are not on CloudLinux OS." %}

    +
    + + {% if not CL %} + +
    +
    +
    +

    {% trans "CageFS is only available with CloudLinux OS. " %} Click + Here {% trans " for conversion details." %}

    +
    +
    +
    + + {% else %} + +
    +
    +

    + {% trans "Install Packages" %} +

    +
    + +

    {% trans "CageFS is not installed on this server. Please proceed to installation." %}

    + + +
    + +
    +
    +
    + +
    +
    +
    +
    + + + +
    + + +
    +
    +
    + + {% endif %} + +
    +{% endblock %} + diff --git a/CLManager/templates/CLManager/websiteContainerLimit.html b/CLManager/templates/CLManager/websiteContainerLimit.html new file mode 100755 index 000000000..13fac7c7b --- /dev/null +++ b/CLManager/templates/CLManager/websiteContainerLimit.html @@ -0,0 +1,52 @@ +{% extends "baseTemplate/index.html" %} +{% load i18n %} +{% block title %}{{ domain }}{% trans " usage - CyberPanel" %}{% endblock %} +{% block content %} + + {% load static %} + {% get_current_language as LANGUAGE_CODE %} + + + +
    + +
    +

    {% trans "Usage" %}

    +

    {% trans "View CPU, Memory and Disk usage for " %} {{ domain }}

    +
    + +
    +
    +

    + {% trans "CPU Usage of" %} {{ domain }} +

    +
    +
    + +
    +
    +
    +

    + {% trans "Memory Usage of" %} {{ domain }} +

    +
    +
    + +
    +
    +
    +

    + {% trans "Disk Usage of" %} {{ domain }} +

    +
    +
    + +
    +
    +
    + +
    + + + +{% endblock %} \ No newline at end of file diff --git a/CLManager/tests.py b/CLManager/tests.py new file mode 100644 index 000000000..5982e6bcd --- /dev/null +++ b/CLManager/tests.py @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.test import TestCase + +# Create your tests here. diff --git a/CLManager/urls.py b/CLManager/urls.py new file mode 100644 index 000000000..d7a531c43 --- /dev/null +++ b/CLManager/urls.py @@ -0,0 +1,18 @@ +from django.conf.urls import url +import views + +urlpatterns = [ + url(r'^CageFS$', views.CageFS, name='CageFS'), + url(r'^submitCageFSInstall$', views.submitCageFSInstall, name='submitCageFSInstall'), + url(r'^submitWebsiteListing$', views.getFurtherAccounts, name='submitWebsiteListing'), + url(r'^enableOrDisable$', views.enableOrDisable, name='enableOrDisable'), + url(r'^CreatePackage$', views.CreatePackage, name='CreatePackageCL'), + url(r'^submitCreatePackage$', views.submitCreatePackage, name='submitCreatePackageCL'), + url(r'^listPackages$', views.listPackages, name='listPackagesCL'), + url(r'^fetchPackages$', views.fetchPackages, name='fetchPackagesCL'), + url(r'^deleteCLPackage$', views.deleteCLPackage, name='deleteCLPackage'), + url(r'^saveSettings$', views.saveSettings, name='saveSettings'), + url(r'^monitorUsage$', views.monitorUsage, name='monitorUsage'), + url(r'^manage/(?P(.*))$', views.websiteContainerLimit, name='websiteContainerLimitCL'), + url(r'^getUsageData$', views.getUsageData, name='getUsageData'), +] \ No newline at end of file diff --git a/CLManager/views.py b/CLManager/views.py new file mode 100644 index 000000000..e02a3a040 --- /dev/null +++ b/CLManager/views.py @@ -0,0 +1,358 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.shortcuts import redirect, HttpResponse +from loginSystem.views import loadLoginPage +from plogical.acl import ACLManager +from CLManagerMain import CLManagerMain +import json +from websiteFunctions.models import Websites +from plogical.processUtilities import ProcessUtilities +import os +from packages.models import Package +from .models import CLPackages +import subprocess +import multiprocessing +import pwd +from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging +# Create your views here. + +def CageFS(request): + try: + templateName = 'CLManager/listWebsites.html' + c = CLManagerMain(request, templateName) + return c.renderC() + except KeyError: + return redirect(loadLoginPage) + +def submitCageFSInstall(request): + try: + + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson() + + c = CLManagerMain(request, None, 'submitCageFSInstall') + c.start() + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + +def getFurtherAccounts(request): + try: + userID = request.session['userID'] + wm = CLManagerMain() + return wm.getFurtherAccounts(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) + +def enableOrDisable(request): + try: + + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson() + + data = json.loads(request.body) + + if data['toggle'] == 1: + cageFSPath = '/home/cyberpanel/cagefs' + if os.path.exists(cageFSPath): + os.remove(cageFSPath) + else: + writeToFile = open(cageFSPath, 'w') + writeToFile.writelines('enable') + writeToFile.close() + + data_ret = {'status': 1, 'error_message': 'None', 'success': 'Default status successfully changed changed.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if data['all'] == 0: + if data['mode'] == 1: + website = Websites.objects.get(domain=data['domain']) + command = '/usr/sbin/cagefsctl --enable %s' % (website.externalApp) + else: + website = Websites.objects.get(domain=data['domain']) + command = '/usr/sbin/cagefsctl --disable %s' % (website.externalApp) + + ProcessUtilities.executioner(command) + data_ret = {'status': 1, 'error_message': 'None', 'success': 'Changes successfully applied.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + c = CLManagerMain(request, None, 'enableOrDisable', data) + c.start() + + data_ret = {'status': 1, 'error_message': 'None', 'success': 'Job started in background, refresh in few seconds to see the status.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + + except BaseException, msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + +def CreatePackage(request): + try: + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + templateName = 'CLManager/createPackage.html' + packageList = ACLManager.loadPackages(userID, currentACL) + data = {} + data['packList'] = packageList + c = CLManagerMain(request, templateName, None, data) + return c.renderC() + except KeyError: + return redirect(loadLoginPage) + +def submitCreatePackage(request): + try: + + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson() + + data = json.loads(request.body) + + selectedPackage = data['selectedPackage'] + + package = Package.objects.get(packageName=selectedPackage) + + if package.clpackages_set.all().count() == 1: + data_ret = {'status': 0, 'error_message': 'This package already have one associated CloudLinux Package.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + name = data['name'] + SPEED = data['SPEED'] + VMEM = data['VMEM'] + PMEM = data['PMEM'] + IO = data['IO'] + IOPS = data['IOPS'] + EP = data['EP'] + NPROC = data['NPROC'] + INODESsoft = data['INODESsoft'] + INODEShard = data['INODEShard'] + + clPackage = CLPackages(name=name, owner=package, speed=SPEED, vmem=VMEM, pmem=PMEM, io=IO, iops=IOPS, ep=EP, nproc=NPROC, inodessoft=INODESsoft, inodeshard=INODEShard) + clPackage.save() + + command = 'sudo lvectl package-set %s --speed=%s --pmem=%s --io=%s --nproc=%s --iops=%s --vmem=%s --ep=%s' % (name, SPEED, PMEM, IO, NPROC, IOPS, VMEM, EP) + ProcessUtilities.executioner(command) + + command = 'sudo lvectl apply all' + ProcessUtilities.popenExecutioner(command) + + data_ret = {'status': 1} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException, msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + +def listPackages(request): + try: + templateName = 'CLManager/listPackages.html' + c = CLManagerMain(request, templateName) + return c.renderC() + except KeyError: + return redirect(loadLoginPage) + +def fetchPackages(request): + try: + userID = request.session['userID'] + wm = CLManagerMain() + return wm.fetchPackages(ACLManager.loadedACL(userID)) + except KeyError: + return redirect(loadLoginPage) + +def deleteCLPackage(request): + try: + + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson() + + data = json.loads(request.body) + + name = data['name'] + + clPackage = CLPackages.objects.get(name=name) + clPackage.delete() + + data_ret = {'status': 1} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException, msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + +def saveSettings(request): + try: + + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson() + + data = json.loads(request.body) + + name = data['name'] + SPEED = data['SPEED'] + VMEM = data['VMEM'] + PMEM = data['PMEM'] + IO = data['IO'] + IOPS = data['IOPS'] + EP = data['EP'] + NPROC = data['NPROC'] + INODESsoft = data['INODESsoft'] + INODEShard = data['INODEShard'] + + clPackage = CLPackages.objects.get(name=name) + clPackage.speed = SPEED + clPackage.vmem = VMEM + clPackage.pmem = PMEM + clPackage.io = IO + clPackage.iops = IOPS + clPackage.ep = EP + clPackage.nproc = NPROC + clPackage.inodessoft = INODESsoft + clPackage.inodeshard = INODEShard + clPackage.save() + + command = 'sudo lvectl package-set %s --speed=%s --pmem=%s --io=%s --nproc=%s --iops=%s --vmem=%s --ep=%s' % ( + name, SPEED, PMEM, IO, NPROC, IOPS, VMEM, EP) + ProcessUtilities.executioner(command) + + command = 'sudo lvectl apply all' + ProcessUtilities.popenExecutioner(command) + + data_ret = {'status': 1} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException, msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + +def monitorUsage(request): + try: + templateName = 'CLManager/monitorUsage.html' + c = CLManagerMain(request, templateName) + return c.renderC() + except KeyError: + return redirect(loadLoginPage) + +def websiteContainerLimit(request, domain): + try: + templateName = 'CLManager/websiteContainerLimit.html' + data = {} + data['domain'] = domain + c = CLManagerMain(request, templateName, None, data) + return c.renderC() + except KeyError: + return redirect(loadLoginPage) + +def getUsageData(request): + try: + + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson() + + data = json.loads(request.body) + domain = data['domain'] + website = Websites.objects.get(domain=domain) + uid = pwd.getpwnam(website.externalApp).pw_uid + + try: + type = data['type'] + finalData = {} + finalData['status'] = 1 + + try: + if type == 'memory': + + command = 'sudo lveps -o id:10,mem:10' + output = ProcessUtilities.outputExecutioner(command).splitlines() + for items in output: + if items.find(website.externalApp) > -1: + finalData['memory'] = int(items.split(' ')[-1]) + break + + elif type == 'io': + + finalData['readRate'] = 0 + finalData['writeRate'] = 0 + + command = 'sudo lveps -o id:10,iops:10' + output = ProcessUtilities.outputExecutioner(command).splitlines() + for items in output: + if items.find(website.externalApp) > -1: + finalData['readRate'] = int(items.split(' ')[-1]) + break + + except: + finalData['memory'] = '0' + finalData['readRate'] = 0 + finalData['writeRate'] = 0 + except: + + finalData = {} + finalData['status'] = 1 + + command = 'sudo lveps -o id:10,cpu:10 -d' + output = ProcessUtilities.outputExecutioner(command).splitlines() + + for items in output: + if items.find(website.externalApp) > -1: + finalData['cpu'] = int(items.split(' ')[-1].rstrip('%')) + break + + final_json = json.dumps(finalData) + return HttpResponse(final_json) + + except BaseException, msg: + data_ret = {'status': 0, 'error_message': str(msg), 'cpu': 0, 'memory':0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) \ No newline at end of file diff --git a/CyberCP/secMiddleware.py b/CyberCP/secMiddleware.py index 9c8a0923d..e1ade8a9c 100755 --- a/CyberCP/secMiddleware.py +++ b/CyberCP/secMiddleware.py @@ -8,6 +8,18 @@ class secMiddleware: self.get_response = get_response def __call__(self, request): + try: + uID = request.session['userID'] + if request.session['ipAddr'] == request.META.get('REMOTE_ADDR'): + pass + else: + logging.writeToFile(request.META.get('REMOTE_ADDR')) + final_dic = {'error_message': "Session reuse detected, IPAddress logged.", + "errorMessage": "Session reuse detected, IPAddress logged."} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except: + pass if request.method == 'POST': try: #logging.writeToFile(request.body) @@ -28,17 +40,23 @@ class secMiddleware: else: continue - if request.build_absolute_uri().find('filemanager') > -1: + if request.build_absolute_uri().find('cloudAPI') > -1 or request.build_absolute_uri().find('filemanager') > -1 or request.build_absolute_uri().find('verifyLogin') > -1 or request.build_absolute_uri().find('submitUserCreation') > -1: continue - if key == 'emailMessage' or key == 'configData' or key == 'rewriteRules' or key == 'modSecRules' or key == 'recordContentTXT' or key == 'SecAuditLogRelevantStatus' or key == 'fileContent': + if key == 'passwordByPass' or key == 'cronCommand' or key == 'emailMessage' or key == 'configData' or key == 'rewriteRules' or key == 'modSecRules' or key == 'recordContentTXT' or key == 'SecAuditLogRelevantStatus' or key == 'fileContent': continue - if value.find(';') > -1 or value.find('&&') > -1 or value.find('|') > -1 or value.find('...') > -1: + if value.find(';') > -1 or value.find('&&') > -1 or value.find('|') > -1 or value.find('...') > -1 \ + or value.find("`") > -1 or value.find("$") > -1 or value.find("(") > -1 or value.find(")") > -1 \ + or value.find("'") > -1 or value.find("[") > -1 or value.find("]") > -1 or value.find("{") > -1 or value.find("}") > -1\ + or value.find(":") > -1 or value.find("<") > -1 or value.find(">") > -1: logging.writeToFile(request.body) final_dic = {'error_message': "Data supplied is not accepted.", "errorMessage": "Data supplied is not accepted."} final_json = json.dumps(final_dic) return HttpResponse(final_json) - if key.find(';') > -1 or key.find('&&') > -1 or key.find('|') > -1 or key.find('...') > -1: + if key.find(';') > -1 or key.find('&&') > -1 or key.find('|') > -1 or key.find('...') > -1 \ + or key.find("`") > -1 or key.find("$") > -1 or key.find("(") > -1 or key.find(")") > -1 \ + or key.find("'") > -1 or key.find("[") > -1 or key.find("]") > -1 or key.find("{") > -1 or key.find("}") > -1\ + or key.find(":") > -1 or key.find("<") > -1 or key.find(">") > -1: logging.writeToFile(request.body) final_dic = {'error_message': "Data supplied is not accepted.", "errorMessage": "Data supplied is not accepted."} final_json = json.dumps(final_dic) diff --git a/CyberCP/settings.py b/CyberCP/settings.py index 6892a9d23..77a7aeecd 100755 --- a/CyberCP/settings.py +++ b/CyberCP/settings.py @@ -63,7 +63,8 @@ INSTALLED_APPS = [ 'highAvailability', 's3Backups', 'dockerManager', - 'containerization' + 'containerization', + 'CLManager' ] MIDDLEWARE = [ @@ -71,6 +72,7 @@ MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', @@ -157,7 +159,6 @@ USE_L10N = True USE_TZ = True - # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ diff --git a/CyberCP/urls.py b/CyberCP/urls.py index fdfd5addc..48f0ff276 100755 --- a/CyberCP/urls.py +++ b/CyberCP/urls.py @@ -42,4 +42,5 @@ urlpatterns = [ url(r'^cloudAPI/', include('cloudAPI.urls')), url(r'^docker/', include('dockerManager.urls')), url(r'^container/', include('containerization.urls')), + url(r'^CloudLinux/', include('CLManager.urls')), ] diff --git a/api/views.py b/api/views.py index 88ad396e7..3be35b466 100755 --- a/api/views.py +++ b/api/views.py @@ -14,15 +14,13 @@ import os from baseTemplate.models import version from plogical.mailUtilities import mailUtilities from plogical.website import WebsiteManager -from loginSystem.models import ACL -from plogical.acl import ACLManager -from firewall.models import FirewallRules from s3Backups.s3Backups import S3Backups from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging from plogical.processUtilities import ProcessUtilities +from django.views.decorators.csrf import csrf_exempt # Create your views here. - +@csrf_exempt def verifyConn(request): try: if request.method == 'POST': @@ -52,6 +50,7 @@ def verifyConn(request): json_data = json.dumps(data_ret) return HttpResponse(json_data) +@csrf_exempt def createWebsite(request): data = json.loads(request.body) adminUser = data['adminUser'] @@ -66,6 +65,7 @@ def createWebsite(request): wm = WebsiteManager() return wm.createWebsiteAPI(json.loads(request.body)) +@csrf_exempt def getUserInfo(request): try: if request.method == 'POST': @@ -111,6 +111,7 @@ def getUserInfo(request): json_data = json.dumps(data_ret) return HttpResponse(json_data) +@csrf_exempt def changeUserPassAPI(request): try: if request.method == 'POST': @@ -155,6 +156,7 @@ def changeUserPassAPI(request): json_data = json.dumps(data_ret) return HttpResponse(json_data) +@csrf_exempt def changePackageAPI(request): try: if request.method == 'POST': @@ -199,6 +201,7 @@ def changePackageAPI(request): json_data = json.dumps(data_ret) return HttpResponse(json_data) +@csrf_exempt def deleteWebsite(request): try: if request.method == 'POST': @@ -243,6 +246,7 @@ def deleteWebsite(request): json_data = json.dumps(data_ret) return HttpResponse(json_data) +@csrf_exempt def submitWebsiteStatus(request): try: if request.method == 'POST': @@ -273,6 +277,7 @@ def submitWebsiteStatus(request): json_data = json.dumps(data_ret) return HttpResponse(json_data) +@csrf_exempt def loginAPI(request): try: username = request.POST['username'] @@ -296,6 +301,7 @@ def loginAPI(request): json_data = json.dumps(data) return HttpResponse(json_data) +@csrf_exempt def fetchSSHkey(request): try: if request.method == "POST": @@ -313,7 +319,7 @@ def fetchSSHkey(request): if hashPassword.check_password(admin.password, password): pubKey = os.path.join("/root",".ssh",'cyberpanel.pub') - execPath = "sudo cat " + pubKey + execPath = "cat " + pubKey data = ProcessUtilities.outputExecutioner(execPath) data_ret = { @@ -338,6 +344,7 @@ def fetchSSHkey(request): json_data = json.dumps(data) return HttpResponse(json_data) +@csrf_exempt def remoteTransfer(request): try: if request.method == "POST": @@ -372,7 +379,7 @@ def remoteTransfer(request): ## Accounts to transfer is a path to file, containing accounts. - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/remoteTransferUtilities.py" + execPath = "python " + virtualHostUtilities.cyberPanel + "/plogical/remoteTransferUtilities.py" execPath = execPath + " remoteTransfer --ipAddress " + ipAddress + " --dir " + dir + " --accountsToTransfer " + path ProcessUtilities.popenExecutioner(execPath) @@ -389,6 +396,7 @@ def remoteTransfer(request): json_data = json.dumps(data) return HttpResponse(json_data) +@csrf_exempt def fetchAccountsFromRemoteServer(request): try: if request.method == "POST": @@ -438,6 +446,7 @@ def fetchAccountsFromRemoteServer(request): json_data = json.dumps(data) return HttpResponse(json_data) +@csrf_exempt def FetchRemoteTransferStatus(request): try: if request.method == "POST": @@ -455,7 +464,7 @@ def FetchRemoteTransferStatus(request): dir = "/home/backup/transfer-"+str(data['dir'])+"/backup_log" try: - command = "sudo cat "+ dir + command = "cat "+ dir status = ProcessUtilities.outputExecutioner(command) @@ -478,6 +487,7 @@ def FetchRemoteTransferStatus(request): json_data = json.dumps(data) return HttpResponse(json_data) +@csrf_exempt def cancelRemoteTransfer(request): try: if request.method == "POST": @@ -500,13 +510,13 @@ def cancelRemoteTransfer(request): path = dir + "/pid" - command = "sudo cat " + path + command = "cat " + path pid = ProcessUtilities.outputExecutioner(command) - command = "sudo kill -KILL " + pid + command = "kill -KILL " + pid ProcessUtilities.executioner(command) - command = "sudo rm -rf " + dir + command = "rm -rf " + dir ProcessUtilities.executioner(command) data = {'cancelStatus': 1, 'error_message': "None"} @@ -524,6 +534,7 @@ def cancelRemoteTransfer(request): json_data = json.dumps(data) return HttpResponse(json_data) +@csrf_exempt def cyberPanelVersion(request): try: if request.method == 'POST': @@ -570,6 +581,7 @@ def cyberPanelVersion(request): json_data = json.dumps(data_ret) return HttpResponse(json_data) +@csrf_exempt def runAWSBackups(request): try: diff --git a/backup/backupManager.py b/backup/backupManager.py index 7bfdd4231..9ad618a1a 100755 --- a/backup/backupManager.py +++ b/backup/backupManager.py @@ -21,6 +21,7 @@ import time import plogical.backupUtilities as backupUtil import requests from plogical.processUtilities import ProcessUtilities +from multiprocessing import Process class BackupManager: def __init__(self, domain = None, childDomain = None): @@ -85,6 +86,11 @@ class BackupManager: else: return ACLManager.loadErrorJson('fetchStatus', 0) + if ACLManager.checkOwnership(backupDomain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + website = Websites.objects.get(domain=backupDomain) backups = website.backups_set.all() @@ -141,11 +147,9 @@ class BackupManager: ## /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 - ProcessUtilities.popenExecutioner(execPath) + p = Process(target=backupUtil.submitBackupCreation, args=(tempStoragePath, backupName, backupPath,backupDomain)) + p.start() time.sleep(2) @@ -166,11 +170,13 @@ class BackupManager: backupFileNamePath = os.path.join("/home", backupDomain, "backup/backupFileName") pid = os.path.join("/home", backupDomain, "backup/pid") + domain = Websites.objects.get(domain=backupDomain) + ## read file name try: command = "sudo cat " + backupFileNamePath - fileName = ProcessUtilities.outputExecutioner(command) + fileName = ProcessUtilities.outputExecutioner(command, domain.externalApp) except: fileName = "Fetching.." @@ -178,20 +184,20 @@ class BackupManager: if os.path.exists(status): command = "sudo cat " + status - status = ProcessUtilities.outputExecutioner(command) + status = ProcessUtilities.outputExecutioner(command, domain.externalApp) if status.find("Completed") > -1: ### Removing Files command = 'sudo rm -f ' + status - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, domain.externalApp) command = 'sudo rm -f ' + backupFileNamePath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, domain.externalApp) command = 'sudo rm -f ' + pid - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, domain.externalApp) final_json = json.dumps( {'backupStatus': 1, 'error_message': "None", "status": status, "abort": 1, @@ -202,13 +208,13 @@ class BackupManager: ## removing status file, so that backup can re-run try: command = 'sudo rm -f ' + status - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, domain.externalApp) command = 'sudo rm -f ' + backupFileNamePath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, domain.externalApp) command = 'sudo rm -f ' + pid - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, domain.externalApp) backupObs = Backups.objects.filter(fileName=fileName) for items in backupObs: @@ -243,9 +249,7 @@ class BackupManager: fileName = data['fileName'] execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" - execPath = execPath + " cancelBackupCreation --backupCancellationDomain " + backupCancellationDomain + " --fileName " + fileName - subprocess.call(shlex.split(execPath)) try: @@ -268,6 +272,12 @@ class BackupManager: backup = Backups.objects.get(id=backupID) domainName = backup.website.domain + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() path = "/home/" + domainName + "/backup/" + backup.fileName + ".tar.gz" command = 'sudo rm -f ' + path @@ -283,7 +293,7 @@ class BackupManager: return HttpResponse(final_json) - def submitRestore(self, data = None): + def submitRestore(self, data = None, userID = None): try: backupFile = data['backupFile'] originalFile = "/home/backup/" + backupFile @@ -293,6 +303,12 @@ class BackupManager: else: dir = "CyberPanelRestore" + currentACL = ACLManager.loadedACL(userID) + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson() + execPath = "sudo nice -n 10 python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" execPath = execPath + " submitRestore --backupFile " + backupFile + " --dir " + dir ProcessUtilities.popenExecutioner(execPath) diff --git a/backup/views.py b/backup/views.py index b4796c76a..20b645ea5 100755 --- a/backup/views.py +++ b/backup/views.py @@ -27,6 +27,7 @@ def backupSite(request): except KeyError: return redirect(loadLoginPage) + def restoreSite(request): try: userID = request.session['userID'] @@ -35,6 +36,7 @@ def restoreSite(request): except KeyError: return redirect(loadLoginPage) + def getCurrentBackups(request): try: userID = request.session['userID'] @@ -43,9 +45,10 @@ def getCurrentBackups(request): except KeyError: return redirect(loadLoginPage) + def submitBackupCreation(request): try: - userID = 1 + userID = request.session['userID'] result = pluginManager.preSubmitBackupCreation(request) if result != 200: @@ -59,6 +62,7 @@ def submitBackupCreation(request): except KeyError: return redirect(loadLoginPage) + def backupStatus(request): try: userID = 1 @@ -67,6 +71,7 @@ def backupStatus(request): except KeyError: return redirect(loadLoginPage) + def cancelBackupCreation(request): try: userID = request.session['userID'] @@ -75,6 +80,7 @@ def cancelBackupCreation(request): except KeyError: return redirect(loadLoginPage) + def deleteBackup(request): try: userID = request.session['userID'] @@ -95,19 +101,22 @@ def deleteBackup(request): except KeyError: return redirect(loadLoginPage) + def submitRestore(request): try: + userID = request.session['userID'] result = pluginManager.preSubmitRestore(request) if result != 200: return result wm = BackupManager() - coreResult = wm.submitRestore(json.loads(request.body)) + coreResult = wm.submitRestore(json.loads(request.body), userID) return coreResult except KeyError: return redirect(loadLoginPage) + def restoreStatus(request): try: wm = BackupManager() @@ -115,6 +124,7 @@ def restoreStatus(request): except KeyError: return redirect(loadLoginPage) + def backupDestinations(request): try: userID = request.session['userID'] @@ -123,6 +133,7 @@ def backupDestinations(request): except KeyError: return redirect(loadLoginPage) + def submitDestinationCreation(request): try: userID = request.session['userID'] diff --git a/baseTemplate/static/baseTemplate/custom-js/system-status.js b/baseTemplate/static/baseTemplate/custom-js/system-status.js index 134e67021..1bf3b0d8f 100755 --- a/baseTemplate/static/baseTemplate/custom-js/system-status.js +++ b/baseTemplate/static/baseTemplate/custom-js/system-status.js @@ -23,7 +23,7 @@ function getCookie(name) { } function randomPassword(length) { - var chars = "abcdefghijklmnopqrstuvwxyz!@#$%^*()-+<>ABCDEFGHIJKLMNOP1234567890"; + var chars = "abcdefghijklmnopqrstuvwxyz!@#%^*-+ABCDEFGHIJKLMNOP1234567890"; var pass = ""; for (var x = 0; x < length; x++) { var i = Math.floor(Math.random() * chars.length); diff --git a/baseTemplate/templates/baseTemplate/index.html b/baseTemplate/templates/baseTemplate/index.html index df0c301af..c8e870de7 100755 --- a/baseTemplate/templates/baseTemplate/index.html +++ b/baseTemplate/templates/baseTemplate/index.html @@ -606,6 +606,34 @@
  • {% trans "Server" %}
  • +
  • + + + {% trans "CloudLinux" %} + {% trans "NEW" %} + + +
  • + +
  • @@ -756,6 +784,9 @@
  • {% trans "CSF" %}
  • +
  • {% trans "CageFS" %} +
  • @@ -870,6 +901,7 @@ + diff --git a/baseTemplate/views.py b/baseTemplate/views.py index 04d0c2c2f..eb200406b 100755 --- a/baseTemplate/views.py +++ b/baseTemplate/views.py @@ -16,9 +16,11 @@ import os import plogical.CyberCPLogFileWriter as logging from plogical.acl import ACLManager from manageServices.models import PDNSStatus +from django.views.decorators.csrf import ensure_csrf_cookie # Create your views here. +@ensure_csrf_cookie def renderBase(request): try: userID = request.session['userID'] @@ -89,6 +91,7 @@ def getLoadAverage(request): return HttpResponse(json_data) +@ensure_csrf_cookie def versionManagment(request): try: userID = request.session['userID'] diff --git a/cloudAPI/views.py b/cloudAPI/views.py index 49ab554ea..40df5120d 100755 --- a/cloudAPI/views.py +++ b/cloudAPI/views.py @@ -5,7 +5,9 @@ from cloudManager import CloudManager import json from loginSystem.models import Administrator from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging +from django.views.decorators.csrf import csrf_exempt +@csrf_exempt def router(request): try: data = json.loads(request.body) diff --git a/containerization/containerManager.py b/containerization/containerManager.py index c2e004a76..1a5b573cf 100755 --- a/containerization/containerManager.py +++ b/containerization/containerManager.py @@ -5,7 +5,6 @@ from plogical.acl import ACLManager import plogical.CyberCPLogFileWriter as logging from serverStatus.serverStatusUtil import ServerStatusUtil import os, stat -from plogical.virtualHostUtilities import virtualHostUtilities class ContainerManager(multi.Thread): diff --git a/containerization/static/containerization/containerization.js b/containerization/static/containerization/containerization.js index f0fad7a03..5f4e6b5c0 100755 --- a/containerization/static/containerization/containerization.js +++ b/containerization/static/containerization/containerization.js @@ -200,6 +200,7 @@ app.controller('websiteContainerLimit', function ($scope, $http, $timeout, $wind dataType: 'json', success: update, type: "POST", + headers: { 'X-CSRFToken': getCookie('csrftoken') }, contentType: "application/json", data: JSON.stringify(data), // Our valid JSON string error: function () { @@ -324,6 +325,7 @@ app.controller('websiteContainerLimit', function ($scope, $http, $timeout, $wind $.ajax({ url: "/container/getUsageData", dataType: 'json', + headers: { 'X-CSRFToken': getCookie('csrftoken') }, success: updateMemory, type: "POST", contentType: "application/json", @@ -457,6 +459,7 @@ app.controller('websiteContainerLimit', function ($scope, $http, $timeout, $wind $.ajax({ url: "/container/getUsageData", dataType: 'json', + headers: { 'X-CSRFToken': getCookie('csrftoken') }, success: updateDisk, type: "POST", contentType: "application/json", diff --git a/containerization/views.py b/containerization/views.py index ef0bccfdd..a82414868 100755 --- a/containerization/views.py +++ b/containerization/views.py @@ -10,10 +10,9 @@ from .models import ContainerLimits from random import randint from plogical.processUtilities import ProcessUtilities import os -import subprocess, shlex +import subprocess import multiprocessing from plogical.httpProc import httpProc -from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging from plogical.acl import ACLManager # Create your views here. diff --git a/databases/databaseManager.py b/databases/databaseManager.py index ac2469cbb..0da7cee19 100755 --- a/databases/databaseManager.py +++ b/databases/databaseManager.py @@ -47,6 +47,7 @@ class DatabaseManager: try: currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) if ACLManager.currentContextPermission(currentACL, 'createDatabase') == 0: return ACLManager.loadErrorJson('createDBStatus', 0) @@ -56,6 +57,11 @@ class DatabaseManager: dbPassword = data['dbPassword'] webUsername = data['webUserName'] + if ACLManager.checkOwnership(databaseWebsite, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + if rAPI == None: dbName = webUsername + "_" + dbName dbUsername = webUsername + "_" + dbUsername @@ -98,6 +104,12 @@ class DatabaseManager: databaseWebsite = data['databaseWebsite'] + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(databaseWebsite, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + website = Websites.objects.get(domain=databaseWebsite) databases = Databases.objects.filter(website=website) @@ -128,11 +140,17 @@ class DatabaseManager: def submitDatabaseDeletion(self, userID = None, data = None): try: currentACL = ACLManager.loadedACL(userID) - + admin = Administrator.objects.get(pk=userID) if ACLManager.currentContextPermission(currentACL, 'deleteDatabase') == 0: return ACLManager.loadErrorJson('deleteStatus', 0) dbName = data['dbName'] + db = Databases.objects.get(dbName=dbName) + + if ACLManager.checkOwnership(db.website.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() result = mysqlUtilities.submitDBDeletion(dbName) @@ -172,6 +190,14 @@ class DatabaseManager: userName = data['dbUserName'] dbPassword = data['dbPassword'] + db = Databases.objects.get(dbName=userName) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(db.website.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + res = mysqlUtilities.changePassword(userName, dbPassword) diff --git a/dns/dnsManager.py b/dns/dnsManager.py index 67cf5f9e9..2fc8b32d5 100755 --- a/dns/dnsManager.py +++ b/dns/dnsManager.py @@ -272,6 +272,12 @@ class DNSManager: zoneDomain = data['selectedZone'] currentSelection = data['currentSelection'] + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(zoneDomain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + domain = Domains.objects.get(name=zoneDomain) records = Records.objects.filter(domain_id=domain.id) @@ -336,11 +342,19 @@ class DNSManager: if ACLManager.currentContextPermission(currentACL, 'addDeleteRecords') == 0: return ACLManager.loadErrorJson('add_status', 0) + + zoneDomain = data['selectedZone'] recordType = data['recordType'] recordName = data['recordName'] ttl = int(data['ttl']) + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(zoneDomain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + zone = Domains.objects.get(name=zoneDomain) value = "" @@ -503,6 +517,17 @@ class DNSManager: id = data['id'] delRecord = Records.objects.get(id=id) + + admin = Administrator.objects.get(pk=userID) + if currentACL['admin'] == 1: + pass + elif delRecord.domainOwner.admin == admin: + pass + else: + return ACLManager.loadErrorJson() + + + delRecord.delete() final_dic = {'status': 1, 'delete_status': 1, 'error_message': "None"} @@ -537,10 +562,16 @@ class DNSManager: zoneDomain = data['zoneDomain'] currentACL = ACLManager.loadedACL(userID) - + admin = Administrator.objects.get(pk=userID) if ACLManager.currentContextPermission(currentACL, 'deleteZone') == 0: return ACLManager.loadErrorJson('delete_status', 0) + + if ACLManager.checkOwnership(zoneDomain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + delZone = Domains.objects.get(name=zoneDomain) admin = Administrator.objects.get(pk=userID) if currentACL['admin'] == 1: diff --git a/emailMarketing/emailMarketing.py b/emailMarketing/emailMarketing.py index 18d8aa578..ba9d1b9a4 100755 --- a/emailMarketing/emailMarketing.py +++ b/emailMarketing/emailMarketing.py @@ -212,7 +212,7 @@ class emailMarketing(multi.Thread): messageFile.close() command = "sudo sed -i 's/{{ unsubscribeCheck }}/" + removalLink + "/g' " + tempPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, 'cyberpanel') messageFile = open(tempPath, 'r') finalMessage = messageFile.read() diff --git a/emailMarketing/emailMarketingManager.py b/emailMarketing/emailMarketingManager.py index 4c1edc433..53f2f8d56 100755 --- a/emailMarketing/emailMarketingManager.py +++ b/emailMarketing/emailMarketingManager.py @@ -205,7 +205,7 @@ class EmailMarketingManager: if currentACL['admin'] == 1: pass elif emailList.owner.id != userID: - ACLManager.loadErrorJson() + return ACLManager.loadErrorJson() emails = emailList.emailsinlist_set.all() @@ -274,7 +274,7 @@ class EmailMarketingManager: if currentACL['admin'] == 1: pass elif delList.owner.id != userID: - ACLManager.loadErrorJson() + return ACLManager.loadErrorJson() delList.delete() @@ -304,7 +304,7 @@ class EmailMarketingManager: if currentACL['admin'] == 1: pass elif delList.owner.id != userID: - ACLManager.loadErrorJson() + return ACLManager.loadErrorJson() em = EM('verificationJob', extraArgs) em.start() @@ -337,7 +337,7 @@ class EmailMarketingManager: if currentACL['admin'] == 1: pass elif delEmail.owner.owner.id != userID: - ACLManager.loadErrorJson() + return ACLManager.loadErrorJson() delEmail.delete() @@ -488,7 +488,7 @@ class EmailMarketingManager: if currentACL['admin'] == 1: pass elif delHost.owner.id != userID: - ACLManager.loadErrorJson() + return ACLManager.loadErrorJson() delHost.delete() data_ret = {"status": 1, 'message': 'Successfully deleted.'} json_data = json.dumps(data_ret) diff --git a/filemanager/filemanager.py b/filemanager/filemanager.py index cea0145d3..33a9a2e4e 100755 --- a/filemanager/filemanager.py +++ b/filemanager/filemanager.py @@ -7,6 +7,7 @@ from websiteFunctions.models import Websites from random import randint from django.core.files.storage import FileSystemStorage import HTMLParser +import os class FileManager: def __init__(self, request, data): @@ -22,6 +23,7 @@ class FileManager: def returnPathEnclosed(self, path): htmlParser = HTMLParser.HTMLParser() path = htmlParser.unescape(path) + return path return "'" + path + "'" def changeOwner(self, path): @@ -31,20 +33,23 @@ class FileManager: if path.find('..') > -1: return self.ajaxPre(0, 'Not allowed to move in this path, please choose location inside home!') - command = "sudo chown -R " + website.externalApp + ':' + website.externalApp + ' ' + self.returnPathEnclosed(path) - ProcessUtilities.executioner(command) + command = "chown -R " + website.externalApp + ':' + website.externalApp + ' ' + self.returnPathEnclosed(path) + ProcessUtilities.executioner(command, website.externalApp) def listForTable(self): try: finalData = {} finalData['status'] = 1 + domainName = self.data['domainName'] + website = Websites.objects.get(domain=domainName) + if not self.data['completeStartingPath'].find(self.data['home']) > -1: return self.ajaxPre(0, 'Not allowed to browse this path, going back home!') - command = "sudo ls -la --group-directories-first " + self.returnPathEnclosed( + command = "ls -la --group-directories-first " + self.returnPathEnclosed( self.data['completeStartingPath']) - output = ProcessUtilities.outputExecutioner(command).splitlines() + output = ProcessUtilities.outputExecutioner(command, website.externalApp).splitlines() counter = 0 for items in output: @@ -81,9 +86,12 @@ class FileManager: finalData = {} finalData['status'] = 1 - command = "sudo ls -la --group-directories-first " + self.returnPathEnclosed( + domainName = self.data['domainName'] + website = Websites.objects.get(domain=domainName) + + command = "ls -la --group-directories-first " + self.returnPathEnclosed( self.data['completeStartingPath']) - output = ProcessUtilities.outputExecutioner(command).splitlines() + output = ProcessUtilities.outputExecutioner(command, website.externalApp).splitlines() counter = 0 for items in output: @@ -119,12 +127,15 @@ class FileManager: finalData = {} finalData['status'] = 1 + domainName = self.data['domainName'] + website = Websites.objects.get(domain=domainName) + if self.data['fileName'].find('..') > -1: return self.ajaxPre(0, 'Not allowed to move in this path, please choose location inside home!') - command = "sudo touch " + self.returnPathEnclosed(self.data['fileName']) - ProcessUtilities.executioner(command) + command = "touch " + self.returnPathEnclosed(self.data['fileName']) + ProcessUtilities.executioner(command, website.externalApp) self.changeOwner(self.returnPathEnclosed(self.data['fileName'])) @@ -138,9 +149,11 @@ class FileManager: try: finalData = {} finalData['status'] = 1 + domainName = self.data['domainName'] + website = Websites.objects.get(domain=domainName) - command = "sudo mkdir " + self.returnPathEnclosed(self.data['folderName']) - ProcessUtilities.executioner(command) + command = "mkdir " + self.returnPathEnclosed(self.data['folderName']) + ProcessUtilities.executioner(command, website.externalApp) self.changeOwner(self.returnPathEnclosed(self.data['folderName'])) @@ -155,9 +168,12 @@ class FileManager: finalData = {} finalData['status'] = 1 + domainName = self.data['domainName'] + website = Websites.objects.get(domain=domainName) + for item in self.data['fileAndFolders']: - command = 'sudo rm -rf ' + self.returnPathEnclosed(self.data['path'] + '/' + item) - ProcessUtilities.executioner(command) + command = 'rm -rf ' + self.returnPathEnclosed(self.data['path'] + '/' + item) + ProcessUtilities.executioner(command, website.externalApp) json_data = json.dumps(finalData) return HttpResponse(json_data) @@ -171,15 +187,18 @@ class FileManager: finalData = {} finalData['status'] = 1 + domainName = self.data['domainName'] + website = Websites.objects.get(domain=domainName) + if not self.data['newPath'].find(self.data['home']) > -1: return self.ajaxPre(0, 'Not allowed to move in this path, please choose location inside home!') - command = 'sudo mkdir ' + self.returnPathEnclosed(self.data['newPath']) - ProcessUtilities.executioner(command) + command = 'mkdir ' + self.returnPathEnclosed(self.data['newPath']) + ProcessUtilities.executioner(command, website.externalApp) for item in self.data['fileAndFolders']: - command = 'sudo cp -R ' + self.returnPathEnclosed(self.data['basePath'] + '/' + item) + ' ' + self.returnPathEnclosed(self.data['newPath'] + '/' + item) - ProcessUtilities.executioner(command) + command = 'cp -R ' + self.returnPathEnclosed(self.data['basePath'] + '/' + item) + ' ' + self.returnPathEnclosed(self.data['newPath'] + '/' + item) + ProcessUtilities.executioner(command, website.externalApp) self.changeOwner(self.data['newPath']) @@ -194,16 +213,18 @@ class FileManager: finalData = {} finalData['status'] = 1 + domainName = self.data['domainName'] + website = Websites.objects.get(domain=domainName) if not self.data['newPath'].find(self.data['home']) > -1: return self.ajaxPre(0, 'Not allowed to move in this path, please choose location inside home!') - command = 'sudo mkdir ' + self.returnPathEnclosed(self.data['newPath']) - ProcessUtilities.executioner(command) + command = 'mkdir ' + self.returnPathEnclosed(self.data['newPath']) + ProcessUtilities.executioner(command, website.externalApp) for item in self.data['fileAndFolders']: - command = 'sudo mv ' + self.returnPathEnclosed(self.data['basePath'] + '/' + item) + ' ' + self.returnPathEnclosed(self.data['newPath'] + '/' + item) - ProcessUtilities.executioner(command) + command = 'mv ' + self.returnPathEnclosed(self.data['basePath'] + '/' + item) + ' ' + self.returnPathEnclosed(self.data['newPath'] + '/' + item) + ProcessUtilities.executioner(command, website.externalApp) self.changeOwner(self.data['newPath']) @@ -218,13 +239,15 @@ class FileManager: finalData = {} finalData['status'] = 1 + domainName = self.data['domainName'] + website = Websites.objects.get(domain=domainName) if self.data['newFileName'].find('..') > -1: return self.ajaxPre(0, 'Not allowed to move in this path, please choose location inside home!') - command = 'sudo mv ' + self.returnPathEnclosed(self.data['basePath'] + '/' + self.data['existingName']) + ' ' + self.returnPathEnclosed(self.data['basePath'] + '/' + self.data['newFileName']) - ProcessUtilities.executioner(command) + command = 'mv ' + self.returnPathEnclosed(self.data['basePath'] + '/' + self.data['existingName']) + ' ' + self.returnPathEnclosed(self.data['basePath'] + '/' + self.data['newFileName']) + ProcessUtilities.executioner(command, website.externalApp) self.changeOwner(self.data['basePath'] + '/' + self.data['newFileName']) @@ -239,9 +262,11 @@ class FileManager: finalData = {} finalData['status'] = 1 + domainName = self.data['domainName'] + website = Websites.objects.get(domain=domainName) - command = 'sudo cat ' + self.returnPathEnclosed(self.data['fileName']) - finalData['fileContents'] = ProcessUtilities.outputExecutioner(command) + command = 'cat ' + self.returnPathEnclosed(self.data['fileName']) + finalData['fileContents'] = ProcessUtilities.outputExecutioner(command, website.externalApp) json_data = json.dumps(finalData) return HttpResponse(json_data) @@ -255,13 +280,27 @@ class FileManager: finalData = {} finalData['status'] = 1 tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + self.data['home'] = '/home/%s' % (self.data['domainName']) + + domainName = self.data['domainName'] + website = Websites.objects.get(domain=domainName) writeToFile = open(tempPath, 'w') writeToFile.write(self.data['fileContent']) writeToFile.close() - command = 'sudo mv ' + tempPath + ' ' + self.returnPathEnclosed(self.data['fileName']) + if os.path.islink(self.data['fileName']): + return self.ajaxPre(0, 'File exists and is symlink.') + + if not self.data['fileName'].find(self.data['home']) > -1: + return self.ajaxPre(0, 'Not allowed to move in this path, please choose location inside home!') + + 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) + self.changeOwner(self.data['fileName']) json_data = json.dumps(finalData) @@ -282,7 +321,16 @@ class FileManager: filename = fs.save(myfile.name, myfile) finalData['fileName'] = fs.url(filename) - command = 'sudo mv ' + self.returnPathEnclosed('/home/cyberpanel/media/' + myfile.name) + ' ' + self.returnPathEnclosed(self.data['completePath'] + '/' + myfile.name) + if not self.data['completePath'].find(self.data['home']) > -1: + return self.ajaxPre(0, 'Not allowed to move in this path, please choose location inside home!') + + command = 'mv ' + self.returnPathEnclosed('/home/cyberpanel/media/' + myfile.name) + ' ' + self.returnPathEnclosed(self.data['completePath'] + '/' + myfile.name) + ProcessUtilities.executioner(command) + + domainName = self.data['domainName'] + website = Websites.objects.get(domain=domainName) + + command = 'chown %s:%s %s' % (website.externalApp, website.externalApp, self.data['completePath'] + '/' + myfile.name) ProcessUtilities.executioner(command) self.changeOwner(self.data['completePath'] + '/' + myfile.name) @@ -299,15 +347,18 @@ class FileManager: finalData = {} finalData['status'] = 1 + domainName = self.data['domainName'] + website = Websites.objects.get(domain=domainName) + if not self.data['extractionLocation'].find(self.data['home']) > -1: return self.ajaxPre(0, 'Not allowed to move in this path, please choose location inside home!') if self.data['extractionType'] == 'zip': - command = 'sudo unzip -o ' + self.returnPathEnclosed(self.data['fileToExtract']) + ' -d ' + self.returnPathEnclosed(self.data['extractionLocation']) + command = 'unzip -o ' + self.returnPathEnclosed(self.data['fileToExtract']) + ' -d ' + self.returnPathEnclosed(self.data['extractionLocation']) else: - command = 'sudo tar -xf ' + self.returnPathEnclosed(self.data['fileToExtract']) + ' -C ' + self.returnPathEnclosed(self.data['extractionLocation']) + command = 'tar -xf ' + self.returnPathEnclosed(self.data['fileToExtract']) + ' -C ' + self.returnPathEnclosed(self.data['extractionLocation']) - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, website.externalApp) self.changeOwner(self.data['extractionLocation']) @@ -322,21 +373,22 @@ class FileManager: finalData = {} finalData['status'] = 1 - + domainName = self.data['domainName'] + website = Websites.objects.get(domain=domainName) if self.data['compressionType'] == 'zip': compressedFileName = self.returnPathEnclosed(self.data['basePath'] + '/' + self.data['compressedFileName'] + '.zip') - command = 'sudo zip -r ' + compressedFileName + ' ' + command = 'zip -r ' + compressedFileName + ' ' else: compressedFileName = self.returnPathEnclosed( self.data['basePath'] + '/' + self.data['compressedFileName'] + '.tar.gz') - command = 'sudo tar -czvf ' + compressedFileName + ' ' + command = 'tar -czvf ' + compressedFileName + ' ' for item in self.data['listOfFiles']: command = command + self.returnPathEnclosed(self.data['basePath'] + '/' + item) + ' ' - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, website.externalApp) self.changeOwner(self.data['compressedFileName']) @@ -351,16 +403,18 @@ class FileManager: finalData = {} finalData['status'] = 1 + domainName = self.data['domainName'] + website = Websites.objects.get(domain=domainName) if self.data['recursive'] == 1: - command = 'sudo chmod -R ' + self.data['newPermissions'] + ' ' + self.returnPathEnclosed( + command = 'chmod -R ' + self.data['newPermissions'] + ' ' + self.returnPathEnclosed( self.data['basePath'] + '/' + self.data['permissionsPath']) else: - command = 'sudo chmod ' + self.data['newPermissions'] + ' ' + self.returnPathEnclosed( + command = 'chmod ' + self.data['newPermissions'] + ' ' + self.returnPathEnclosed( self.data['basePath'] + '/' + self.data['permissionsPath']) - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, website.externalApp) json_data = json.dumps(finalData) return HttpResponse(json_data) diff --git a/filemanager/static/filemanager/js/fileManager.js b/filemanager/static/filemanager/js/fileManager.js index a76ebcb04..e21eafd01 100755 --- a/filemanager/static/filemanager/js/fileManager.js +++ b/filemanager/static/filemanager/js/fileManager.js @@ -1,3 +1,20 @@ +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; +} + + var fileManager = angular.module('fileManager', ['angularFileUpload']); fileManager.config(['$interpolateProvider', function ($interpolateProvider) { @@ -5,6 +22,7 @@ fileManager.config(['$interpolateProvider', function ($interpolateProvider) { $interpolateProvider.endSymbol('$}'); }]); + fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, $window) { $(document.body).click(function () { @@ -58,8 +76,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (functionName === "primary") { nodeForChilds = element.currentTarget.parentNode; funcCompletePath = completePath; - } - else { + } else { nodeForChilds = element.parentNode; funcCompletePath = completePath; } @@ -74,7 +91,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -95,8 +119,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, for (var i = 0; i < keys.length; i++) { if (keys[i] === "error_message" | keys[i] === "status") { continue; - } - else { + } else { path = filesData[keys[i]][0]; completePath = filesData[keys[i]][1]; dropDown = filesData[keys[i]][2]; @@ -105,8 +128,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, } activateMinus(nodeForChilds, funcCompletePath); - } - else { + } else { } } @@ -185,8 +207,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, liNode.appendChild(secondANode); return liNode; - } - else { + } else { liNode.appendChild(iNodeFile); liNode.appendChild(pathNode); return liNode; @@ -430,8 +451,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var fileOrFolderNode = document.createTextNode("Folder"); fifthTDNode.appendChild(fileOrFolderNode) - } - else { + } else { thNode.appendChild(iNodeFile); trNode.appendChild(thNode); trNode.addEventListener("click", function () { @@ -475,40 +495,32 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (result[0] === "js") { aceEditorMode = "ace/mode/javascript"; editNotRight.style.display = "Block"; - } - else if (result[0] === "html") { + } else if (result[0] === "html") { aceEditorMode = "ace/mode/html"; editNotRight.style.display = "Block"; - } - else if (result[0] === "css") { + } else if (result[0] === "css") { aceEditorMode = "ace/mode/css"; editNotRight.style.display = "Block"; - } - else if (result[0] === "php") { + } else if (result[0] === "php") { aceEditorMode = "ace/mode/php"; editNotRight.style.display = "Block"; - } - else if (result[0] === "txt") { + } else if (result[0] === "txt") { aceEditorMode = ""; editNotRight.style.display = "Block"; - } - else if (result[0] === "htaccess") { + } else if (result[0] === "htaccess") { aceEditorMode = ""; editNotRight.style.display = "Block"; - } - else { + } else { var editNode = document.getElementById("editFile"); editNode.style.pointerEvents = "none"; editNotRight.style.display = "None"; } - } - else { + } else { var editNode = document.getElementById("editFile"); editNode.style.pointerEvents = "none"; editNotRight.style.display = "None"; } - } - else { + } else { var editNode = document.getElementById("editFile"); editNode.style.pointerEvents = "none"; } @@ -527,21 +539,18 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (result[0] === "gz") { extractFileNode.style.pointerEvents = "auto"; extractNodeRight.style.display = "Block"; - } - else if (result[0] === "zip") { + } else if (result[0] === "zip") { extractFileNode.style.pointerEvents = "auto"; extractNodeRight.style.display = "Block"; } else { extractFileNode.style.pointerEvents = "none"; extractNodeRight.style.display = "None"; } - } - else { + } else { extractFileNode.style.pointerEvents = "none"; extractNodeRight.style.display = "None"; } - } - else { + } else { var extractFileNode = document.getElementById("extractFile"); extractFileNode.style.pointerEvents = "none"; } @@ -553,8 +562,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var moveFileNode = document.getElementById("moveFile"); moveFileNode.style.pointerEvents = "auto"; - } - else { + } else { var moveFileNode = document.getElementById("moveFile"); moveFileNode.style.pointerEvents = "none"; } @@ -565,8 +573,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var copeFileNode = document.getElementById("copyFile"); copeFileNode.style.pointerEvents = "auto"; - } - else { + } else { var copeFileNode = document.getElementById("copyFile"); copeFileNode.style.pointerEvents = "none"; } @@ -578,8 +585,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var renameFileNode = document.getElementById("renameFile"); renameFileNode.style.pointerEvents = "auto"; - } - else { + } else { var renameFileNode = document.getElementById("renameFile"); renameFileNode.style.pointerEvents = "none"; } @@ -590,8 +596,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (allFilesAndFolders.length >= 1) { var compressFile = document.getElementById("compressFile"); compressFile.style.pointerEvents = "auto"; - } - else { + } else { var compressFile = document.getElementById("compressFile"); compressFile.style.pointerEvents = "none"; } @@ -603,8 +608,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var deleteFile = document.getElementById("deleteFile"); deleteFile.style.pointerEvents = "auto"; - } - else { + } else { var deleteFile = document.getElementById("deleteFile"); deleteFile.style.pointerEvents = "none"; } @@ -625,22 +629,17 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (functionName === "startPoint") { completePathToFile = $scope.currentPath; - } - else if (functionName === "doubleClick") { + } else if (functionName === "doubleClick") { completePathToFile = $scope.currentPath + "/" + node.innerHTML; - } - else if (functionName === "homeFetch") { + } else if (functionName === "homeFetch") { completePathToFile = homePathBack; - } - else if (functionName === "goBackOnPath") { + } else if (functionName === "goBackOnPath") { var pos = $scope.currentPath.lastIndexOf("/"); completePathToFile = $scope.currentPath.slice(0, pos); - } - else if (functionName === "refresh") { + } else if (functionName === "refresh") { completePathToFile = $scope.currentPath; var rightClickNode = document.getElementById("rightClick"); - } - else if (functionName === "fromTree") { + } else if (functionName === "fromTree") { completePathToFile = arguments[2]; } @@ -659,7 +658,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, tableBody.innerHTML = ''; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -678,8 +684,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, for (var i = 0; i < keys.length; i++) { if (keys[i] === "error_message" | keys[i] === "status") { continue; - } - else { + } else { var fileName = filesData[keys[i]][0]; var lastModified = filesData[keys[i]][2]; var fileSize = filesData[keys[i]][3]; @@ -694,8 +699,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, } } - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 10, function () { }); $scope.fetchForTableSecondary(null, 'homeFetch'); @@ -711,6 +715,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, function findFileExtension(fileName) { return (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName) : undefined; } + $scope.fetchForTableSecondary(null, "startPoint"); // html editor @@ -727,8 +732,15 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, domainName: domainName }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -741,8 +753,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, editor.getSession().setMode(aceEditorMode); editor.setValue(response.data.fileContents); - } - else { + } else { $scope.errorMessageEditor = false; $scope.error_message = response.data.error_message; } @@ -771,7 +782,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -780,8 +798,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (response.data.status === 1) { $scope.htmlEditorLoading = true; $scope.saveSuccess = false; - } - else { + } else { $scope.errorMessageEditor = false; $scope.error_message = response.data.error_message; } @@ -800,6 +817,9 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var uploader = $scope.uploader = new FileUploader({ url: "/filemanager/upload", + headers: { + 'X-CSRFToken': getCookie('csrftoken') // X-CSRF-TOKEN is used for Ruby on Rails Tokens + }, formData: [{ "method": "upload", "home": homePathBack @@ -810,8 +830,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (response.uploadStatus === 1) { $scope.errorMessage = true; $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { $scope.errorMessage = false; $scope.fileName = response.fileName; $scope.error_message = response.error_message; @@ -863,7 +882,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; var url = '/filemanager/controller'; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -871,8 +897,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, $scope.createSuccess = false; $scope.fetchForTableSecondary(null, 'refresh'); $('#showCreateFolder').modal('hide'); - } - else { + } else { $scope.errorMessageFolder = false; $scope.error_message = response.data.error_message; } @@ -915,7 +940,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -923,8 +955,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, $scope.createSuccess = false; $scope.fetchForTableSecondary(null, 'refresh'); $('#showCreateFile').modal('hide'); - } - else { + } else { $scope.errorMessageFile = false; $scope.error_message = response.data.error_message; } @@ -960,7 +991,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { $scope.deleteLoading = true; @@ -969,8 +1007,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var notification = alertify.notify('Successfully Deleted!', 'success', 5, function () { }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify('Files/Folders can not be deleted', 'error', 5, function () { console.log('dismissed'); }); @@ -1015,7 +1052,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -1025,8 +1069,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var notification = alertify.notify('Successfully Compressed!', 'success', 5, function () { }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 5, function () { }); } @@ -1058,8 +1101,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (findFileExtension(completeFileToExtract) == "gz") { extractionType = "tar.gz"; - } - else { + } else { extractionType = "zip"; } @@ -1075,7 +1117,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -1087,8 +1136,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, console.log('dismissed'); }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 10, function () { console.log('dismissed'); }); @@ -1134,7 +1182,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -1145,8 +1200,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var notification = alertify.notify('Successfully Moved!', 'success', 5, function () { }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 5, function () { }); } @@ -1190,7 +1244,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { $scope.copyLoading = true; @@ -1201,8 +1262,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var notification = alertify.notify('Successfully Copied!', 'success', 5, function () { }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 5, function () { }); } @@ -1311,7 +1371,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -1323,8 +1390,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var notification = alertify.notify('Successfully Renamed!', 'success', 5, function () { }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 5, function () { }); } @@ -1351,7 +1417,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -1361,8 +1434,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, console.log('dismissed'); }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 5, function () { console.log('dismissed'); }); @@ -1410,8 +1482,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if ($scope.userRead === true) { $scope.userPermissions = $scope.userPermissions + 4; - } - else { + } else { if ($scope.userRead !== undefined) { $scope.userPermissions = $scope.userPermissions - 4; } @@ -1450,8 +1521,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if ($scope.userWrite === true) { $scope.userPermissions = $scope.userPermissions + 2; - } - else { + } else { if ($scope.userWrite !== undefined) { $scope.userPermissions = $scope.userPermissions - 2; } @@ -1490,8 +1560,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if ($scope.userExecute === true) { $scope.userPermissions = $scope.userPermissions + 1; - } - else { + } else { if ($scope.userExecute !== undefined) { $scope.userPermissions = $scope.userPermissions - 1; } @@ -1544,7 +1613,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -1555,8 +1631,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var notification = alertify.notify('Permissions Successfully Changed!', 'success', 5, function () { }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 5, function () { }); } diff --git a/firewall/templates/firewall/firewall.html b/firewall/templates/firewall/firewall.html index 038001aab..e8e7fd15c 100755 --- a/firewall/templates/firewall/firewall.html +++ b/firewall/templates/firewall/firewall.html @@ -3,176 +3,177 @@ {% block title %}{% trans "Firewall - CyberPanel" %}{% endblock %} {% block content %} -{% load static %} -{% get_current_language as LANGUAGE_CODE %} - + {% load static %} + {% get_current_language as LANGUAGE_CODE %} + -
    -
    -

    {% trans "Add/Delete Firewall Rules" %}

    -

    {% trans "On this page you can add/delete firewall rules. (By default all ports are blocked, except mentioned below)" %}

    -
    -
    -
    -

    - {% trans "Add/Delete Rules" %} -

    -
    +
    +
    +

    {% trans "Add/Delete Firewall Rules" %}

    +

    {% trans "On this page you can add/delete firewall rules. (By default all ports are blocked, except mentioned below)" %}

    +
    +
    +
    +

    + {% trans "Add/Delete Rules" %} +

    +
    -
    + -
    - -
    -
    +
    + +
    +
    -
    +
    - + {% trans "Status" %} {$ status $} - + - + - - - + + + - - + + - + - - + + -
    -

    {% trans "Action failed. Error message:" %} {$ errorMessage $}

    +
    +

    {% trans "Action failed. Error message:" %} {$ errorMessage $}

    +
    + +
    +

    {% trans "Action successful." %}

    +
    + + +
    + +
    +
    -
    -

    {% trans "Action successful." %}

    +
    + +
    + +
    + +
    + +
    + + +
    + +
    + + + + + +
    + +
    + + + + +
    + +
    +
    -
    + -
    -
    -
    +
    -
    +
    -
    - -
    - -
    - -
    - - -
    - -
    - - - - - -
    - -
    - - - - -
    - -
    - -
    - - - - - - - -
    - -
    - - - - - - - - - - - - - - - - - - - - - - -
    {% trans "ID" %}{% trans "Name" %}{% trans "Protocol" %}{% trans "IP Address" %}{% trans "Port" %}{% trans "Delete" %}
    X
    -
    -
    - - - - -
    - - - -
    -
    -

    {% trans "Error message:" %} {$ errorMessage $}

    + + + + + + + + + + + + + + + + + + + + + +
    {% trans "ID" %}{% trans "Name" %}{% trans "Protocol" %}{% trans "IP Address" %}{% trans "Port" %}{% trans "Delete" %}
    +
    X
    +
    +
    + + +
    + + + +
    +
    +

    {% trans "Error message:" %} {$ errorMessage $}

    +
    + + +
    +

    {% trans "Rule successfully added." %}

    +
    + +
    +

    {% trans "Could Not Connect to server. Please refresh this page" %}

    +
    -
    -

    {% trans "Rule successfully added." %}

    +
    + + + -
    -

    {% trans "Could Not Connect to server. Please refresh this page" %}

    -
    -
    - - - - - - - +
    + +
    -
    - - -
    {% endblock %} diff --git a/ftp/ftpManager.py b/ftp/ftpManager.py index b5504ad56..28e0ab6b8 100755 --- a/ftp/ftpManager.py +++ b/ftp/ftpManager.py @@ -61,10 +61,17 @@ class FTPManager: data = json.loads(self.request.body) userName = data['ftpUserName'] - password = data['ftpPassword'] + password = data['passwordByPass'] domainName = data['ftpDomain'] + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + try: api = data['api'] except: @@ -81,18 +88,15 @@ class FTPManager: except: path = 'None' - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/ftpUtilities.py" - execPath = execPath + " submitFTPCreation --domainName " + domainName + " --userName " + userName \ - + " --password '" + password + "' --path " + path + " --owner " + admin.userName + ' --api ' + api - output = ProcessUtilities.outputExecutioner(execPath) + result = FTPUtilities.submitFTPCreation(domainName, userName, password, path, admin.userName, api) - if output.find("1,None") > -1: + if result[0] == 1: data_ret = {'status': 1, 'creatFTPStatus': 1, 'error_message': 'None'} json_data = json.dumps(data_ret) return HttpResponse(json_data) else: - data_ret = {'status': 0, 'creatFTPStatus': 0, 'error_message': output} + data_ret = {'status': 0, 'creatFTPStatus': 0, 'error_message': result[1]} json_data = json.dumps(data_ret) return HttpResponse(json_data) @@ -131,6 +135,12 @@ class FTPManager: data = json.loads(self.request.body) domain = data['ftpDomain'] + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + website = Websites.objects.get(domain=domain) ftpAccounts = website.users_set.all() @@ -167,6 +177,12 @@ class FTPManager: data = json.loads(self.request.body) ftpUserName = data['ftpUsername'] + admin = Administrator.objects.get(pk=userID) + ftp = Users.objects.get(user=ftpUserName) + + if ftp.domain.admin != admin: + return ACLManager.loadErrorJson() + FTPUtilities.submitFTPDeletion(ftpUserName) final_json = json.dumps({'status': 1, 'deleteStatus': 1, 'error_message': "None"}) @@ -208,6 +224,12 @@ class FTPManager: domain = Websites.objects.get(domain=selectedDomain) + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(selectedDomain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + records = Users.objects.filter(domain=domain) json_data = "[" @@ -247,6 +269,14 @@ class FTPManager: userName = data['ftpUserName'] password = data['ftpPassword'] + admin = Administrator.objects.get(pk=userID) + ftp = Users.objects.get(user=userName) + + if currentACL['admin'] == 1: + pass + elif ftp.domain.admin != admin: + return ACLManager.loadErrorJson() + FTPUtilities.changeFTPPassword(userName, password) data_ret = {'status': 1, 'changePasswordStatus': 1, 'error_message': "None"} diff --git a/ftp/static/ftp/ftp.js b/ftp/static/ftp/ftp.js index 88a7c3806..8e2d41bdf 100755 --- a/ftp/static/ftp/ftp.js +++ b/ftp/static/ftp/ftp.js @@ -4,7 +4,7 @@ /* Java script code to create account */ -app.controller('createFTPAccount', function($scope,$http) { +app.controller('createFTPAccount', function ($scope, $http) { $scope.ftpLoading = true; $scope.ftpDetails = true; @@ -12,7 +12,7 @@ app.controller('createFTPAccount', function($scope,$http) { $scope.successfullyCreated = true; $scope.couldNotConnect = true; - $scope.showFTPDetails = function(){ + $scope.showFTPDetails = function () { $scope.ftpLoading = true; $scope.ftpDetails = false; @@ -23,91 +23,84 @@ app.controller('createFTPAccount', function($scope,$http) { }; - $scope.createFTPAccount = function(){ + $scope.createFTPAccount = function () { - $scope.ftpLoading = false; + $scope.ftpLoading = false; + $scope.ftpDetails = false; + $scope.canNotCreate = true; + $scope.successfullyCreated = true; + $scope.couldNotConnect = true; + + var ftpDomain = $scope.ftpDomain; + var ftpUserName = $scope.ftpUserName; + var ftpPassword = $scope.ftpPassword; + var path = $scope.ftpPath; + + if (typeof path === 'undefined') { + path = ""; + } + + var url = "/ftp/submitFTPCreation"; + + + var data = { + ftpDomain: ftpDomain, + ftpUserName: ftpUserName, + passwordByPass: ftpPassword, + path: path, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.creatFTPStatus == 1) { + + $scope.ftpLoading = true; $scope.ftpDetails = false; $scope.canNotCreate = true; + $scope.successfullyCreated = false; + $scope.couldNotConnect = true; + + + } else { + $scope.ftpLoading = true; + $scope.ftpDetails = false; + $scope.canNotCreate = false; $scope.successfullyCreated = true; $scope.couldNotConnect = true; - var ftpDomain = $scope.ftpDomain; - var ftpUserName = $scope.ftpUserName; - var ftpPassword = $scope.ftpPassword; - var path = $scope.ftpPath; - - if (typeof path === 'undefined'){ - path = ""; - } - - var url = "/ftp/submitFTPCreation"; + $scope.errorMessage = response.data.error_message; - var data = { - ftpDomain:ftpDomain, - ftpUserName:ftpUserName, - ftpPassword:ftpPassword, - path:path, - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + } - function ListInitialDatas(response) { - - - if(response.data.creatFTPStatus == 1){ - - $scope.ftpLoading = true; - $scope.ftpDetails = false; - $scope.canNotCreate = true; - $scope.successfullyCreated = false; - $scope.couldNotConnect = true; - - - } - - else - { - $scope.ftpLoading = true; - $scope.ftpDetails = false; - $scope.canNotCreate = false; - $scope.successfullyCreated = true; - $scope.couldNotConnect = true; - - $scope.errorMessage = response.data.error_message; - - - } - - - - } - function cantLoadInitialDatas(response) { - - $scope.ftpLoading = true; - $scope.ftpDetails = false; - $scope.canNotCreate = true; - $scope.successfullyCreated = true; - $scope.couldNotConnect = false; - - - - } - + } + + function cantLoadInitialDatas(response) { + + $scope.ftpLoading = true; + $scope.ftpDetails = false; + $scope.canNotCreate = true; + $scope.successfullyCreated = true; + $scope.couldNotConnect = false; + } }; - $scope.hideFewDetails = function(){ + $scope.hideFewDetails = function () { $scope.successfullyCreated = true; @@ -119,8 +112,8 @@ app.controller('createFTPAccount', function($scope,$http) { $scope.generatedPasswordView = true; $scope.generatePassword = function () { - $scope.generatedPasswordView = false; - $scope.ftpPassword = randomPassword(12); + $scope.generatedPasswordView = false; + $scope.ftpPassword = randomPassword(12); }; $scope.usePassword = function () { @@ -134,7 +127,7 @@ app.controller('createFTPAccount', function($scope,$http) { /* Java script code to delete ftp account */ -app.controller('deleteFTPAccount', function($scope,$http) { +app.controller('deleteFTPAccount', function ($scope, $http) { $scope.ftpAccountsOfDomain = true; $scope.deleteFTPButton = true; @@ -143,7 +136,7 @@ app.controller('deleteFTPAccount', function($scope,$http) { $scope.couldNotConnect = true; $scope.deleteFTPButtonInit = true; - $scope.getFTPAccounts = function(){ + $scope.getFTPAccounts = function () { $scope.ftpAccountsOfDomain = true; $scope.deleteFTPButton = true; @@ -156,152 +149,138 @@ app.controller('deleteFTPAccount', function($scope,$http) { var url = "/ftp/fetchFTPAccounts"; - var data = { - ftpDomain:$scope.selectedDomain, - }; + var data = { + ftpDomain: $scope.selectedDomain, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus == 1){ + if (response.data.fetchStatus == 1) { - $scope.ftpAccountsFeteched = JSON.parse(response.data.data); - - $scope.ftpAccountsOfDomain = false; - $scope.deleteFTPButton = true; - $scope.deleteFailure = true; - $scope.deleteSuccess = true; - $scope.couldNotConnect = true; - $scope.deleteFTPButtonInit = false; - - - } - - else - { - - $scope.ftpAccountsOfDomain = true; - $scope.deleteFTPButton = true; - $scope.deleteFailure = true; - $scope.deleteSuccess = true; - $scope.couldNotConnect = false; - $scope.deleteFTPButtonInit = true; - - } - - - - } - function cantLoadInitialDatas(response) { - - $scope.ftpAccountsOfDomain = true; - $scope.deleteFTPButton = true; - $scope.deleteFailure = true; - $scope.deleteSuccess = true; - $scope.couldNotConnect = false; - $scope.deleteFTPButtonInit = true; - - - } - - - - - - }; - - $scope.deleteFTPAccount = function(){ + $scope.ftpAccountsFeteched = JSON.parse(response.data.data); $scope.ftpAccountsOfDomain = false; - $scope.deleteFTPButton = false; + $scope.deleteFTPButton = true; $scope.deleteFailure = true; $scope.deleteSuccess = true; $scope.couldNotConnect = true; $scope.deleteFTPButtonInit = false; + + } else { + + $scope.ftpAccountsOfDomain = true; + $scope.deleteFTPButton = true; + $scope.deleteFailure = true; + $scope.deleteSuccess = true; + $scope.couldNotConnect = false; + $scope.deleteFTPButtonInit = true; + + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.ftpAccountsOfDomain = true; + $scope.deleteFTPButton = true; + $scope.deleteFailure = true; + $scope.deleteSuccess = true; + $scope.couldNotConnect = false; + $scope.deleteFTPButtonInit = true; + + + } + + + }; + + $scope.deleteFTPAccount = function () { + + $scope.ftpAccountsOfDomain = false; + $scope.deleteFTPButton = false; + $scope.deleteFailure = true; + $scope.deleteSuccess = true; + $scope.couldNotConnect = true; + $scope.deleteFTPButtonInit = false; + }; - - $scope.deleteFTPFinal = function(){ - + $scope.deleteFTPFinal = function () { var url = "/ftp/submitFTPDelete"; - var data = { - ftpUsername:$scope.selectedFTPAccount, - }; + var data = { + ftpUsername: $scope.selectedFTPAccount, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.deleteStatus == 1){ + if (response.data.deleteStatus == 1) { - $scope.ftpAccountsOfDomain = true; - $scope.deleteFTPButton = true; - $scope.deleteFailure = true; - $scope.deleteSuccess = false; - $scope.couldNotConnect = true; - $scope.deleteFTPButtonInit = true; + $scope.ftpAccountsOfDomain = true; + $scope.deleteFTPButton = true; + $scope.deleteFailure = true; + $scope.deleteSuccess = false; + $scope.couldNotConnect = true; + $scope.deleteFTPButtonInit = true; - $scope.ftpUserNameDeleted = $scope.selectedFTPAccount; + $scope.ftpUserNameDeleted = $scope.selectedFTPAccount; - } + } else { - else - { + $scope.ftpAccountsOfDomain = true; + $scope.deleteFTPButton = true; + $scope.deleteFailure = false; + $scope.deleteSuccess = true; + $scope.couldNotConnect = true; + $scope.deleteFTPButtonInit = false; - $scope.ftpAccountsOfDomain = true; - $scope.deleteFTPButton = true; - $scope.deleteFailure = false; - $scope.deleteSuccess = true; - $scope.couldNotConnect = true; - $scope.deleteFTPButtonInit = false; + $scope.errorMessage = response.data.error_message; - $scope.errorMessage = response.data.error_message; - - } + } + } - } - function cantLoadInitialDatas(response) { - - $scope.ftpAccountsOfDomain = true; - $scope.deleteFTPButton = true; - $scope.deleteFailure = false; - $scope.deleteSuccess = true; - $scope.couldNotConnect = false; - $scope.deleteFTPButtonInit = true; - - - } + function cantLoadInitialDatas(response) { + $scope.ftpAccountsOfDomain = true; + $scope.deleteFTPButton = true; + $scope.deleteFailure = false; + $scope.deleteSuccess = true; + $scope.couldNotConnect = false; + $scope.deleteFTPButtonInit = true; + } }; @@ -310,7 +289,7 @@ app.controller('deleteFTPAccount', function($scope,$http) { /* Java script code to delete ftp account ends here */ -app.controller('listFTPAccounts', function($scope,$http) { +app.controller('listFTPAccounts', function ($scope, $http) { $scope.recordsFetched = true; $scope.passwordChanged = true; @@ -324,157 +303,155 @@ app.controller('listFTPAccounts', function($scope,$http) { var globalFTPUsername = ""; $scope.fetchFTPAccounts = function () { - populateCurrentRecords(); + populateCurrentRecords(); }; $scope.changePassword = function (ftpUsername) { - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.ftpLoading = true; - $scope.changePasswordBox = false; - $scope.notificationsBox = true; - $scope.ftpUsername = ftpUsername; - globalFTPUsername = ftpUsername; + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.ftpLoading = true; + $scope.changePasswordBox = false; + $scope.notificationsBox = true; + $scope.ftpUsername = ftpUsername; + globalFTPUsername = ftpUsername; }; $scope.changePasswordBtn = function () { - $scope.ftpLoading = false; + $scope.ftpLoading = false; - url = "/ftp/changePassword"; + url = "/ftp/changePassword"; - var data = { - ftpUserName:globalFTPUsername, - ftpPassword: $scope.ftpPassword, - }; + var data = { + ftpUserName: globalFTPUsername, + ftpPassword: $scope.ftpPassword, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.changePasswordStatus == 1){ - $scope.notificationsBox = false; - $scope.passwordChanged = false; - $scope.ftpLoading = true; - $scope.domainFeteched = $scope.selectedDomain; + if (response.data.changePasswordStatus == 1) { + $scope.notificationsBox = false; + $scope.passwordChanged = false; + $scope.ftpLoading = true; + $scope.domainFeteched = $scope.selectedDomain; - } - else{ - $scope.notificationsBox = false; - $scope.canNotChangePassword = false; - $scope.ftpLoading = true; - $scope.canNotChangePassword = false; - $scope.errorMessage = response.data.error_message; - } + } else { + $scope.notificationsBox = false; + $scope.canNotChangePassword = false; + $scope.ftpLoading = true; + $scope.canNotChangePassword = false; + $scope.errorMessage = response.data.error_message; + } - } - function cantLoadInitialDatas(response) { - $scope.notificationsBox = false; - $scope.couldNotConnect = false; - $scope.ftpLoading = true; + } - } + function cantLoadInitialDatas(response) { + $scope.notificationsBox = false; + $scope.couldNotConnect = false; + $scope.ftpLoading = true; - }; + } - function populateCurrentRecords(){ - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.ftpLoading = false; - $scope.ftpAccounts = true; - $scope.changePasswordBox = true; + }; - var selectedDomain = $scope.selectedDomain; + function populateCurrentRecords() { + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.ftpLoading = false; + $scope.ftpAccounts = true; + $scope.changePasswordBox = true; - url = "/ftp/getAllFTPAccounts"; + var selectedDomain = $scope.selectedDomain; - var data = { - selectedDomain:selectedDomain, - }; + url = "/ftp/getAllFTPAccounts"; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var data = { + selectedDomain: selectedDomain, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus == 1){ + if (response.data.fetchStatus == 1) { - $scope.records = JSON.parse(response.data.data); + $scope.records = JSON.parse(response.data.data); - $scope.notificationsBox = false; - $scope.recordsFetched = false; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.ftpLoading = true; - $scope.ftpAccounts = false; - $scope.changePasswordBox = true; + $scope.notificationsBox = false; + $scope.recordsFetched = false; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.ftpLoading = true; + $scope.ftpAccounts = false; + $scope.changePasswordBox = true; - $scope.domainFeteched = $scope.selectedDomain; + $scope.domainFeteched = $scope.selectedDomain; - } - else{ - $scope.notificationsBox = false; - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.ftpLoading = true; - $scope.ftpAccounts = true; - $scope.changePasswordBox = true; + } else { + $scope.notificationsBox = false; + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.ftpLoading = true; + $scope.ftpAccounts = true; + $scope.changePasswordBox = true; - $scope.errorMessage = response.data.error_message; - } + $scope.errorMessage = response.data.error_message; + } - } - function cantLoadInitialDatas(response) { - $scope.notificationsBox = false; - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = false; - $scope.ftpLoading = true; - $scope.ftpAccounts = true; - $scope.changePasswordBox = true; + } + + function cantLoadInitialDatas(response) { + $scope.notificationsBox = false; + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = false; + $scope.ftpLoading = true; + $scope.ftpAccounts = true; + $scope.changePasswordBox = true; - } + } - } + } //// $scope.generatedPasswordView = true; $scope.generatePassword = function () { - $scope.generatedPasswordView = false; - $scope.ftpPassword = randomPassword(12); + $scope.generatedPasswordView = false; + $scope.ftpPassword = randomPassword(12); }; $scope.usePassword = function () { diff --git a/install/install.py b/install/install.py index 7251a025d..f44a3a714 100755 --- a/install/install.py +++ b/install/install.py @@ -13,6 +13,44 @@ import socket from os.path import * from stat import * import stat +from os import urandom +from random import choice + +char_set = {'small': 'abcdefghijklmnopqrstuvwxyz', + 'nums': '0123456789', + 'big': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + } + + +def generate_pass(length=14): + """Function to generate a password""" + + password = [] + + while len(password) < length: + key = choice(char_set.keys()) + a_char = urandom(1) + if a_char in char_set[key]: + if check_prev_char(password, char_set[key]): + continue + else: + password.append(a_char) + return ''.join(password) + +def check_prev_char(password, current_char_set): + """Function to ensure that there are no consecutive + UPPERCASE/lowercase/numbers/special-characters.""" + + index = len(password) + if index == 0: + return False + else: + prev_char = password[index - 1] + if prev_char in current_char_set: + return True + else: + return False + # There can not be peace without first a great suffering. @@ -914,7 +952,7 @@ class preFlightsChecks: os.chdir(self.path) - command = "wget http://cyberpanel.sh/CyberPanel.1.8.5.tar.gz" + command = "wget http://cyberpanel.sh/CyberPanel.1.8.7.tar.gz" #command = "wget http://cyberpanel.sh/CyberPanelTemp.tar.gz" preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', 'CyberPanel Download', @@ -923,7 +961,7 @@ class preFlightsChecks: ## count = 0 - command = "tar zxf CyberPanel.1.8.5.tar.gz" + command = "tar zxf CyberPanel.1.8.7.tar.gz" #command = "tar zxf CyberPanelTemp.tar.gz" preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', 'Extract CyberPanel',1, 1, os.EX_OSERR) @@ -949,6 +987,10 @@ class preFlightsChecks: counter = 0 for items in data: + if items.find('SECRET_KEY') > -1: + SK = "SECRET_KEY = '%s'\n" % (generate_pass(50)) + writeDataToFile.writelines(SK) + continue if mysql == 'Two': if items.find("'PASSWORD':") > -1: if counter == 0: @@ -974,6 +1016,8 @@ class preFlightsChecks: else: writeDataToFile.writelines(items) + + if self.distro == ubuntu: os.fchmod(writeDataToFile.fileno(), stat.S_IRUSR | stat.S_IWUSR) @@ -1097,6 +1141,51 @@ class preFlightsChecks: preFlightsChecks.call(command, self.distro, '[fixCyberPanelPermissions]', 'Change permissions for client.', 1, 0, os.EX_OSERR) + files = ['/etc/yum.repos.d/MariaDB.repo', '/etc/pdns/pdns.conf', '/etc/systemd/system/lscpd.service', + '/etc/pure-ftpd/pure-ftpd.conf', '/etc/pure-ftpd/pureftpd-pgsql.conf', '/etc/pure-ftpd/pureftpd-mysql.conf', '/etc/pure-ftpd/pureftpd-ldap.conf', + '/etc/dovecot/dovecot.conf', '/usr/local/lsws/conf/httpd_config.xml', '/usr/local/lsws/conf/modsec.conf', '/usr/local/lsws/conf/httpd.conf'] + + for items in files: + command = 'chmod 644 %s' % (items) + preFlightsChecks.call(command, self.distro, '[fixCyberPanelPermissions]', + 'Change permissions for client.', 1, 0, os.EX_OSERR) + + impFile = ['/etc/pure-ftpd/pure-ftpd.conf', '/etc/pure-ftpd/pureftpd-pgsql.conf', '/etc/pure-ftpd/pureftpd-mysql.conf', '/etc/pure-ftpd/pureftpd-ldap.conf', + '/etc/dovecot/dovecot.conf', '/etc/pdns/pdns.conf'] + + for items in impFile: + command = 'chmod 600 %s' % (items) + preFlightsChecks.call(command, self.distro, '[fixCyberPanelPermissions]', + 'Change permissions for client.', 1, 0, os.EX_OSERR) + + + command = 'chmod 640 /etc/postfix/*.cf' + subprocess.call(command, shell=True) + + command = 'chmod 644 /etc/postfix/main.cf' + subprocess.call(command, shell=True) + + command = 'chmod 640 /etc/dovecot/*.conf' + subprocess.call(command, shell=True) + + command = 'chmod 644 /etc/dovecot/dovecot.conf' + subprocess.call(command, shell=True) + + command = 'chmod 640 /etc/dovecot/dovecot-sql.conf.ext' + subprocess.call(command, shell=True) + + fileM = ['/usr/local/lsws/FileManager/', '/usr/local/CyberCP/install/FileManager', + '/usr/local/CyberCP/serverStatus/litespeed/FileManager', '/usr/local/lsws/Example/html/FileManager'] + + for items in fileM: + try: + shutil.rmtree(items) + except: + pass + + command = 'chmod 755 /etc/pure-ftpd/' + subprocess.call(command, shell=True) + def install_unzip(self): self.stdOut("Install unzip") try: @@ -2248,7 +2337,9 @@ enabled=1""" 'rainlooop data folder', 1, 0, os.EX_OSERR) - path = "/usr/local/CyberCP/public/rainloop/rainloop/v/1.12.1/include.php" + iPath = os.listdir('/usr/local/CyberCP/public/rainloop/rainloop/v/') + + path = "/usr/local/CyberCP/public/rainloop/rainloop/v/%s/include.php" % (iPath[0]) data = open(path, 'r').readlines() writeToFile = open(path, 'w') @@ -3071,6 +3162,24 @@ enabled=1""" res = subprocess.call(shlex.split(command)) + if preFlightsChecks.resFailed(self.distro, res): + count = count + 1 + preFlightsChecks.stdOut( + "Trying to install tldextract, trying again, try number: " + str(count)) + if count == 3: + logging.InstallLog.writeToFile( + "Failed to install tldextract! [installTLDExtract]") + else: + logging.InstallLog.writeToFile("tldextract successfully installed! [pip]") + preFlightsChecks.stdOut("tldextract successfully installed! [pip]") + break + + count = 0 + while (1): + command = "pip install bcrypt" + + res = subprocess.call(shlex.split(command)) + if preFlightsChecks.resFailed(self.distro, res): count = count + 1 preFlightsChecks.stdOut( @@ -3658,18 +3767,23 @@ def main(): checks.test_Requests() checks.installPYDNS() checks.installDockerPY() + checks.installTLDExtract() checks.download_install_CyberPanel(installCyberPanel.InstallCyberPanel.mysqlPassword, mysql) checks.downoad_and_install_raindloop() checks.download_install_phpmyadmin() checks.setupCLI() checks.setup_cron() - checks.installTLDExtract() # checks.installdnsPython() ## Install and Configure OpenDKIM. - checks.installOpenDKIM() - checks.configureOpenDKIM() + if args.postfix == None: + checks.installOpenDKIM() + checks.configureOpenDKIM() + else: + if args.postfix == 'On': + checks.installOpenDKIM() + checks.configureOpenDKIM() checks.modSecPreReqs() checks.setupVirtualEnv(distro) diff --git a/install/installCyberPanel.py b/install/installCyberPanel.py index 59ddffae5..432e1152d 100755 --- a/install/installCyberPanel.py +++ b/install/installCyberPanel.py @@ -697,11 +697,25 @@ def Main(cwd, mysql, distro, ent, serial = None, port = "8090", ftp = None, dns if os.access(file_name, os.F_OK): password = open(file_name, 'r') InstallCyberPanel.mysql_Root_password = password.readline() + password.close() else: password = open(file_name, "w") password.writelines(InstallCyberPanel.mysql_Root_password) + command = 'chmod 640 %s' % (file_name) + password.close() + try: + install.preFlightsChecks.call(command, distro, '[chmod]', + '', + 1, 0, os.EX_OSERR) + command = 'chown root:cyberpanel %s' % (file_name) + install.preFlightsChecks.call(command, distro, '[chmod]', + '', + 1, 0, os.EX_OSERR) + except: + pass + + - password.close() if distro == centos: InstallCyberPanel.mysqlPassword = randomPassword.generate_pass() diff --git a/install/lscp.tar.gz b/install/lscp.tar.gz index 13ae87653..77da6f1ed 100755 Binary files a/install/lscp.tar.gz and b/install/lscp.tar.gz differ diff --git a/loginSystem/views.py b/loginSystem/views.py index 51db2fe15..36d8ea48c 100755 --- a/loginSystem/views.py +++ b/loginSystem/views.py @@ -14,6 +14,7 @@ from django.utils.translation import LANGUAGE_SESSION_KEY import CyberCP.settings as settings from models import ACL from plogical.acl import ACLManager +from django.views.decorators.csrf import ensure_csrf_cookie # Create your views here. def verifyLogin(request): @@ -115,6 +116,8 @@ def verifyLogin(request): if hashPassword.check_password(admin.password, password): request.session['userID'] = admin.pk + request.session['ipAddr'] = request.META.get('REMOTE_ADDR') + request.session.set_expiry(3600) data = {'userID': admin.pk, 'loginStatus': 1, 'error_message': "None"} json_data = json.dumps(data) return HttpResponse(json_data) @@ -129,6 +132,7 @@ def verifyLogin(request): json_data = json.dumps(data) return HttpResponse(json_data) +@ensure_csrf_cookie def loadLoginPage(request): try: userID = request.session['userID'] @@ -202,7 +206,7 @@ def loadLoginPage(request): firstName="Cyber",lastName="Panel", acl=acl, token=token) admin.save() - vers = version(currentVersion="1.8", build=5) + vers = version(currentVersion="1.8", build=7) vers.save() package = Package(admin=admin, packageName="Default", diskSpace=1000, @@ -213,6 +217,7 @@ def loadLoginPage(request): else: return render(request, 'loginSystem/login.html', {}) +@ensure_csrf_cookie def logout(request): try: del request.session['userID'] diff --git a/mailServer/mailserverManager.py b/mailServer/mailserverManager.py index b5ab0a740..8fc3400aa 100755 --- a/mailServer/mailserverManager.py +++ b/mailServer/mailserverManager.py @@ -24,6 +24,7 @@ import os from plogical.dnsUtilities import DNS from loginSystem.models import Administrator from plogical.processUtilities import ProcessUtilities +import bcrypt class MailServerManager: @@ -69,24 +70,25 @@ class MailServerManager: data = json.loads(self.request.body) domainName = data['domain'] userName = data['username'] - password = data['password'] + password = data['passwordByPass'] + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() ## Create email entry - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/mailUtilities.py" + result = mailUtilities.createEmailAccount(domainName, userName, password) - execPath = execPath + " createEmailAccount --domain " + domainName + " --userName " \ - + userName + " --password '" + password + "'" - - output = ProcessUtilities.outputExecutioner(execPath) - - if output.find("1,None") > -1: + if result[0] == 1: data_ret = {'status': 1, 'createEmailStatus': 1, 'error_message': "None"} json_data = json.dumps(data_ret) return HttpResponse(json_data) else: - data_ret = {'status': 0, 'createEmailStatus': 0, 'error_message': output} + data_ret = {'status': 0, 'createEmailStatus': 0, 'error_message': result[1]} json_data = json.dumps(data_ret) return HttpResponse(json_data) @@ -127,6 +129,12 @@ class MailServerManager: data = json.loads(self.request.body) domain = data['domain'] + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + try: domain = Domains.objects.get(domain=domain) except: @@ -174,9 +182,18 @@ class MailServerManager: if ACLManager.currentContextPermission(currentACL, 'deleteEmail') == 0: return ACLManager.loadErrorJson('deleteEmailStatus', 0) + data = json.loads(self.request.body) email = data['email'] + eUser = EUsers.objects.get(email=email) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(eUser.emailOwner.domainOwner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + mailUtilities.deleteEmailAccount(email) data_ret = {'status': 1, 'deleteEmailStatus': 1, 'error_message': "None"} json_data = json.dumps(data_ret) @@ -217,6 +234,14 @@ class MailServerManager: data = json.loads(self.request.body) emailAddress = data['emailAddress'] + eUser = EUsers.objects.get(email=emailAddress) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(eUser.emailOwner.domainOwner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + currentForwardings = Forwardings.objects.filter(source=emailAddress) json_data = "[" @@ -260,6 +285,14 @@ class MailServerManager: destination = data['destination'] source = data['source'] + eUser = EUsers.objects.get(email=source) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(eUser.emailOwner.domainOwner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + for items in Forwardings.objects.filter(destination=destination, source=source): items.delete() @@ -284,6 +317,14 @@ class MailServerManager: source = data['source'] destination = data['destination'] + eUser = EUsers.objects.get(email=source) + + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(eUser.emailOwner.domainOwner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + if Forwardings.objects.filter(source=source, destination=destination).count() > 0: data_ret = {'status': 0, 'createStatus': 0, 'error_message': "You have already forwared to this destination."} @@ -340,10 +381,16 @@ class MailServerManager: emailDB = EUsers.objects.get(email=email) + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(emailDB.emailOwner.domainOwner.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + CentOSPath = '/etc/redhat-release' if os.path.exists(CentOSPath): - command = 'doveadm pw -p %s' % (password) - password = ProcessUtilities.outputExecutioner(command).strip('\n') + password = bcrypt.hashpw(str(password), bcrypt.gensalt()) + password = '{CRYPT}%s' % (password) emailDB.password = password else: emailDB.password = password @@ -392,16 +439,22 @@ class MailServerManager: data = json.loads(self.request.body) domainName = data['domainName'] + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + try: path = "/etc/opendkim/keys/" + domainName + "/default.txt" command = "sudo cat " + path - output = ProcessUtilities.outputExecutioner(command) + output = ProcessUtilities.outputExecutioner(command, 'opendkim') leftIndex = output.index('(') + 2 rightIndex = output.rindex(')') - 1 path = "/etc/opendkim/keys/" + domainName + "/default.private" command = "sudo cat " + path - privateKey = ProcessUtilities.outputExecutioner(command) + privateKey = ProcessUtilities.outputExecutioner(command, 'opendkim') data_ret = {'status': 1, 'fetchStatus': 1, 'keysAvailable': 1, 'publicKey': output[leftIndex:rightIndex], 'privateKey': privateKey, 'dkimSuccessMessage': 'Keys successfully fetched!', @@ -430,6 +483,12 @@ class MailServerManager: data = json.loads(self.request.body) domainName = data['domainName'] + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/mailUtilities.py" execPath = execPath + " generateKeys --domain " + domainName output = ProcessUtilities.outputExecutioner(execPath) diff --git a/mailServer/static/mailServer/mailServer.js b/mailServer/static/mailServer/mailServer.js index c5d8e512d..96403c507 100755 --- a/mailServer/static/mailServer/mailServer.js +++ b/mailServer/static/mailServer/mailServer.js @@ -4,7 +4,7 @@ /* Java script code to create account */ -app.controller('createEmailAccount', function($scope,$http) { +app.controller('createEmailAccount', function ($scope, $http) { $scope.emailDetails = true; $scope.emailLoading = true; @@ -12,7 +12,7 @@ app.controller('createEmailAccount', function($scope,$http) { $scope.successfullyCreated = true; $scope.couldNotConnect = true; - $scope.showEmailDetails = function(){ + $scope.showEmailDetails = function () { $scope.emailDetails = false; $scope.emailLoading = true; @@ -26,100 +26,91 @@ app.controller('createEmailAccount', function($scope,$http) { }; - $scope.createEmailAccount = function(){ + $scope.createEmailAccount = function () { + + $scope.emailDetails = false; + $scope.emailLoading = false; + $scope.canNotCreate = true; + $scope.successfullyCreated = true; + $scope.couldNotConnect = true; + + + var url = "/email/submitEmailCreation"; + + var domain = $scope.emailDomain; + var username = $scope.emailUsername; + var password = $scope.emailPassword; + + + var data = { + domain: domain, + username: username, + passwordByPass: password, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.createEmailStatus === 1) { $scope.emailDetails = false; - $scope.emailLoading = false; + $scope.emailLoading = true; $scope.canNotCreate = true; + $scope.successfullyCreated = false; + $scope.couldNotConnect = true; + + $scope.createdID = username + "@" + domain; + + + } else { + $scope.emailDetails = false; + $scope.emailLoading = true; + $scope.canNotCreate = false; $scope.successfullyCreated = true; $scope.couldNotConnect = true; + $scope.errorMessage = response.data.error_message; - var url = "/email/submitEmailCreation"; - - var domain = $scope.emailDomain; - var username = $scope.emailUsername; - var password = $scope.emailPassword; + } - var data = { - domain:domain, - username:username, - password:password, - }; + } - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if(response.data.createEmailStatus === 1){ - - $scope.emailDetails = false; - $scope.emailLoading = true; - $scope.canNotCreate = true; - $scope.successfullyCreated = false; - $scope.couldNotConnect = true; - - $scope.createdID = username + "@" + domain; - - - } - - else - { - $scope.emailDetails = false; - $scope.emailLoading = true; - $scope.canNotCreate = false; - $scope.successfullyCreated = true; - $scope.couldNotConnect = true; - - $scope.errorMessage = response.data.error_message; - - - } - - - - } - function cantLoadInitialDatas(response) { - - $scope.emailDetails = false; - $scope.emailLoading = true; - $scope.canNotCreate = true; - $scope.successfullyCreated = true; - $scope.couldNotConnect = false; - - - - } + function cantLoadInitialDatas(response) { + $scope.emailDetails = false; + $scope.emailLoading = true; + $scope.canNotCreate = true; + $scope.successfullyCreated = true; + $scope.couldNotConnect = false; + } }; - $scope.hideFewDetails = function(){ + $scope.hideFewDetails = function () { $scope.successfullyCreated = true; - }; $scope.generatedPasswordView = true; $scope.generatePassword = function () { - $scope.generatedPasswordView = false; - $scope.emailPassword = randomPassword(12); + $scope.generatedPasswordView = false; + $scope.emailPassword = randomPassword(12); }; $scope.usePassword = function () { @@ -131,7 +122,7 @@ app.controller('createEmailAccount', function($scope,$http) { /* Java script code to create account */ -app.controller('deleteEmailAccount', function($scope,$http) { +app.controller('deleteEmailAccount', function ($scope, $http) { $scope.emailDetails = true; $scope.emailLoading = true; @@ -141,7 +132,7 @@ app.controller('deleteEmailAccount', function($scope,$http) { $scope.emailDetailsFinal = true; $scope.noEmails = true; - $scope.showEmailDetails = function(){ + $scope.showEmailDetails = function () { $scope.emailDetails = true; $scope.emailLoading = false; @@ -157,80 +148,68 @@ app.controller('deleteEmailAccount', function($scope,$http) { var domain = $scope.emailDomain; + var data = { + domain: domain, + }; - var data = { - domain:domain, - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus == 1){ + if (response.data.fetchStatus == 1) { - $scope.emails = JSON.parse(response.data.data); + $scope.emails = JSON.parse(response.data.data); - $scope.emailDetails = false; - $scope.emailLoading = true; - $scope.canNotDelete = true; - $scope.successfullyDeleted = true; - $scope.couldNotConnect = true; - $scope.emailDetailsFinal = true; - $scope.noEmails = true; + $scope.emailDetails = false; + $scope.emailLoading = true; + $scope.canNotDelete = true; + $scope.successfullyDeleted = true; + $scope.couldNotConnect = true; + $scope.emailDetailsFinal = true; + $scope.noEmails = true; + } else { + $scope.emailDetails = true; + $scope.emailLoading = true; + $scope.canNotDelete = true; + $scope.successfullyDeleted = true; + $scope.couldNotConnect = true; + $scope.emailDetailsFinal = true; + $scope.noEmails = false; + + } + } - } - - else - { - $scope.emailDetails = true; - $scope.emailLoading = true; - $scope.canNotDelete = true; - $scope.successfullyDeleted = true; - $scope.couldNotConnect = true; - $scope.emailDetailsFinal = true; - $scope.noEmails = false; - - } - - - - } - function cantLoadInitialDatas(response) { - - $scope.emailDetails = true; - $scope.emailLoading = true; - $scope.canNotDelete = true; - $scope.successfullyDeleted = true; - $scope.couldNotConnect = false; - $scope.emailDetailsFinal = true; - $scope.noEmails = true; - - - - } - + function cantLoadInitialDatas(response) { + $scope.emailDetails = true; + $scope.emailLoading = true; + $scope.canNotDelete = true; + $scope.successfullyDeleted = true; + $scope.couldNotConnect = false; + $scope.emailDetailsFinal = true; + $scope.noEmails = true; + } }; - $scope.deleteEmailAccountFinal = function(){ + $scope.deleteEmailAccountFinal = function () { $scope.emailLoading = false; @@ -240,83 +219,73 @@ app.controller('deleteEmailAccount', function($scope,$http) { var email = $scope.selectedEmail; + var data = { + email: email, + }; - var data = { - email:email, - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.deleteEmailStatus === 1){ + if (response.data.deleteEmailStatus === 1) { - $scope.emailDetails = true; - $scope.emailLoading = true; - $scope.canNotDelete = true; - $scope.successfullyDeleted = false; - $scope.couldNotConnect = true; - $scope.emailDetailsFinal = true; - $scope.noEmails = true; + $scope.emailDetails = true; + $scope.emailLoading = true; + $scope.canNotDelete = true; + $scope.successfullyDeleted = false; + $scope.couldNotConnect = true; + $scope.emailDetailsFinal = true; + $scope.noEmails = true; - $scope.deletedID = email; + $scope.deletedID = email; - } + } else { + $scope.emailDetails = true; + $scope.emailLoading = true; + $scope.canNotDelete = false; + $scope.successfullyDeleted = true; + $scope.couldNotConnect = true; + $scope.emailDetailsFinal = true; + $scope.noEmails = true; - else - { - $scope.emailDetails = true; - $scope.emailLoading = true; - $scope.canNotDelete = false; - $scope.successfullyDeleted = true; - $scope.couldNotConnect = true; - $scope.emailDetailsFinal = true; - $scope.noEmails = true; + $scope.errorMessage = response.data.error_message; - $scope.errorMessage = response.data.error_message; - - } + } + } - } - function cantLoadInitialDatas(response) { - - $scope.emailDetails = true; - $scope.emailLoading = true; - $scope.canNotDelete = true; - $scope.successfullyDeleted = true; - $scope.couldNotConnect = false; - $scope.emailDetailsFinal = true; - $scope.noEmails = true; - - - - } - + function cantLoadInitialDatas(response) { + $scope.emailDetails = true; + $scope.emailLoading = true; + $scope.canNotDelete = true; + $scope.successfullyDeleted = true; + $scope.couldNotConnect = false; + $scope.emailDetailsFinal = true; + $scope.noEmails = true; + } }; - - $scope.deleteEmailAccount = function(){ + $scope.deleteEmailAccount = function () { var domain = $scope.selectedEmail; - if(domain.length>0) { + if (domain.length > 0) { $scope.emailDetailsFinal = false; } @@ -327,7 +296,7 @@ app.controller('deleteEmailAccount', function($scope,$http) { /* Java script code to create account */ -app.controller('changeEmailPassword', function($scope,$http) { +app.controller('changeEmailPassword', function ($scope, $http) { $scope.emailLoading = true; $scope.emailDetails = true; @@ -336,7 +305,7 @@ app.controller('changeEmailPassword', function($scope,$http) { $scope.couldNotConnect = true; $scope.noEmails = true; - $scope.showEmailDetails = function(){ + $scope.showEmailDetails = function () { $scope.emailLoading = false; $scope.emailDetails = true; @@ -351,71 +320,63 @@ app.controller('changeEmailPassword', function($scope,$http) { var domain = $scope.emailDomain; + var data = { + domain: domain, + }; - var data = { - domain:domain, - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus == 1){ + if (response.data.fetchStatus == 1) { - $scope.emails = JSON.parse(response.data.data); + $scope.emails = JSON.parse(response.data.data); - $scope.emailLoading = true; - $scope.emailDetails = false; - $scope.canNotChangePassword = true; - $scope.passwordChanged = true; - $scope.couldNotConnect = true; - $scope.noEmails = true; + $scope.emailLoading = true; + $scope.emailDetails = false; + $scope.canNotChangePassword = true; + $scope.passwordChanged = true; + $scope.couldNotConnect = true; + $scope.noEmails = true; + } else { + $scope.emailLoading = true; + $scope.emailDetails = true; + $scope.canNotChangePassword = true; + $scope.passwordChanged = true; + $scope.couldNotConnect = true; + $scope.noEmails = false; + + } + } - } + function cantLoadInitialDatas(response) { - else - { - $scope.emailLoading = true; - $scope.emailDetails = true; - $scope.canNotChangePassword = true; - $scope.passwordChanged = true; - $scope.couldNotConnect = true; - $scope.noEmails = false; - - } + $scope.emailLoading = true; + $scope.emailDetails = true; + $scope.canNotChangePassword = true; + $scope.passwordChanged = true; + $scope.couldNotConnect = false; + $scope.noEmails = true; - - } - function cantLoadInitialDatas(response) { - - $scope.emailLoading = true; - $scope.emailDetails = true; - $scope.canNotChangePassword = true; - $scope.passwordChanged = true; - $scope.couldNotConnect = false; - $scope.noEmails = true; - - - - } + } }; - $scope.changePassword = function(){ + $scope.changePassword = function () { $scope.emailLoading = false; @@ -427,83 +388,72 @@ app.controller('changeEmailPassword', function($scope,$http) { var domain = $scope.emailDomain; + var data = { + domain: domain, + email: email, + password: password, + }; - var data = { - domain:domain, - email:email, - password:password, - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.passChangeStatus == 1){ + if (response.data.passChangeStatus == 1) { - $scope.emailLoading = true; - $scope.emailDetails = true; - $scope.canNotChangePassword = true; - $scope.passwordChanged = false; - $scope.couldNotConnect = true; - $scope.noEmails = true; + $scope.emailLoading = true; + $scope.emailDetails = true; + $scope.canNotChangePassword = true; + $scope.passwordChanged = false; + $scope.couldNotConnect = true; + $scope.noEmails = true; - $scope.passEmail = email; + $scope.passEmail = email; - } - - else - { - $scope.emailLoading = true; - $scope.emailDetails = false; - $scope.canNotChangePassword = false; - $scope.passwordChanged = true; - $scope.couldNotConnect = true; - $scope.noEmails = true; + } else { + $scope.emailLoading = true; + $scope.emailDetails = false; + $scope.canNotChangePassword = false; + $scope.passwordChanged = true; + $scope.couldNotConnect = true; + $scope.noEmails = true; - $scope.errorMessage = response.data.error_message; + $scope.errorMessage = response.data.error_message; - } + } + } - } - function cantLoadInitialDatas(response) { - - $scope.emailLoading = true; - $scope.emailDetails = false; - $scope.canNotChangePassword = true; - $scope.passwordChanged = true; - $scope.couldNotConnect = false; - $scope.noEmails = true; - - - - - - } - + function cantLoadInitialDatas(response) { + $scope.emailLoading = true; + $scope.emailDetails = false; + $scope.canNotChangePassword = true; + $scope.passwordChanged = true; + $scope.couldNotConnect = false; + $scope.noEmails = true; + } }; - $scope.deleteEmailAccount = function(){ + $scope.deleteEmailAccount = function () { var domain = $scope.selectedEmail; - if(domain.length>0) { + if (domain.length > 0) { $scope.emailDetailsFinal = false; } @@ -514,8 +464,8 @@ app.controller('changeEmailPassword', function($scope,$http) { $scope.generatedPasswordView = true; $scope.generatePassword = function () { - $scope.generatedPasswordView = false; - $scope.emailPassword = randomPassword(12); + $scope.generatedPasswordView = false; + $scope.emailPassword = randomPassword(12); }; $scope.usePassword = function () { @@ -523,331 +473,322 @@ app.controller('changeEmailPassword', function($scope,$http) { }; - }); /* Java script code to create account ends here */ - /* Java script code for DKIM Manager */ -app.controller('dkimManager', function($scope, $http, $timeout, $window) { +app.controller('dkimManager', function ($scope, $http, $timeout, $window) { - $scope.manageDKIMLoading = true; - $scope.dkimError = true; - $scope.dkimSuccess = true; - $scope.couldNotConnect = true; - $scope.domainRecords = true; - $scope.noKeysAvailable = true; + $scope.manageDKIMLoading = true; + $scope.dkimError = true; + $scope.dkimSuccess = true; + $scope.couldNotConnect = true; + $scope.domainRecords = true; + $scope.noKeysAvailable = true; + $scope.fetchKeys = function () { - $scope.fetchKeys = function(){ - - $scope.manageDKIMLoading = false; - $scope.dkimError = true; - $scope.dkimSuccess = true; - $scope.couldNotConnect = true; - $scope.domainRecords = true; - $scope.noKeysAvailable = true; + $scope.manageDKIMLoading = false; + $scope.dkimError = true; + $scope.dkimSuccess = true; + $scope.couldNotConnect = true; + $scope.domainRecords = true; + $scope.noKeysAvailable = true; - url = "/email/fetchDKIMKeys"; + url = "/email/fetchDKIMKeys"; - var data = { - domainName: $scope.domainName - }; + var data = { + domainName: $scope.domainName + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus === 1){ + if (response.data.fetchStatus === 1) { - if(response.data.keysAvailable === 1){ - - $scope.manageDKIMLoading = true; - $scope.dkimError = true; - $scope.dkimSuccess = false; - $scope.couldNotConnect = true; - $scope.domainRecords = false; - $scope.noKeysAvailable = true; - - $scope.privateKey = response.data.privateKey; - $scope.publicKey = response.data.publicKey; - $scope.dkimSuccessMessage = response.data.dkimSuccessMessage; - - - - }else{ - $scope.manageDKIMLoading = true; - $scope.dkimError = true; - $scope.dkimSuccess = true; - $scope.couldNotConnect = true; - $scope.domainRecords = true; - $scope.noKeysAvailable = false; - } - - - - } - else{ - $scope.errorMessage = response.data.error_message; - - $scope.manageDKIMLoading = true; - $scope.dkimError = false; - $scope.dkimSuccess = true; - $scope.couldNotConnect = true; - $scope.domainRecords = true; - $scope.noKeysAvailable = true; - } - - } - function cantLoadInitialDatas(response) { + if (response.data.keysAvailable === 1) { $scope.manageDKIMLoading = true; $scope.dkimError = true; - $scope.dkimSuccess = true; - $scope.couldNotConnect = false; - $scope.domainRecords = true; + $scope.dkimSuccess = false; + $scope.couldNotConnect = true; + $scope.domainRecords = false; $scope.noKeysAvailable = true; - - } - - }; - - $scope.createDomainDKIMKeys = function () { - - $scope.manageDKIMLoading = false; - $scope.dkimError = true; - $scope.dkimSuccess = true; - $scope.couldNotConnect = true; - $scope.domainRecords = true; - $scope.noKeysAvailable = false; - - url = "/email/generateDKIMKeys"; - - var data = { - domainName: $scope.domainName - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + $scope.privateKey = response.data.privateKey; + $scope.publicKey = response.data.publicKey; + $scope.dkimSuccessMessage = response.data.dkimSuccessMessage; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if(response.data.generateStatus === 1){ - - $scope.manageDKIMLoading = true; - $scope.dkimError = true; - $scope.dkimSuccess = true; - $scope.couldNotConnect = true; - $scope.domainRecords = true; - $scope.noKeysAvailable = true; - - $scope.fetchKeys(); - - - } - else{ - $scope.errorMessage = response.data.error_message; - - $scope.manageDKIMLoading = true; - $scope.dkimError = false; - $scope.dkimSuccess = true; - $scope.couldNotConnect = true; - $scope.domainRecords = true; - $scope.noKeysAvailable = false; - } - - } - function cantLoadInitialDatas(response) { - + } else { $scope.manageDKIMLoading = true; $scope.dkimError = true; $scope.dkimSuccess = true; - $scope.couldNotConnect = false; + $scope.couldNotConnect = true; $scope.domainRecords = true; - $scope.noKeysAvailable = true; - - + $scope.noKeysAvailable = false; } + } else { + $scope.errorMessage = response.data.error_message; - }; + $scope.manageDKIMLoading = true; + $scope.dkimError = false; + $scope.dkimSuccess = true; + $scope.couldNotConnect = true; + $scope.domainRecords = true; + $scope.noKeysAvailable = true; + } - // Installation + } + + function cantLoadInitialDatas(response) { + + $scope.manageDKIMLoading = true; + $scope.dkimError = true; + $scope.dkimSuccess = true; + $scope.couldNotConnect = false; + $scope.domainRecords = true; + $scope.noKeysAvailable = true; - $scope.openDKIMNotifyBox = true; - $scope.openDKIMError = true; - $scope.couldNotConnect = true; - $scope.openDKIMSuccessfullyInstalled = true; - $scope.openDKIMInstallBox = true; - $scope.manageDKIMLoading = true; + } + + }; + + $scope.createDomainDKIMKeys = function () { + + $scope.manageDKIMLoading = false; + $scope.dkimError = true; + $scope.dkimSuccess = true; + $scope.couldNotConnect = true; + $scope.domainRecords = true; + $scope.noKeysAvailable = false; + + url = "/email/generateDKIMKeys"; + + var data = { + domainName: $scope.domainName + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $scope.installOpenDKIM = function(){ - - $scope.openDKIMNotifyBox = true; - $scope.openDKIMError = true; - $scope.couldNotConnect = true; - $scope.openDKIMSuccessfullyInstalled = true; - $scope.openDKIMInstallBox = true; - $scope.manageDKIMLoading = false; - - url = "/email/installOpenDKIM"; - - var data = {}; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + if (response.data.generateStatus === 1) { + + $scope.manageDKIMLoading = true; + $scope.dkimError = true; + $scope.dkimSuccess = true; + $scope.couldNotConnect = true; + $scope.domainRecords = true; + $scope.noKeysAvailable = true; + + $scope.fetchKeys(); - function ListInitialDatas(response) { + } else { + $scope.errorMessage = response.data.error_message; + + $scope.manageDKIMLoading = true; + $scope.dkimError = false; + $scope.dkimSuccess = true; + $scope.couldNotConnect = true; + $scope.domainRecords = true; + $scope.noKeysAvailable = false; + } + + } + + function cantLoadInitialDatas(response) { + + $scope.manageDKIMLoading = true; + $scope.dkimError = true; + $scope.dkimSuccess = true; + $scope.couldNotConnect = false; + $scope.domainRecords = true; + $scope.noKeysAvailable = true; - if(response.data.installOpenDKIM === 1){ + } - $scope.openDKIMNotifyBox = true; - $scope.openDKIMError = true; - $scope.couldNotConnect = true; - $scope.openDKIMSuccessfullyInstalled = true; - $scope.openDKIMInstallBox = false; - $scope.manageDKIMLoading = true; - getRequestStatus(); + }; - } - else{ - $scope.errorMessage = response.data.error_message; + // Installation - $scope.openDKIMNotifyBox = false; - $scope.openDKIMError = false; - $scope.couldNotConnect = true; - $scope.openDKIMSuccessfullyInstalled = true; - $scope.openDKIMInstallBox = true; - $scope.manageDKIMLoading = true; - } - } - function cantLoadInitialDatas(response) { + $scope.openDKIMNotifyBox = true; + $scope.openDKIMError = true; + $scope.couldNotConnect = true; + $scope.openDKIMSuccessfullyInstalled = true; + $scope.openDKIMInstallBox = true; + $scope.manageDKIMLoading = true; - $scope.openDKIMNotifyBox = false; - $scope.openDKIMError = true; - $scope.couldNotConnect = false; - $scope.openDKIMSuccessfullyInstalled = true; - $scope.openDKIMInstallBox = true; - $scope.manageDKIMLoading = false; + + $scope.installOpenDKIM = function () { + + $scope.openDKIMNotifyBox = true; + $scope.openDKIMError = true; + $scope.couldNotConnect = true; + $scope.openDKIMSuccessfullyInstalled = true; + $scope.openDKIMInstallBox = true; + $scope.manageDKIMLoading = false; + + url = "/email/installOpenDKIM"; + + var data = {}; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.installOpenDKIM === 1) { + + $scope.openDKIMNotifyBox = true; + $scope.openDKIMError = true; + $scope.couldNotConnect = true; + $scope.openDKIMSuccessfullyInstalled = true; + $scope.openDKIMInstallBox = false; + $scope.manageDKIMLoading = true; + + getRequestStatus(); + + } else { + $scope.errorMessage = response.data.error_message; + + $scope.openDKIMNotifyBox = false; + $scope.openDKIMError = false; + $scope.couldNotConnect = true; + $scope.openDKIMSuccessfullyInstalled = true; + $scope.openDKIMInstallBox = true; + $scope.manageDKIMLoading = true; + } + + } + + function cantLoadInitialDatas(response) { + + $scope.openDKIMNotifyBox = false; + $scope.openDKIMError = true; + $scope.couldNotConnect = false; + $scope.openDKIMSuccessfullyInstalled = true; + $scope.openDKIMInstallBox = true; + $scope.manageDKIMLoading = false; + } + + }; + + + function getRequestStatus() { + + $scope.openDKIMNotifyBox = true; + $scope.openDKIMError = true; + $scope.couldNotConnect = true; + $scope.openDKIMSuccessfullyInstalled = true; + $scope.openDKIMInstallBox = false; + $scope.manageDKIMLoading = false; + + + url = "/email/installStatusOpenDKIM"; + + var data = {}; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.abort === 0) { + $scope.requestData = response.data.requestStatus; + $timeout(getRequestStatus, 1000); + } else { + // Notifications + $timeout.cancel(); + + $scope.openDKIMNotifyBox = false; + $scope.openDKIMError = true; + $scope.couldNotConnect = true; + $scope.openDKIMSuccessfullyInstalled = true; + $scope.openDKIMInstallBox = true; + $scope.manageDKIMLoading = true; + + $scope.requestData = response.data.requestStatus; + + if (response.data.installed === 0) { + $scope.openDKIMError = false; + $scope.errorMessage = response.data.error_message; + } else { + $scope.openDKIMSuccessfullyInstalled = false; + $timeout(function () { + $window.location.reload(); + }, 3000); } - }; + } + + } + + function cantLoadInitialDatas(response) { + + $scope.modSecNotifyBox = false; + $scope.modeSecInstallBox = false; + $scope.modsecLoading = true; + $scope.failedToStartInallation = true; + $scope.couldNotConnect = false; + $scope.modSecSuccessfullyInstalled = true; + $scope.installationFailed = true; - function getRequestStatus(){ - - $scope.openDKIMNotifyBox = true; - $scope.openDKIMError = true; - $scope.couldNotConnect = true; - $scope.openDKIMSuccessfullyInstalled = true; - $scope.openDKIMInstallBox = false; - $scope.manageDKIMLoading = false; - - - - url = "/email/installStatusOpenDKIM"; - - var data = {}; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if(response.data.abort === 0){ - $scope.requestData = response.data.requestStatus; - $timeout(getRequestStatus,1000); - } - else{ - // Notifications - $timeout.cancel(); - - $scope.openDKIMNotifyBox = false; - $scope.openDKIMError = true; - $scope.couldNotConnect = true; - $scope.openDKIMSuccessfullyInstalled = true; - $scope.openDKIMInstallBox = true; - $scope.manageDKIMLoading = true; - - $scope.requestData = response.data.requestStatus; - - if(response.data.installed === 0) { - $scope.openDKIMError = false; - $scope.errorMessage = response.data.error_message; - }else{ - $scope.openDKIMSuccessfullyInstalled = false; - $timeout(function() { $window.location.reload(); }, 3000); - } - - } - - } - function cantLoadInitialDatas(response) { - - $scope.modSecNotifyBox = false; - $scope.modeSecInstallBox = false; - $scope.modsecLoading = true; - $scope.failedToStartInallation = true; - $scope.couldNotConnect = false; - $scope.modSecSuccessfullyInstalled = true; - $scope.installationFailed = true; - - - } - - } + } + } }); /* Java script code for email forwarding */ -app.controller('emailForwarding', function($scope,$http) { +app.controller('emailForwarding', function ($scope, $http) { $scope.creationBox = true; $scope.emailDetails = true; @@ -858,7 +799,7 @@ app.controller('emailForwarding', function($scope,$http) { $scope.notifyBox = true; - $scope.showEmailDetails = function(){ + $scope.showEmailDetails = function () { $scope.creationBox = true; $scope.emailDetails = true; @@ -871,69 +812,62 @@ app.controller('emailForwarding', function($scope,$http) { var url = "/email/getEmailsForDomain"; - var data = { - domain:$scope.emailDomain - }; + var data = { + domain: $scope.emailDomain + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus === 1){ + if (response.data.fetchStatus === 1) { - $scope.emails = JSON.parse(response.data.data); + $scope.emails = JSON.parse(response.data.data); - $scope.creationBox = true; - $scope.emailDetails = false; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = false; + $scope.creationBox = true; + $scope.emailDetails = false; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = false; - } + } else { + $scope.creationBox = true; + $scope.emailDetails = true; + $scope.forwardLoading = true; + $scope.forwardError = false; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = false; - else - { - $scope.creationBox = true; - $scope.emailDetails = true; - $scope.forwardLoading = true; - $scope.forwardError = false; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = false; + $scope.errorMessage = response.data.error_message; - $scope.errorMessage = response.data.error_message; - - } + } + } - } - function cantLoadInitialDatas(response) { - - $scope.creationBox = true; - $scope.emailDetails = true; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = false; - $scope.notifyBox = false; - - - } - + function cantLoadInitialDatas(response) { + $scope.creationBox = true; + $scope.emailDetails = true; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = false; + $scope.notifyBox = false; + } }; @@ -950,7 +884,7 @@ app.controller('emailForwarding', function($scope,$http) { $scope.fetchCurrentForwardings(); }; - $scope.fetchCurrentForwardings = function(){ + $scope.fetchCurrentForwardings = function () { $scope.creationBox = false; $scope.emailDetails = false; @@ -963,74 +897,67 @@ app.controller('emailForwarding', function($scope,$http) { var url = "/email/fetchCurrentForwardings"; - var data = { - emailAddress:$scope.selectedEmail - }; + var data = { + emailAddress: $scope.selectedEmail + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus === 1){ + if (response.data.fetchStatus === 1) { - $scope.records = JSON.parse(response.data.data); + $scope.records = JSON.parse(response.data.data); - $scope.creationBox = false; - $scope.emailDetails = false; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = true; + $scope.creationBox = false; + $scope.emailDetails = false; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = true; - } + } else { + $scope.creationBox = true; + $scope.emailDetails = true; + $scope.forwardLoading = true; + $scope.forwardError = false; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = false; - else - { - $scope.creationBox = true; - $scope.emailDetails = true; - $scope.forwardLoading = true; - $scope.forwardError = false; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = false; + $scope.errorMessage = response.data.error_message; - $scope.errorMessage = response.data.error_message; - - } + } + } - } - function cantLoadInitialDatas(response) { - - $scope.creationBox = true; - $scope.emailDetails = true; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = false; - $scope.notifyBox = false; - - - } - + function cantLoadInitialDatas(response) { + $scope.creationBox = true; + $scope.emailDetails = true; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = false; + $scope.notifyBox = false; + } }; - $scope.deleteForwarding = function(source, destination){ + $scope.deleteForwarding = function (source, destination) { $scope.creationBox = true; $scope.emailDetails = true; @@ -1043,75 +970,68 @@ app.controller('emailForwarding', function($scope,$http) { var url = "/email/submitForwardDeletion"; - var data = { - destination:destination, - source: source - }; + var data = { + destination: destination, + source: source + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.deleteForwardingStatus === 1){ + if (response.data.deleteForwardingStatus === 1) { - $scope.creationBox = false; - $scope.emailDetails = false; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = true; + $scope.creationBox = false; + $scope.emailDetails = false; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = true; - $scope.fetchCurrentForwardings(); + $scope.fetchCurrentForwardings(); - } + } else { + $scope.creationBox = false; + $scope.emailDetails = false; + $scope.forwardLoading = true; + $scope.forwardError = false; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = false; - else - { - $scope.creationBox = false; - $scope.emailDetails = false; - $scope.forwardLoading = true; - $scope.forwardError = false; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = false; + $scope.errorMessage = response.data.error_message; - $scope.errorMessage = response.data.error_message; - - } + } + } - } - function cantLoadInitialDatas(response) { - - $scope.creationBox = true; - $scope.emailDetails = true; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = false; - $scope.notifyBox = false; - - - } - + function cantLoadInitialDatas(response) { + $scope.creationBox = true; + $scope.emailDetails = true; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = false; + $scope.notifyBox = false; + } }; - $scope.forwardEmail = function(){ + $scope.forwardEmail = function () { $scope.creationBox = false; $scope.emailDetails = false; @@ -1124,70 +1044,63 @@ app.controller('emailForwarding', function($scope,$http) { var url = "/email/submitEmailForwardingCreation"; - var data = { - source: $scope.selectedEmail, - destination:$scope.destinationEmail - }; + var data = { + source: $scope.selectedEmail, + destination: $scope.destinationEmail + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.createStatus === 1){ + if (response.data.createStatus === 1) { - $scope.creationBox = false; - $scope.emailDetails = false; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = true; + $scope.creationBox = false; + $scope.emailDetails = false; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = true; - $scope.fetchCurrentForwardings(); + $scope.fetchCurrentForwardings(); - } + } else { + $scope.creationBox = false; + $scope.emailDetails = false; + $scope.forwardLoading = true; + $scope.forwardError = false; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = false; - else - { - $scope.creationBox = false; - $scope.emailDetails = false; - $scope.forwardLoading = true; - $scope.forwardError = false; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = false; + $scope.errorMessage = response.data.error_message; - $scope.errorMessage = response.data.error_message; - - } + } + } - } - function cantLoadInitialDatas(response) { - - $scope.creationBox = true; - $scope.emailDetails = true; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = false; - $scope.notifyBox = false; - - - } - + function cantLoadInitialDatas(response) { + $scope.creationBox = true; + $scope.emailDetails = true; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = false; + $scope.notifyBox = false; + } }; diff --git a/manageSSL/views.py b/manageSSL/views.py index 869ebee20..9dbcc24e2 100755 --- a/manageSSL/views.py +++ b/manageSSL/views.py @@ -60,6 +60,11 @@ def issueSSL(request): data = json.loads(request.body) virtualHost = data['virtualHost'] + if ACLManager.checkOwnership(virtualHost, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + adminEmail = "" path = "" @@ -146,6 +151,14 @@ def obtainHostNameSSL(request): path = "/home/" + virtualHost + "/public_html" + data = json.loads(request.body) + virtualHost = data['virtualHost'] + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(virtualHost, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + ## ssl issue execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" @@ -213,6 +226,12 @@ def obtainMailServerSSL(request): data = json.loads(request.body) virtualHost = data['virtualHost'] + admin = Administrator.objects.get(pk=userID) + if ACLManager.checkOwnership(virtualHost, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + path = "/home/" + virtualHost + "/public_html" ## ssl issue diff --git a/plogical/adminPass.py b/plogical/adminPass.py index fa5dc21e3..d2f4fe369 100755 --- a/plogical/adminPass.py +++ b/plogical/adminPass.py @@ -31,7 +31,7 @@ def main(): firstName="Cyber", lastName="Panel", acl=acl, token=token) admin.save() - vers = version(currentVersion="1.8", build=5) + vers = version(currentVersion="1.8", build=7) vers.save() package = Package(admin=admin, packageName="Default", diskSpace=1000, diff --git a/plogical/applicationInstaller.py b/plogical/applicationInstaller.py index 744c854eb..0b3a0cf3f 100755 --- a/plogical/applicationInstaller.py +++ b/plogical/applicationInstaller.py @@ -235,7 +235,7 @@ class ApplicationInstaller(multi.Thread): if not os.path.exists(finalPath): command = 'sudo mkdir -p ' + finalPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) ## checking for directories/files @@ -249,7 +249,7 @@ class ApplicationInstaller(multi.Thread): statusFile.close() command = "sudo wp core download --allow-root --path=" + finalPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) ## @@ -258,7 +258,7 @@ class ApplicationInstaller(multi.Thread): statusFile.close() command = "sudo wp core config --dbname=" + dbName + " --dbuser=" + dbUser + " --dbpass=" + dbPassword + " --dbhost=localhost --dbprefix=wp_ --allow-root --path=" + finalPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) if home == '0': path = self.extraArgs['path'] @@ -267,7 +267,7 @@ class ApplicationInstaller(multi.Thread): finalURL = domainName command = 'sudo wp core install --url="http://' + finalURL + '" --title="' + blogTitle + '" --admin_user="' + adminUser + '" --admin_password="' + adminPassword + '" --admin_email="' + adminEmail + '" --allow-root --path=' + finalPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) ## @@ -276,20 +276,20 @@ class ApplicationInstaller(multi.Thread): statusFile.close() command = "sudo wp plugin install litespeed-cache --allow-root --path=" + finalPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) statusFile = open(tempStatusPath, 'w') statusFile.writelines('Activating LSCache Plugin,90') statusFile.close() command = "sudo wp plugin activate litespeed-cache --allow-root --path=" + finalPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) ## command = "sudo chown -R " + externalApp + ":" + externalApp + " " + finalPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) statusFile = open(tempStatusPath, 'w') statusFile.writelines("Successfully Installed. [200]") @@ -306,7 +306,7 @@ class ApplicationInstaller(multi.Thread): if not os.path.exists(homeDir): command = "sudo chown -R " + externalApp + ":" + externalApp + " " + homeDir - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) try: mysqlUtilities.deleteDatabase(dbName, dbUser) @@ -404,7 +404,7 @@ class ApplicationInstaller(multi.Thread): if not os.path.exists(finalPath): command = 'sudo mkdir -p ' + finalPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) ## checking for directories/files @@ -417,14 +417,14 @@ class ApplicationInstaller(multi.Thread): statusFile.writelines('Downloading and extracting PrestaShop Core..,30') statusFile.close() - command = "sudo wget https://download.prestashop.com/download/releases/prestashop_1.7.4.2.zip" - ProcessUtilities.executioner(command) + command = "sudo wget https://download.prestashop.com/download/releases/prestashop_1.7.4.2.zip -P %s" % (finalPath) + ProcessUtilities.executioner(command, externalApp) - command = "sudo unzip -o prestashop_1.7.4.2.zip -d " + finalPath - ProcessUtilities.executioner(command) + command = "sudo unzip -o %sprestashop_1.7.4.2.zip -d " % (finalPath) + finalPath + ProcessUtilities.executioner(command, externalApp) - command = "sudo unzip -o " + finalPath + "prestashop.zip -d " + finalPath - ProcessUtilities.executioner(command) + command = "sudo unzip -o %sprestashop.zip -d " % (finalPath) + finalPath + ProcessUtilities.executioner(command, externalApp) ## @@ -447,20 +447,20 @@ class ApplicationInstaller(multi.Thread): " --db_server=localhost --db_name=" + dbName + " --db_user=" + dbUser + " --db_password=" + dbPassword \ + " --name='" + shopName + "' --firstname=" + firstName + " --lastname=" + lastName + \ " --email=" + email + " --password=" + password - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) ## command = "sudo rm -rf " + finalPath + "install" - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) ## command = "sudo chown -R " + externalApp + ":" + externalApp + " " + finalPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) command = "sudo rm -f prestashop_1.7.4.2.zip" - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) statusFile = open(tempStatusPath, 'w') statusFile.writelines("Successfully Installed. [200]") @@ -475,7 +475,7 @@ class ApplicationInstaller(multi.Thread): if not os.path.exists(homeDir): command = "sudo chown -R " + externalApp + ":" + externalApp + " " + homeDir - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) try: mysqlUtilities.deleteDatabase(dbName, dbUser) @@ -552,11 +552,9 @@ class ApplicationInstaller(multi.Thread): statusFile.close() return 0 - FNULL = open(os.devnull, 'w') - if not os.path.exists(finalPath): - command = 'sudo mkdir -p ' + finalPath - ProcessUtilities.executioner(command) + command = 'sudo mkdir -p ' + finalPath + ProcessUtilities.executioner(command, externalApp) ## checking for directories/files @@ -573,7 +571,7 @@ class ApplicationInstaller(multi.Thread): try: command = 'sudo GIT_SSH_COMMAND="ssh -o StrictHostKeyChecking=no" git clone --depth 1 --no-single-branch git@' + defaultProvider +'.com:' + username + '/' + reponame + '.git -b ' + branch + ' ' + finalPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) except subprocess.CalledProcessError, msg: statusFile = open(tempStatusPath, 'w') statusFile.writelines('Failed to clone repository, make sure you deployed your key to repository. [404]') @@ -583,7 +581,7 @@ class ApplicationInstaller(multi.Thread): ## command = "sudo chown -R " + externalApp + ":" + externalApp + " " + finalPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) vhost.addRewriteRules(domainName) installUtilities.reStartLiteSpeed() @@ -615,9 +613,11 @@ class ApplicationInstaller(multi.Thread): try: website = Websites.objects.get(domain=domain) finalPath = "/home/" + domain + "/public_html/" + externalApp = website.externalApp except: childDomain = ChildDomains.objects.get(domain=domain) finalPath = childDomain.path + externalApp = website.externalApp path = '/home/cyberpanel/' + domain + '.git' @@ -626,7 +626,7 @@ class ApplicationInstaller(multi.Thread): return 0 command = 'sudo git --git-dir=' + finalPath + '.git --work-tree=' + finalPath +' pull' - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) ## @@ -634,7 +634,7 @@ class ApplicationInstaller(multi.Thread): externalApp = website.externalApp command = "sudo chown -R " + externalApp + ":" + externalApp + " " + finalPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) return 0 @@ -666,15 +666,15 @@ class ApplicationInstaller(multi.Thread): command = 'sudo rm -rf ' + finalPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, website.externalApp) command = 'sudo mkdir ' + finalPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, website.externalApp) ## command = "sudo chown -R " + externalApp + ":" + externalApp + " " + finalPath - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, website.externalApp) gitPath = '/home/cyberpanel/' + domain + '.git' @@ -703,8 +703,6 @@ class ApplicationInstaller(multi.Thread): sitename = self.extraArgs['sitename'] tempStatusPath = self.extraArgs['tempStatusPath'] - - FNULL = open(os.devnull, 'w') if not os.path.exists(finalPath): @@ -850,6 +848,7 @@ class ApplicationInstaller(multi.Thread): statusFile = open(tempStatusPath, 'w') statusFile.writelines(str(msg) + " [404]") statusFile.close() + logging.writeToFile(str(msg)) return 0 def changeBranch(self): @@ -861,17 +860,19 @@ class ApplicationInstaller(multi.Thread): try: website = Websites.objects.get(domain=domainName) finalPath = "/home/" + domainName + "/public_html/" + externalApp = website.externalApp except: childDomain = ChildDomains.objects.get(domain=domainName) finalPath = childDomain.path + externalApp = childDomain.master.externalApp try: command = 'sudo git --git-dir=' + finalPath + '/.git checkout -b ' + githubBranch - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) except: try: command = 'sudo git --git-dir=' + finalPath + '/.git checkout ' + githubBranch - ProcessUtilities.executioner(command) + ProcessUtilities.executioner(command, externalApp) except subprocess.CalledProcessError, msg: logging.writeToFile('Failed to change branch: ' + str(msg)) return 0 diff --git a/plogical/backupSchedule.py b/plogical/backupSchedule.py index 531591d50..1c79d047b 100755 --- a/plogical/backupSchedule.py +++ b/plogical/backupSchedule.py @@ -15,6 +15,8 @@ from re import match,I,M from websiteFunctions.models import Websites, Backups from plogical.virtualHostUtilities import virtualHostUtilities from plogical.processUtilities import ProcessUtilities +from multiprocessing import Process +import plogical.backupUtilities as backupUtil class backupSchedule: @@ -43,11 +45,9 @@ class backupSchedule: ## /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 ' + virtualHost - - subprocess.Popen(shlex.split(execPath)) + p = Process(target=backupUtil.submitBackupCreation, + args=(tempStoragePath, backupName, backupPath, virtualHost)) + p.start() time.sleep(2) diff --git a/plogical/backupUtilities.py b/plogical/backupUtilities.py index 7da361f83..7a015318c 100755 --- a/plogical/backupUtilities.py +++ b/plogical/backupUtilities.py @@ -2,7 +2,10 @@ import os,sys sys.path.append('/usr/local/CyberCP') import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") -django.setup() +try: + django.setup() +except: + pass import pexpect import CyberCPLogFileWriter as logging import subprocess @@ -28,6 +31,8 @@ from mailServer.models import Domains as eDomains import time from plogical.mailUtilities import mailUtilities from shutil import copy +from random import randint +from plogical.processUtilities import ProcessUtilities ## I am not the monster that you think I am.. @@ -40,14 +45,6 @@ class backupUtilities: @staticmethod def prepareBackupMeta(backupDomain, backupName, tempStoragePath, backupPath): try: - ## /home/example.com/backup/backup-example-06-50-03-Thu-Feb-2018 -- tempStoragePath - ## /home/example.com/backup - backupPath - - if not os.path.exists(backupPath): - os.mkdir(backupPath) - - if not os.path.exists(tempStoragePath): - os.mkdir(tempStoragePath) website = Websites.objects.get(domain=backupDomain) @@ -181,30 +178,41 @@ class backupUtilities: return reparsed.toprettyxml(indent=" ") ## /home/example.com/backup/backup-example-06-50-03-Thu-Feb-2018/meta.xml -- metaPath - metaPath = os.path.join(tempStoragePath, "meta.xml") + + metaPath = '/tmp/%s' % (str(randint(1000, 9999))) xmlpretty = prettify(metaFileXML).encode('ascii', 'ignore') metaFile = open(metaPath, 'w') metaFile.write(xmlpretty) metaFile.close() + os.chmod(metaPath, 0777) ## meta generated newBackup = Backups(website=website, fileName=backupName, date=time.strftime("%I-%M-%S-%a-%b-%Y"), - size=0, status=0) + size=0, status=1) newBackup.save() - return 1,'None' + return 1,'None', metaPath except BaseException, msg: return 0,str(msg) @staticmethod - def startBackup(tempStoragePath, backupName, backupPath): + def startBackup(tempStoragePath, backupName, backupPath, metaPath = None): try: + ## /home/example.com/backup/backup-example-06-50-03-Thu-Feb-2018 -- tempStoragePath + ## /home/example.com/backup - backupPath + + if not os.path.exists(backupPath): + os.mkdir(backupPath) + + if not os.path.exists(tempStoragePath): + os.mkdir(tempStoragePath) + ##### Writing the name of backup file. ## /home/example.com/backup/backupFileName @@ -221,7 +229,16 @@ class backupUtilities: ##### Parsing XML Meta file! ## /home/example.com/backup/backup-example-06-50-03-Thu-Feb-2018 -- tempStoragePath - backupMetaData = ElementTree.parse(os.path.join(tempStoragePath,'meta.xml')) + + metaPathInBackup = os.path.join(tempStoragePath,'meta.xml') + + if metaPath != None: + writeToFile = open(metaPathInBackup, 'w') + writeToFile.write(open(metaPath, 'r').read()) + writeToFile.close() + + backupMetaData = ElementTree.parse(metaPathInBackup) + ##### Making archive of home directory @@ -251,28 +268,6 @@ class backupUtilities: except: pass - ## backup email accounts - - logging.CyberCPLogFileWriter.statusWriter(status, "Backing up email accounts!\n") - - try: - make_archive(os.path.join(tempStoragePath,domainName),'gztar',os.path.join("/home","vmail",domainName)) - except: - pass - - ## Backing up databases - databases = backupMetaData.findall('Databases/database') - - for database in databases: - - dbName = database.find('dbName').text - - logging.CyberCPLogFileWriter.statusWriter(status, "Backing up database: " + dbName) - - if mysqlUtilities.mysqlUtilities.createDatabaseBackup(dbName, tempStoragePath) == 0: - raise BaseException - - ## Child Domains SSL. @@ -303,40 +298,11 @@ class backupUtilities: sslStoragePath) except: pass - except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [startBackup]") - ##### Saving SSL Certificates if any - - ## shutil.make_archive. Creating final package. - - make_archive(os.path.join(backupPath,backupName), 'gztar', tempStoragePath) - rmtree(tempStoragePath) - - ### - - fileName = open(backupFileNamePath, 'r').read() - - backupObs = Backups.objects.filter(fileName=fileName) - - ## adding backup data to database. - try: - for items in backupObs: - items.status = 1 - items.size = str(int(float( - os.path.getsize(os.path.join(backupPath,backupName+".tar.gz"))) / ( - 1024.0 * 1024.0))) + "MB" - items.save() - except: - for items in backupObs: - items.status = 1 - items.size = str(int(float( - os.path.getsize(os.path.join(backupPath,backupName+".tar.gz"))) / ( - 1024.0 * 1024.0))) + "MB" - items.save() - - logging.CyberCPLogFileWriter.statusWriter(status, "Completed\n") + logging.CyberCPLogFileWriter.statusWriter(status, "Backing up databases.") + print '1,None' except BaseException,msg: try: @@ -350,9 +316,63 @@ class backupUtilities: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [startBackup]") status = os.path.join(backupPath, 'status') - logging.CyberCPLogFileWriter.statusWriter(status, "Aborted, "+ str(msg) + ". [5009]") + logging.CyberCPLogFileWriter.statusWriter(status, "Aborted, "+ str(msg) + ".[365] [5009]") logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [startBackup]") + @staticmethod + def BackupRoot(tempStoragePath, backupName, backupPath, metaPath=None): + + ## backup emails + + status = os.path.join(backupPath, 'status') + metaPathInBackup = os.path.join(tempStoragePath, 'meta.xml') + backupMetaData = ElementTree.parse(metaPathInBackup) + domainName = backupMetaData.find('masterDomain').text + + if os.path.islink(status) or os.path.islink(tempStoragePath or os.path.islink(backupPath)) or os.path.islink(metaPath): + logging.CyberCPLogFileWriter.writeToFile('symlinked.') + return 0 + + ## backup email accounts + + logging.CyberCPLogFileWriter.statusWriter(status, "Backing up email accounts!\n") + + try: + make_archive(os.path.join(tempStoragePath, domainName), 'gztar', os.path.join("/home", "vmail", domainName)) + except BaseException, msg: + print str(msg) + pass + + + ## shutil.make_archive. Creating final package. + + make_archive(os.path.join(backupPath, backupName), 'gztar', tempStoragePath) + rmtree(tempStoragePath) + + ### + backupFileNamePath = os.path.join(backupPath,"backupFileName") + fileName = open(backupFileNamePath, 'r').read() + + backupObs = Backups.objects.filter(fileName=fileName) + + ## adding backup data to database. + try: + for items in backupObs: + items.status = 1 + items.size = str(int(float( + os.path.getsize(os.path.join(backupPath,backupName+".tar.gz"))) / ( + 1024.0 * 1024.0))) + "MB" + items.save() + except: + for items in backupObs: + items.status = 1 + items.size = str(int(float( + os.path.getsize(os.path.join(backupPath,backupName+".tar.gz"))) / ( + 1024.0 * 1024.0))) + "MB" + items.save() + + logging.CyberCPLogFileWriter.statusWriter(status, "Completed\n") + @staticmethod def initiateBackup(tempStoragePath,backupName,backupPath): try: @@ -983,13 +1003,47 @@ def submitBackupCreation(tempStoragePath, backupName, backupPath, backupDomain): logging.CyberCPLogFileWriter.statusWriter(status, result[1] + ' [5009]') return + website = Websites.objects.get(domain=backupDomain) - p = Process(target=backupUtilities.startBackup, args=(tempStoragePath, backupName, backupPath,)) - p.start() - pid = open(os.path.join(backupPath, 'pid'), "w") - pid.write(str(p.pid)) - pid.close() + execPath = "sudo nice -n 10 python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" + execPath = execPath + " startBackup --tempStoragePath " + tempStoragePath + " --backupName " \ + + backupName + " --backupPath " + backupPath + ' --backupDomain ' + backupDomain + ' --metaPath %s' % (result[2]) + ProcessUtilities.executioner(execPath, website.externalApp) + + ## Backing up databases + + backupMetaData = ElementTree.parse(result[2]) + + if os.path.islink(status) or os.path.islink(tempStoragePath or os.path.islink(backupPath)) or os.path.islink( + result[2]): + logging.CyberCPLogFileWriter.writeToFile('symlinked.') + return 0 + + databases = backupMetaData.findall('Databases/database') + + for database in databases: + + dbName = database.find('dbName').text + + if mysqlUtilities.mysqlUtilities.createDatabaseBackup(dbName, '/home/cyberpanel') == 0: + return 0 + + command = 'mv /home/cyberpanel/%s.sql %s/%s.sql' % (dbName, tempStoragePath, dbName) + ProcessUtilities.executioner(command, 'root') + + ## + + if ProcessUtilities.outputExecutioner(execPath, website.externalApp).find('1,None') > -1: + execPath = "sudo nice -n 10 python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" + execPath = execPath + " BackupRoot --tempStoragePath " + tempStoragePath + " --backupName " \ + + backupName + " --backupPath " + backupPath + ' --backupDomain ' + backupDomain + ' --metaPath %s' % ( + result[2]) + + ProcessUtilities.executioner(execPath, 'root') + + command = 'rm -f %s' % (result[2]) + ProcessUtilities.executioner(command, 'cyberpanel') except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile( @@ -1105,6 +1159,10 @@ def main(): submitDestinationCreation(args.ipAddress, args.password, args.port) elif args.function == "getConnectionStatus": getConnectionStatus(args.ipAddress) + elif args.function == "startBackup": + backupUtilities.startBackup(args.tempStoragePath, args.backupName, args.backupPath, args.metaPath) + elif args.function == "BackupRoot": + backupUtilities.BackupRoot(args.tempStoragePath, args.backupName, args.backupPath, args.metaPath) if __name__ == "__main__": main() \ No newline at end of file diff --git a/plogical/cPanelImporter.py b/plogical/cPanelImporter.py index 45e9f6023..35ec41fc5 100644 --- a/plogical/cPanelImporter.py +++ b/plogical/cPanelImporter.py @@ -41,7 +41,7 @@ class cPanelImporter: def __init__(self, backupFile, logFile): self.backupFile = backupFile - self.fileName = backupFile.split('/')[-1].strip('.tar.gz') + self.fileName = backupFile.split('/')[-1].replace('.tar.gz', '') self.logFile = logFile self.PHPVersion = '' self.email = '' @@ -68,6 +68,10 @@ class cPanelImporter: elif self.PHPVersion.find('73') > -1: self.PHPVersion = 'PHP 7.3' + if self.PHPVersion == '': + self.PHPVersion = 'PHP 7.1' + + def SetupSSL(self, path, domain): data = open(path, 'r').readlines() @@ -154,7 +158,7 @@ class cPanelImporter: for items in data: if items.find('main_domain') > -1: - DomainName = items.split(' ')[-1].strip('\n') + DomainName = items.split(' ')[-1].replace('\n', '') self.mainDomain = DomainName break @@ -169,13 +173,18 @@ class cPanelImporter: DomainMeta = '%s/userdata/%s' % (CompletPathToExtractedArchive, DomainName) data = open(DomainMeta, 'r').readlines() + phpChecker = 1 for items in data: if items.find('phpversion') > -1: - self.PHPVersion = items.split(' ')[-1].strip('\n') + self.PHPVersion = items.split(' ')[-1].replace('\n', '') self.PHPDecider() + phpChecker = 0 break + if phpChecker: + self.PHPDecider() + message = 'PHP version of %s is %s.' % (DomainName, self.PHPVersion) logging.statusWriter(self.logFile, message, 1) @@ -188,7 +197,7 @@ class cPanelImporter: for items in data: if items.find('serveradmin') > -1: - self.email = items.split(' ')[-1].strip('\n') + self.email = items.split(' ')[-1].replace('\n', '') break message = 'Server Admin email for %s is %s.' % (DomainName, self.email) @@ -240,14 +249,14 @@ class cPanelImporter: for items in data: if items.find('homedir') > -1: - self.homeDir = items.split(' ')[-1].strip('\n') + self.homeDir = items.split(' ')[-1].replace('\n', '') break data = open(DomainMeta, 'r').readlines() for items in data: if items.find('documentroot') > -1: - self.documentRoot = items.split(' ')[-1].strip('\n') + self.documentRoot = items.split(' ')[-1].replace('\n', '') break nowPath = '/home/%s/public_html' % (DomainName) @@ -303,7 +312,7 @@ class cPanelImporter: addonStatus = 0 continue else: - cDomain = items.split(':')[0].strip(' ') + cDomain = items.split(':')[0].replace(' ', '') if len(cDomain) < 2: continue Domains.append(ChildDomains(cDomain, 1)) @@ -317,7 +326,7 @@ class cPanelImporter: existCheck = 0 if subDomainsStatus == 1: - cDomain = items.split(' ')[-1].strip('\n') + cDomain = items.split(' ')[-1].replace('\n', '') for items in Domains: if cDomain.find(items.domain) > -1: existCheck = 1 @@ -340,56 +349,54 @@ class cPanelImporter: for items in Domains: - message = 'Creating %s.' % (items.domain) - logging.statusWriter(self.logFile, message, 1) + try: - path = '/home/' + self.mainDomain + '/public_html/' + items.domain + message = 'Creating %s.' % (items.domain) + logging.statusWriter(self.logFile, message, 1) - ## Find PHP Version + path = '/home/' + self.mainDomain + '/public_html/' + items.domain - if items.addon == 1: - DomainMeta = '%s/userdata/%s.%s' % (CompletPathToExtractedArchive, items.domain, self.mainDomain) - else: - DomainMeta = '%s/userdata/%s' % (CompletPathToExtractedArchive, items.domain) + ## Find PHP Version - data = open(DomainMeta, 'r').readlines() + if items.addon == 1: + DomainMeta = '%s/userdata/%s.%s' % (CompletPathToExtractedArchive, items.domain, self.mainDomain) + else: + DomainMeta = '%s/userdata/%s' % (CompletPathToExtractedArchive, items.domain) - for it in data: - if it.find('phpversion') > -1: - self.PHPVersion = it.split(' ')[-1].strip('\n') + data = open(DomainMeta, 'r').readlines() + phpChecker = 1 + for it in data: + if it.find('phpversion') > -1: + self.PHPVersion = it.split(' ')[-1].replace('\n', '') + self.PHPDecider() + phpChecker = 0 + break + + if phpChecker: self.PHPDecider() - break - message = 'Calling core to create %s.' % (items.domain) - logging.statusWriter(self.logFile, message, 1) - - result = virtualHostUtilities.createDomain(self.mainDomain, items.domain, self.PHPVersion, path, 0, 0, - 0, 'admin', 0) - - if result[0] == 1: - message = 'Child domain %s created from archive file: %s' % (items.domain, self.backupFile) - logging.statusWriter(self.logFile, message, 1) - else: - message = 'Failed to create Child domain %s from archive file: %s' % (items.domain, self.backupFile) + message = 'Calling core to create %s.' % (items.domain) logging.statusWriter(self.logFile, message, 1) + result = virtualHostUtilities.createDomain(self.mainDomain, items.domain, self.PHPVersion, path, 0, 0, + 0, 'admin', 0) + + if result[0] == 1: + message = 'Child domain %s created from archive file: %s' % (items.domain, self.backupFile) + logging.statusWriter(self.logFile, message, 1) + else: + message = 'Failed to create Child domain %s from archive file: %s' % (items.domain, self.backupFile) + logging.statusWriter(self.logFile, message, 1) - ## Setup SSL - message = 'Detecting SSL for %s.' % (items.domain) - logging.statusWriter(self.logFile, message, 1) + ## Setup SSL - SSLPath = '%s/apache_tls/%s' % (CompletPathToExtractedArchive, items.domain) - - if os.path.exists(SSLPath): - message = 'SSL found for %s, setting up.' % (items.domain) + message = 'Detecting SSL for %s.' % (items.domain) logging.statusWriter(self.logFile, message, 1) - self.SetupSSL(SSLPath, items.domain) - message = 'SSL set up OK for %s.' % (items.domain) - logging.statusWriter(self.logFile, message, 1) - else: - SSLPath = '%s/apache_tls/%s.%s' % (CompletPathToExtractedArchive, items.domain, self.mainDomain) + + SSLPath = '%s/apache_tls/%s' % (CompletPathToExtractedArchive, items.domain) + if os.path.exists(SSLPath): message = 'SSL found for %s, setting up.' % (items.domain) logging.statusWriter(self.logFile, message, 1) @@ -397,38 +404,49 @@ class cPanelImporter: message = 'SSL set up OK for %s.' % (items.domain) logging.statusWriter(self.logFile, message, 1) else: - message = 'SSL not detected for %s, you can later issue SSL from Manage SSL in CyberPanel.' % ( - items.domain) - logging.statusWriter(self.logFile, message, 1) + SSLPath = '%s/apache_tls/%s.%s' % (CompletPathToExtractedArchive, items.domain, self.mainDomain) + if os.path.exists(SSLPath): + message = 'SSL found for %s, setting up.' % (items.domain) + logging.statusWriter(self.logFile, message, 1) + self.SetupSSL(SSLPath, items.domain) + message = 'SSL set up OK for %s.' % (items.domain) + logging.statusWriter(self.logFile, message, 1) + else: + message = 'SSL not detected for %s, you can later issue SSL from Manage SSL in CyberPanel.' % ( + items.domain) + logging.statusWriter(self.logFile, message, 1) - ## Creating Document root for childs + ## Creating Document root for childs - message = 'Restoring document root files for %s.' % (items.domain) - logging.statusWriter(self.logFile, message, 1) + message = 'Restoring document root files for %s.' % (items.domain) + logging.statusWriter(self.logFile, message, 1) - externalApp = "".join(re.findall("[a-zA-Z]+", self.mainDomain))[:7] + externalApp = "".join(re.findall("[a-zA-Z]+", self.mainDomain))[:7] - data = open(DomainMeta, 'r').readlines() + data = open(DomainMeta, 'r').readlines() - for items in data: - if items.find('documentroot') > -1: - ChildDocRoot = items.split(' ')[-1].strip('\n') - break + for items in data: + if items.find('documentroot') > -1: + ChildDocRoot = items.split(' ')[-1].replace('\n', '') + break - if os.path.exists(path): - shutil.rmtree(path) + if os.path.exists(path): + shutil.rmtree(path) - movePath = '%s/homedir/public_html/%s' % ( - CompletPathToExtractedArchive, ChildDocRoot.replace(self.documentRoot, '', 1).replace('/', '')) + movePath = '%s/homedir/public_html/%s' % ( + CompletPathToExtractedArchive, ChildDocRoot.replace(self.documentRoot, '', 1).replace('/', '')) - shutil.move(movePath, path) + shutil.move(movePath, path) - command = 'chown -R %s:%s %s' % (externalApp, externalApp, path) - ProcessUtilities.normalExecutioner(command) + command = 'chown -R %s:%s %s' % (externalApp, externalApp, path) + ProcessUtilities.normalExecutioner(command) - message = 'Successfully created child domain.' - logging.statusWriter(self.logFile, message, 1) + message = 'Successfully created child domain.' + logging.statusWriter(self.logFile, message, 1) + except BaseException, msg: + message = 'Failed to create child domain from backup file %s, error message: %s. Moving on..' % ( + self.backupFile, str(msg)) return 1 @@ -517,7 +535,7 @@ class cPanelImporter: RecordsData[4] = ipAddress if RecordsData[0].find(topLevelDomain) > -1: - DNS.createDNSRecord(zone, RecordsData[0].strip('.'), RecordsData[3], RecordsData[4], 0, RecordsData[1]) + DNS.createDNSRecord(zone, RecordsData[0].replace('.', ''), RecordsData[3], RecordsData[4], 0, RecordsData[1]) else: DNS.createDNSRecord(zone, RecordsData[0] + '.' + topLevelDomain , RecordsData[3], RecordsData[4], 0, RecordsData[1]) @@ -540,7 +558,7 @@ class cPanelImporter: f = open(passFile) data = f.read() password = data.split('\n', 1)[0] - password = password.strip('\n').strip('\r') + password = password.replace('\n', '').replace('\r', '') conn = mysql.connect(user='root', passwd=password, cursorclass=cursors.SSCursor) cursor = conn.cursor() @@ -575,16 +593,16 @@ class cPanelImporter: for items in os.listdir(DatabasesPath): if items.endswith('.sql'): - message = 'Restoring MySQL dump for %s.' % (items.strip('.sql')) + message = 'Restoring MySQL dump for %s.' % (items.replace('.sql', '')) logging.statusWriter(self.logFile, message, 1) try: - cursor.execute("CREATE DATABASE " + items.strip('.sql')) + cursor.execute("CREATE DATABASE " + items.replace('.sql', '')) except BaseException, msg: - message = 'Error while restoring database %s from backup file %s, error message: %s' % (items.strip('.sql'), self.backupFile, str(msg)) + message = 'Error while restoring database %s from backup file %s, error message: %s' % (items.replace('.sql', ''), self.backupFile, str(msg)) logging.statusWriter(self.logFile, message, 1) - command = 'sudo mysql -u root -p' + password + ' ' + items.strip('.sql') + command = 'sudo mysql -u root -p' + password + ' ' + items.replace('.sql', '') cmd = shlex.split(command) @@ -595,10 +613,10 @@ class cPanelImporter: website = Websites.objects.get(domain=self.mainDomain) - db = Databases(website=website, dbName=items.strip('.sql'), dbUser=items.strip('.sql')) + db = Databases(website=website, dbName=items.replace('.sql', ''), dbUser=items.replace('.sql', '')) db.save() - message = 'MySQL dump successfully restored for %s.' % (items.strip('.sql')) + message = 'MySQL dump successfully restored for %s.' % (items.replace('.sql', '')) logging.statusWriter(self.logFile, message, 1) message = 'Creating Database users from backup file %s.' % (self.backupFile) @@ -615,7 +633,7 @@ class cPanelImporter: cursor.execute(items) except BaseException, msg: message = 'Error while restoring database %s from backup file %s, error message: %s' % ( - items.strip('.sql'), self.backupFile, str(msg)) + items.replace('.sql', ''), self.backupFile, str(msg)) logging.statusWriter(self.logFile, message, 1) connection.close() @@ -791,12 +809,13 @@ def main(): args = parser.parse_args() for items in os.listdir(args.path): - finalPath = '%s/%s' % (args.path, items) - cI = cPanelImporter(finalPath, LogFile) - if cI.MainController(): - pass - else: - cI.DeleteSite() + if items.endswith('.tar.gz'): + finalPath = '%s/%s' % (args.path.rstrip('/'), items) + cI = cPanelImporter(finalPath, LogFile) + if cI.MainController(): + pass + else: + pass if __name__ == "__main__": main() diff --git a/plogical/cronUtil.py b/plogical/cronUtil.py index 08493833b..90f50e19d 100755 --- a/plogical/cronUtil.py +++ b/plogical/cronUtil.py @@ -20,15 +20,8 @@ class CronUtil: else: cronPath = "/var/spool/cron/crontabs/" + externalApp - cmd = 'sudo test -e ' + cronPath + ' && echo Exists' - output = os.popen(cmd).read() - - if "Exists" not in output: - print "0,CyberPanel,Not Exists" - return 1 - try: - f = subprocess.check_output(["sudo", "crontab", "-u", externalApp, "-l"]) + f = open(cronPath, 'r').read() print f except BaseException, msg: print "0,CyberPanel," + str(msg) @@ -41,38 +34,20 @@ class CronUtil: def saveCronChanges(externalApp, finalCron, line): try: - tempPath = "/home/cyberpanel/" + externalApp + str(randint(10000, 99999)) + ".cron.tmp" - output = subprocess.check_output(["sudo", "/usr/bin/crontab", "-u", externalApp, "-l"]) + if ProcessUtilities.decideDistro() == ProcessUtilities.centos: + cronPath = "/var/spool/cron/" + externalApp + else: + cronPath = "/var/spool/cron/crontabs/" + externalApp - if "no crontab for" in output: - print "0,crontab file does not exists for user" - return 1 - - with open(tempPath, "w+") as file: - file.write(output) - - # Confirming that directory is read/writable - o = subprocess.call(['sudo', 'chown', 'cyberpanel:cyberpanel', tempPath]) - if o is not 0: - print "0,Error Changing Permissions" - return 1 - - with open(tempPath, 'r') as file: + with open(cronPath, 'r') as file: data = file.readlines() data[line] = finalCron + '\n' - with open(tempPath, 'w') as file: + with open(cronPath, 'w') as file: file.writelines(data) - output = subprocess.call(["sudo", "/usr/bin/crontab", "-u", externalApp, tempPath]) - - os.remove(tempPath) - if output != 0: - print "0,Incorrect Syntax cannot be accepted." - return 1 - print "1,None" except BaseException, msg: print "0," + str(msg) @@ -82,37 +57,24 @@ class CronUtil: try: line -= 1 - output = subprocess.check_output(["sudo", "/usr/bin/crontab", "-u", externalApp, "-l"]) + if ProcessUtilities.decideDistro() == ProcessUtilities.centos: + cronPath = "/var/spool/cron/" + externalApp + else: + cronPath = "/var/spool/cron/crontabs/" + externalApp - if "no crontab for" in output: - print "0,No Cron exists for this user" - return 1 + data = open(cronPath, 'r').readlines() - tempPath = "/home/cyberpanel/" + externalApp + str(randint(10000, 99999)) + ".cron.tmp" + counter = 0 - with open(tempPath, "w+") as file: - file.write(output) + writeToFile = open(cronPath, 'w') + for items in data: + if counter == line: + removedLine = items + continue + else: + writeToFile.writelines(items) - # Confirming that directory is read/writable - o = subprocess.call(['sudo', 'chown', 'cyberpanel:cyberpanel', tempPath]) - if o is not 0: - print "0,Error Changing Permissions" - return 1 - - with open(tempPath, 'r') as file: - data = file.readlines() - - removedLine = data.pop(line) - - with open(tempPath, 'w') as file: - file.writelines(data) - - output = subprocess.call(["sudo", "/usr/bin/crontab", "-u", externalApp, tempPath]) - - os.remove(tempPath) - if output != 0: - print "0,Incorrect Syntax cannot be accepted" - return 1 + counter = counter + 1 print "1," + removedLine except BaseException, msg: @@ -121,44 +83,26 @@ class CronUtil: @staticmethod def addNewCron(externalApp, finalCron): try: + CronPath = '/var/spool/cron/%s' % (externalApp) - try: - output = subprocess.check_output(["sudo", "/usr/bin/crontab", "-u", externalApp, "-l"]) - except: - try: - subprocess.call(('sudo', 'crontab', '-u', externalApp, '-')) - except: - print "0,Unable to initialise crontab file for user" - return 1 - - output = subprocess.check_output(["sudo", "/usr/bin/crontab", "-u", externalApp, "-l"]) - - if "no crontab for" in output: - echo = subprocess.Popen((['cat', '/dev/null']), stdout=subprocess.PIPE) - subprocess.call(('sudo', 'crontab', '-u', externalApp, '-'), stdin=echo.stdout) - echo.wait() - echo.stdout.close() - output = subprocess.check_output(["sudo", "/usr/bin/crontab", "-u", externalApp, "-l"]) - if "no crontab for" in output: - print "0,Unable to initialise crontab file for user" - return 1 - - tempPath = "/home/cyberpanel/" + externalApp + str(randint(10000, 99999)) + ".cron.tmp" - - with open(tempPath, "a") as file: - file.write(output + finalCron + "\n") - - output = subprocess.call(["sudo", "/usr/bin/crontab", "-u", externalApp, tempPath]) - - os.remove(tempPath) - if output != 0: - print "0,Incorrect Syntax cannot be accepted" - return 1 + with open(CronPath, "a") as file: + file.write(finalCron + "\n") print "1,None" except BaseException, msg: print "0," + str(msg) + @staticmethod + def CronPrem(mode): + if mode: + cronParent = '/var/spool/cron' + commandT = 'chmod 755 %s' % (cronParent) + ProcessUtilities.executioner(commandT, 'root') + else: + cronParent = '/var/spool/cron' + commandT = 'chmod 700 %s' % (cronParent) + ProcessUtilities.executioner(commandT, 'root') + def main(): diff --git a/plogical/ftpUtilities.py b/plogical/ftpUtilities.py index a1e49d19c..31dab10a3 100755 --- a/plogical/ftpUtilities.py +++ b/plogical/ftpUtilities.py @@ -17,6 +17,7 @@ import grp import hashlib from ftp.models import Users from datetime import datetime +from plogical.processUtilities import ProcessUtilities class FTPUtilities: @@ -88,14 +89,9 @@ class FTPUtilities: @staticmethod def ftpFunctions(path,externalApp): try: - FNULL = open(os.devnull, 'w') - if not os.path.exists(path): - os.makedirs(path) - - command = "chown " + externalApp + ":" + externalApp + " " + path - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + command = 'mkdir %s' % (path) + ProcessUtilities.executioner(command, externalApp) return 1,'None' @@ -143,6 +139,10 @@ class FTPUtilities: else: path = "/home/" + domainName + if os.path.islink(path): + print "0, %s file is symlinked." % (path) + return 0 + hash = hashlib.md5() hash.update(password) diff --git a/plogical/mailUtilities.py b/plogical/mailUtilities.py index 4eb94008d..9cb176829 100755 --- a/plogical/mailUtilities.py +++ b/plogical/mailUtilities.py @@ -15,6 +15,7 @@ from websiteFunctions.models import Websites, ChildDomains from processUtilities import ProcessUtilities import os, getpass import hashlib +import bcrypt class mailUtilities: @@ -22,6 +23,21 @@ class mailUtilities: spamassassinInstallLogPath = "/home/cyberpanel/spamassassinInstallLogPath" cyberPanelHome = "/home/cyberpanel" + @staticmethod + def AfterEffects(domain): + path = "/usr/local/CyberCP/install/rainloop/cyberpanel.net.ini" + + if not os.path.exists("/usr/local/lscp/cyberpanel/rainloop/data/_data_/_default_/domains/"): + os.makedirs("/usr/local/lscp/cyberpanel/rainloop/data/_data_/_default_/domains/") + + finalPath = "/usr/local/lscp/cyberpanel/rainloop/data/_data_/_default_/domains/" + domain + ".ini" + + if not os.path.exists(finalPath): + shutil.copy(path, finalPath) + + command = 'chown -R lscpd:lscpd /usr/local/lscp/cyberpanel/rainloop/data/' + ProcessUtilities.normalExecutioner(command) + @staticmethod def createEmailAccount(domain, userName, password): try: @@ -88,19 +104,9 @@ class mailUtilities: ## After effects - - path = "/usr/local/CyberCP/install/rainloop/cyberpanel.net.ini" - - if not os.path.exists("/usr/local/lscp/cyberpanel/rainloop/data/_data_/_default_/domains/"): - os.makedirs("/usr/local/lscp/cyberpanel/rainloop/data/_data_/_default_/domains/") - - finalPath = "/usr/local/lscp/cyberpanel/rainloop/data/_data_/_default_/domains/" + domain + ".ini" - - if not os.path.exists(finalPath): - shutil.copy(path, finalPath) - - command = 'chown -R lscpd:lscpd /usr/local/lscp/cyberpanel/rainloop/data/' - ProcessUtilities.normalExecutioner(command) + execPath = "sudo python /usr/local/CyberCP/plogical/mailUtilities.py" + execPath = execPath + " AfterEffects --domain " + domain + ProcessUtilities.executioner(execPath, 'lscpd') ## After effects ends @@ -114,8 +120,8 @@ class mailUtilities: CentOSPath = '/etc/redhat-release' if os.path.exists(CentOSPath): - command = 'doveadm pw -p %s' % (password) - password = subprocess.check_output(shlex.split(command)).strip('\n') + password = bcrypt.hashpw(str(password), bcrypt.gensalt()) + password = '{CRYPT}%s' % (password) emailAcct = EUsers(emailOwner=emailDomain, email=finalEmailUsername, password=password) emailAcct.mail = 'maildir:/home/vmail/%s/%s/Maildir' % (domain, userName) emailAcct.save() @@ -164,8 +170,8 @@ class mailUtilities: CentOSPath = '/etc/redhat-release' changePass = EUsers.objects.get(email=email) if os.path.exists(CentOSPath): - command = 'doveadm pw -p %s' % (newPassword) - password = subprocess.check_output(shlex.split(command)).strip('\n') + password = bcrypt.hashpw(str(newPassword), bcrypt.gensalt()) + password = '{CRYPT}%s' % (password) changePass.password = password else: changePass.password = newPassword @@ -657,6 +663,8 @@ def main(): mailUtilities.savePolicyServerStatus(args.install) elif args.function == 'installSpamAssassin': mailUtilities.installSpamAssassin("install", "SpamAssassin") + elif args.function == 'AfterEffects': + mailUtilities.AfterEffects(args.domain) if __name__ == "__main__": main() \ No newline at end of file diff --git a/plogical/mysqlUtilities.py b/plogical/mysqlUtilities.py index 9e79a4462..4ab5c9f04 100755 --- a/plogical/mysqlUtilities.py +++ b/plogical/mysqlUtilities.py @@ -2,7 +2,10 @@ import os,sys sys.path.append('/usr/local/CyberCP') import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") -django.setup() +try: + django.setup() +except: + pass import CyberCPLogFileWriter as logging import subprocess import shlex @@ -142,22 +145,43 @@ class mysqlUtilities: def createDatabaseBackup(databaseName,tempStoragePath): try: passFile = "/etc/cyberpanel/mysqlPassword" - f = open(passFile) data = f.read() password = data.split('\n', 1)[0] - command = 'sudo mysqldump -u root -p'+password+' '+databaseName + cnfPath = '/home/cyberpanel/.my.cnf' + if not os.path.exists(cnfPath): + cnfContent = """[mysqldump] +user=root +password=%s +[mysql] +user=root +password=%s +""" % (password, password) + writeToFile = open(cnfPath, 'w') + writeToFile.write(cnfContent) + writeToFile.close() + + os.chmod(cnfPath, 0600) + + command = 'mysqldump --defaults-extra-file=/home/cyberpanel/.my.cnf --host=localhost ' + databaseName cmd = shlex.split(command) - with open(tempStoragePath+"/"+databaseName+'.sql', 'w') as f: - res = subprocess.call(cmd,stdout=f) + try: + errorPath = '/home/cyberpanel/error-logs.txt' + errorLog = open(errorPath, 'a') + with open(tempStoragePath+"/"+databaseName+'.sql', 'w') as f: + res = subprocess.call(cmd,stdout=f, stderr=errorLog) + if res != 0: + logging.CyberCPLogFileWriter.writeToFile( + "Database: " + databaseName + "could not be backed! [createDatabaseBackup]") + return 0 - if res == 1: - logging.CyberCPLogFileWriter.writeToFile("Database: "+databaseName + "could not be backed! [createDatabaseBackup]") + except subprocess.CalledProcessError, msg: + logging.CyberCPLogFileWriter.writeToFile( + "Database: " + databaseName + "could not be backed! Error: %s. [createDatabaseBackup]" % (str(msg))) return 0 - return 1 except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[createDatabaseBackup]") @@ -172,12 +196,27 @@ class mysqlUtilities: data = f.read() password = data.split('\n', 1)[0] + cnfPath = '/home/cyberpanel/.my.cnf' - command = 'sudo mysql -u root -p' + password + ' ' + databaseName + if not os.path.exists(cnfPath): + cnfContent = """[mysqldump] +user=root +password=%s +[mysql] +user=root +password=%s +""" % (password, password) + writeToFile = open(cnfPath, 'w') + writeToFile.write(cnfContent) + writeToFile.close() + os.chmod(cnfPath, 0600) + command = 'chown cyberpanel:cyberpanel %s' % (cnfPath) + subprocess.call(shlex.split(command)) + + command = 'sudo mysql --defaults-extra-file=/home/cyberpanel/.my.cnf --host=localhost ' + databaseName cmd = shlex.split(command) - with open(tempStoragePath + "/" + databaseName + '.sql', 'r') as f: res = subprocess.call(cmd, stdin=f) diff --git a/plogical/processUtilities.py b/plogical/processUtilities.py index 40cc41a68..3058abf7e 100755 --- a/plogical/processUtilities.py +++ b/plogical/processUtilities.py @@ -5,6 +5,7 @@ import os import socket import threading as multi import time +from pipes import quote class ProcessUtilities(multi.Thread): litespeedProcess = "litespeed" @@ -162,7 +163,7 @@ class ProcessUtilities(multi.Thread): time.sleep(2) @staticmethod - def sendCommand(command): + def sendCommand(command, user=None): try: ret = ProcessUtilities.setupUDSConnection() @@ -176,7 +177,29 @@ class ProcessUtilities(multi.Thread): sock = ret[0] - sock.sendall(ProcessUtilities.token + command) + # SplittedCommand = command.split(' ') + # if SplittedCommand[0] == 'sudo': + # finalCommand = SplittedCommand[1:] + # else: + # finalCommand = SplittedCommand + # + # CommandArgs = finalCommand[1:] + # + # finalCommand = finalCommand[0] + # + # for items in CommandArgs: + # finalCommand = '%s %s' % (finalCommand, items) + + + if user == None: + sock.sendall(ProcessUtilities.token + command) + else: + command = '%s-u %s %s' % (ProcessUtilities.token, user, command) + command = command.replace('sudo', '') + sock.sendall(command) + + #logging.writeToFile(command) + data = "" while (1): @@ -192,9 +215,9 @@ class ProcessUtilities(multi.Thread): return "0" + str(msg) @staticmethod - def executioner(command): + def executioner(command, user=None): try: - ret = ProcessUtilities.sendCommand(command) + ret = ProcessUtilities.sendCommand(command, user) exitCode = ret[len(ret) -1] exitCode = int(exitCode.encode('hex'), 16) @@ -211,14 +234,14 @@ class ProcessUtilities(multi.Thread): return 0 @staticmethod - def outputExecutioner(command): + def outputExecutioner(command, user=None): try: if type(command) == str or type(command) == unicode: pass else: command = " ".join(command) - return ProcessUtilities.sendCommand(command)[:-1] + return ProcessUtilities.sendCommand(command, user)[:-1] except BaseException, msg: logging.writeToFile(str(msg) + "[outputExecutioner:188]") @@ -229,17 +252,18 @@ class ProcessUtilities(multi.Thread): else: command = " ".join(self.extraArgs['command']) - ProcessUtilities.sendCommand(command) + ProcessUtilities.sendCommand(command, self.extraArgs['user']) return 1 except BaseException, msg: logging.writeToFile(str(msg) + " [customPoen]") @staticmethod - def popenExecutioner(command): + def popenExecutioner(command, user=None): try: extraArgs = {} extraArgs['command'] = command + extraArgs['user'] = user pu = ProcessUtilities("popen", extraArgs) pu.start() except BaseException, msg: diff --git a/plogical/sslUtilities.py b/plogical/sslUtilities.py index f039b594e..e809b504f 100755 --- a/plogical/sslUtilities.py +++ b/plogical/sslUtilities.py @@ -192,7 +192,7 @@ class sslUtilities: """ - VirtualHost = '\n\n' + VirtualHost = '\n\n\n' ServerName = ' ServerName ' + virtualHostName + '\n' ServerAlias = ' ServerAlias www.' + virtualHostName + '\n' ServerAdmin = ' ServerAdmin ' + adminEmail + '\n' diff --git a/plogical/upgrade.py b/plogical/upgrade.py index 7026f9bf7..23cabd357 100755 --- a/plogical/upgrade.py +++ b/plogical/upgrade.py @@ -808,6 +808,12 @@ class Upgrade: except: pass + try: + cursor.execute( + 'ALTER TABLE e_users MODIFY password varchar(200)') + except: + pass + try: cursor.execute( 'ALTER TABLE e_forwardings DROP PRIMARY KEY;ALTER TABLE e_forwardings ADD id INT AUTO_INCREMENT PRIMARY KEY') @@ -1049,6 +1055,41 @@ class Upgrade: except: pass + @staticmethod + def CLMigrations(): + try: + connection, cursor = Upgrade.setupConnection('cyberpanel') + + query = """CREATE TABLE `CLManager_clpackages` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(50) NOT NULL, + `speed` varchar(50) NOT NULL, + `vmem` varchar(50) NOT NULL, + `pmem` varchar(50) NOT NULL, + `io` varchar(50) NOT NULL, + `iops` varchar(50) NOT NULL, + `ep` varchar(50) NOT NULL, + `nproc` varchar(50) NOT NULL, + `inodessoft` varchar(50) NOT NULL, + `inodeshard` varchar(50) NOT NULL, + `owner_id` int(11) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name` (`name`), + KEY `CLManager_clpackages_owner_id_9898c1e8_fk_packages_package_id` (`owner_id`), + CONSTRAINT `CLManager_clpackages_owner_id_9898c1e8_fk_packages_package_id` FOREIGN KEY (`owner_id`) REFERENCES `packages_package` (`id`) +)""" + try: + cursor.execute(query) + except: + pass + + try: + connection.close() + except: + pass + except: + pass + @staticmethod def manageServiceMigrations(): try: @@ -1058,8 +1099,6 @@ class Upgrade: `id` int(11) NOT NULL AUTO_INCREMENT, `serverStatus` int(11) NOT NULL, `type` varchar(6) NOT NULL, - `allow_axfr_ips` varchar(500) NOT NULL, - `also_notify` varchar(500) NOT NULL, PRIMARY KEY (`id`) )""" try: @@ -1067,6 +1106,16 @@ class Upgrade: except: pass + try: + cursor.execute('alter table manageServices_pdnsstatus add masterServer varchar(200)') + except: + pass + + try: + cursor.execute('alter table manageServices_pdnsstatus add masterIP varchar(200)') + except: + pass + try: connection.close() except: @@ -1139,6 +1188,11 @@ class Upgrade: data = open("/usr/local/settings.py", 'r').readlines() + csrfCheck = 1 + for items in data: + if items.find('CsrfViewMiddleware') > -1: + csrfCheck = 0 + pluginCheck = 1 for items in data: if items.find('pluginHolder') > -1: @@ -1174,11 +1228,20 @@ class Upgrade: if items.find('manageServices') > -1: manageServices = 0 + CLManager = 1 + for items in data: + if items.find('CLManager') > -1: + CLManager = 0 + Upgrade.stdOut('Restoring settings file!') writeToFile = open("/usr/local/CyberCP/CyberCP/settings.py", 'w') for items in data: + if items.find("CommonMiddleware") > -1: + if csrfCheck == 1: + writeToFile.writelines(" 'django.middleware.common.CommonMiddleware',\n") + if items.find("'filemanager',") > -1: writeToFile.writelines(items) if pluginCheck == 1: @@ -1198,6 +1261,9 @@ class Upgrade: if manageServices == 1: writeToFile.writelines(" 'manageServices',\n") + if CLManager == 1: + writeToFile.writelines(" 'CLManager',\n") + else: writeToFile.writelines(items) @@ -1234,6 +1300,8 @@ class Upgrade: try: command = "pip install tldextract" Upgrade.executioner(command, 'Install tldextract', 1) + command = "pip install bcrypt" + Upgrade.executioner(command, 'Install tldextract', 1) except OSError, msg: Upgrade.stdOut(str(msg) + " [installTLDExtract]") return 0 @@ -1253,31 +1321,20 @@ class Upgrade: ## + lscpdPath = '/usr/local/lscp/bin/lscpd' + + if os.path.exists(lscpdPath): + os.remove(lscpdPath) + + command = 'wget https://cyberpanel.sh/lscpd -P /usr/local/lscp/bin/' + Upgrade.executioner(command, 'LSCPD Download.', 0) + + command = 'chmod 755 %s' % (lscpdPath) + Upgrade.executioner(command, 'LSCPD Download.', 0) + command = 'yum -y install pcre-devel openssl-devel expat-devel geoip-devel zlib-devel udns-devel which curl' Upgrade.executioner(command, 'LSCPD Pre-reqs [two]', 0) - ## - - if os.path.exists('/usr/local/lscp.tar.gz'): - os.remove('/usr/local/lscp.tar.gz') - - command = 'wget https://cyberpanel.net/lscp.tar.gz' - Upgrade.executioner(command, 'Download LSCPD [two]', 0) - - ## - - command = 'tar zxf lscp.tar.gz -C /usr/local/' - Upgrade.executioner(command, 'Extract LSCPD [two]', 0) - - try: - os.remove("/usr/local/lscp/fcgi-bin/lsphp") - shutil.copy("/usr/local/lsws/lsphp70/bin/lsphp", "/usr/local/lscp/fcgi-bin/lsphp") - except: - pass - - command = 'openssl req -newkey rsa:1024 -new -nodes -x509 -days 3650 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout /usr/local/lscp/conf/key.pem -out /usr/local/lscp/conf/cert.pem' - Upgrade.executioner(command, 'generate cyberpanel ssl', 0) - command = 'adduser lscpd -M -d /usr/local/lscp' Upgrade.executioner(command, 'Add user LSCPD', 0) @@ -1371,6 +1428,56 @@ class Upgrade: command = "chown root:cyberpanel /usr/local/CyberCP/CyberCP/settings.py" Upgrade.executioner(command, 'chown core code', 0) + command = 'chmod +x /usr/local/CyberCP/CLManager/CLPackages.py' + Upgrade.executioner(command, 'chmod CLPackages', 0) + + files = ['/etc/yum.repos.d/MariaDB.repo', '/etc/pdns/pdns.conf', '/etc/systemd/system/lscpd.service', + '/etc/pure-ftpd/pure-ftpd.conf', '/etc/pure-ftpd/pureftpd-pgsql.conf', + '/etc/pure-ftpd/pureftpd-mysql.conf', '/etc/pure-ftpd/pureftpd-ldap.conf', + '/etc/dovecot/dovecot.conf', '/usr/local/lsws/conf/httpd_config.xml', + '/usr/local/lsws/conf/modsec.conf', '/usr/local/lsws/conf/httpd.conf'] + + for items in files: + command = 'chmod 644 %s' % (items) + Upgrade.executioner(command, 'chown core code', 0) + + impFile = ['/etc/pure-ftpd/pure-ftpd.conf', '/etc/pure-ftpd/pureftpd-pgsql.conf', + '/etc/pure-ftpd/pureftpd-mysql.conf', '/etc/pure-ftpd/pureftpd-ldap.conf', + '/etc/dovecot/dovecot.conf', '/etc/pdns/pdns.conf'] + + for items in impFile: + command = 'chmod 600 %s' % (items) + Upgrade.executioner(command, 'chown core code', 0) + + command = 'chmod 640 /etc/postfix/*.cf' + subprocess.call(command, shell=True) + + command = 'chmod 640 /etc/dovecot/*.conf' + subprocess.call(command, shell=True) + + command = 'chmod 640 /etc/dovecot/dovecot-sql.conf.ext' + subprocess.call(command, shell=True) + + fileM = ['/usr/local/lsws/FileManager/', '/usr/local/CyberCP/install/FileManager', + '/usr/local/CyberCP/serverStatus/litespeed/FileManager', + '/usr/local/lsws/Example/html/FileManager'] + + for items in fileM: + try: + shutil.rmtree(items) + except: + pass + + command = 'chmod 755 /etc/pure-ftpd/' + subprocess.call(command, shell=True) + + command = 'chmod 644 /etc/dovecot/dovecot.conf' + subprocess.call(command, shell=True) + + command = 'chmod 644 /etc/postfix/main.cf' + subprocess.call(command, shell=True) + + Upgrade.stdOut("Permissions updated.") except BaseException, msg: @@ -1432,32 +1539,37 @@ enabled=1""" data = open(path, 'r').readlines() + updatePasswords = 1 + writeToFile = open(path, 'w') for items in data: if items.find('default_pass_scheme') > -1: + updatePasswords = 0 continue else: writeToFile.writelines(items) writeToFile.close() - - for items in EUsers.objects.all(): - command = 'doveadm pw -p %s' % (items.password) - items.password = subprocess.check_output(shlex.split(command)).strip('\n') - items.save() + if updatePasswords: + for items in EUsers.objects.all(): + command = 'doveadm pw -p %s' % (items.password) + items.password = subprocess.check_output(shlex.split(command)).strip('\n') + items.save() command = "systemctl restart dovecot" Upgrade.executioner(command, 0) - - @staticmethod def upgrade(): # Upgrade.stdOut("Upgrades are currently disabled") # return 0 + postfixPath = '/home/cyberpanel/postfix' + pdns = '/home/cyberpanel/pdns' + pureftpd = '/home/cyberpanel/ftp' + os.chdir("/usr/local") ## Current Version @@ -1499,6 +1611,7 @@ enabled=1""" Upgrade.mailServerMigrations() Upgrade.emailMarketingMigrationsa() Upgrade.dockerMigrations() + Upgrade.CLMigrations() ## @@ -1517,13 +1630,14 @@ enabled=1""" Upgrade.setupPythonWSGI() Upgrade.someDirectories() Upgrade.installLSCPD() - Upgrade.fixPermissions() Upgrade.GeneralMigrations() - Upgrade.upgradeDovecot() + + if os.path.exists(postfixPath): + Upgrade.upgradeDovecot() time.sleep(3) ## Upgrade version - + Upgrade.fixPermissions() Upgrade.upgradeVersion() try: diff --git a/plogical/vhost.py b/plogical/vhost.py index b52a13ef5..758844b8e 100755 --- a/plogical/vhost.py +++ b/plogical/vhost.py @@ -95,15 +95,15 @@ class vhost: try: os.makedirs(pathLogs) - command = "chown " + "lscpd" + ":" + "lscpd" + " " + pathLogs + command = "chown %s:%s %s" % ('root', 'nobody', pathLogs) cmd = shlex.split(command) subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) if ProcessUtilities.decideServer() == ProcessUtilities.OLS: - command = "chmod -R 666 " + pathLogs + command = "chmod -R 750 " + pathLogs else: - command = "chmod -R 755 " + pathLogs + command = "chmod -R 750 " + pathLogs cmd = shlex.split(command) subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) @@ -129,6 +129,10 @@ class vhost: cmd = shlex.split(command) subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + command = 'chmod 600 %s' % (completePathToConfigFile) + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + except IOError, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectories]]") return [0, "[45 Not able to directories for virtual host [createDirectories]]"] diff --git a/plogical/virtualHostUtilities.py b/plogical/virtualHostUtilities.py index aed5d4e97..3e53b5821 100755 --- a/plogical/virtualHostUtilities.py +++ b/plogical/virtualHostUtilities.py @@ -29,6 +29,7 @@ from processUtilities import ProcessUtilities from ApachController.ApacheController import ApacheController from ApachController.ApacheVhosts import ApacheVhost from managePHP.phpManager import PHPManager +from CLManager.models import CLPackages ## If you want justice, you have come to the wrong place. @@ -38,6 +39,38 @@ class virtualHostUtilities: ols = 2 lsws = 3 + @staticmethod + def EnableCloudLinux(): + if ProcessUtilities.decideServer() == ProcessUtilities.OLS: + confPath = '/usr/local/lsws/conf/httpd_config.conf' + data = open(confPath, 'r').readlines() + + writeToFile = open(confPath, 'w') + + for items in data: + if items.find('priority') > -1: + writeToFile.writelines(items) + writeToFile.writelines('enableLVE 2\n') + else: + writeToFile.writelines(items) + + writeToFile.close() + else: + confPath = '/usr/local/lsws/conf/httpd_config.xml' + data = open(confPath, 'r').readlines() + + writeToFile = open(confPath, 'w') + + for items in data: + if items.find('') > -1: + writeToFile.writelines(items) + writeToFile.writelines(' 2\n') + else: + writeToFile.writelines(items) + + writeToFile.close() + + Server_root = "/usr/local/lsws" cyberPanel = "/usr/local/CyberCP" @staticmethod @@ -154,12 +187,57 @@ class virtualHostUtilities: ## DKIM Check - if dkimCheck == 1: - DNS.createDKIMRecords(virtualHostName) + postFixPath = '/home/cyberpanel/postfix' + if os.path.exists(postFixPath): + if dkimCheck == 1: + DNS.createDKIMRecords(virtualHostName) + cageFSPath = '/home/cyberpanel/cagefs' + + if os.path.exists(cageFSPath): + command = '/usr/sbin/cagefsctl --enable %s' % (virtualHostUser) + ProcessUtilities.normalExecutioner(command) logging.CyberCPLogFileWriter.statusWriter(tempStatusPath, 'Website successfully created. [200]') + CLPath = '/etc/sysconfig/cloudlinux' + + if os.path.exists(CLPath): + if CLPackages.objects.count() == 0: + package = Package.objects.get(packageName='Default') + clPackage = CLPackages(name='Default', owner=package, speed='100%', vmem='1G', pmem='1G', io='1024', + iops='1024', ep='20', nproc='50', inodessoft='20', inodeshard='20') + clPackage.save() + + writeToFile = open(CLPath, 'a') + writeToFile.writelines('CUSTOM_GETPACKAGE_SCRIPT=/usr/local/CyberCP/CLManager/CLPackages.py\n') + writeToFile.close() + + command = 'chmod +x /usr/local/CyberCP/CLManager/CLPackages.py' + ProcessUtilities.normalExecutioner(command) + + virtualHostUtilities.EnableCloudLinux() + installUtilities.installUtilities.reStartLiteSpeed() + + command = 'sudo lvectl package-set %s --speed=%s --pmem=%s --io=%s --nproc=%s --iops=%s --vmem=%s --ep=%s' % ( + 'Default', '100%', '1G', '1024', '50', '1024', '1G', '20') + ProcessUtilities.normalExecutioner(command) + + command = 'sudo lvectl apply all' + ProcessUtilities.normalExecutioner(command) + else: + try: + clPackage = CLPackages.objects.get(owner=selectedPackage) + command = 'sudo lvectl package-set %s --speed=%s --pmem=%s --io=%s --nproc=%s --iops=%s --vmem=%s --ep=%s' % ( + clPackage.name, clPackage.speed, clPackage.pmem, clPackage.io, clPackage.np, clPackage.iops, clPackage.vmem, clPackage.ep) + ProcessUtilities.normalExecutioner(command) + command = 'sudo lvectl apply all' + ProcessUtilities.normalExecutioner(command) + except: + pass + + + return 1, 'None' except BaseException, msg: @@ -192,6 +270,10 @@ class virtualHostUtilities: def getAccessLogs(fileName, page): try: + if os.path.islink(fileName): + print "0, %s file is symlinked." % (fileName) + return 0 + numberOfTotalLines = int(subprocess.check_output(["wc", "-l", fileName]).split(" ")[0]) if numberOfTotalLines < 25: @@ -225,6 +307,10 @@ class virtualHostUtilities: def getErrorLogs(fileName, page): try: + if os.path.islink(fileName): + print "0, %s file is symlinked." % (fileName) + return 0 + numberOfTotalLines = int(subprocess.check_output(["wc", "-l", fileName]).split(" ")[0]) if numberOfTotalLines < 25: @@ -280,16 +366,21 @@ class virtualHostUtilities: def saveRewriteRules(virtualHost, fileName, tempPath): try: + if os.path.islink(fileName): + print "0, .htaccess file is symlinked." + return 0 + vhost.addRewriteRules(virtualHost, fileName) vhostFile = open(fileName, "w") vhostFile.write(open(tempPath, "r").read()) vhostFile.close() - if os.path.exists(tempPath): - os.remove(tempPath) - - installUtilities.installUtilities.reStartLiteSpeed() + try: + if os.path.exists(tempPath): + os.remove(tempPath) + except: + pass print "1,None" @@ -1007,8 +1098,11 @@ class virtualHostUtilities: ## DKIM Check - if dkimCheck == 1: - DNS.createDKIMRecords(virtualHostName) + postFixPath = '/home/cyberpanel/postfix' + + if os.path.exists(postFixPath): + if dkimCheck == 1: + DNS.createDKIMRecords(virtualHostName) logging.CyberCPLogFileWriter.statusWriter(tempStatusPath, 'Domain successfully created. [200]') diff --git a/plogical/website.py b/plogical/website.py index 98711f23d..1bf7aef67 100755 --- a/plogical/website.py +++ b/plogical/website.py @@ -36,6 +36,8 @@ from 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: @@ -156,12 +158,35 @@ class WebsiteManager: phpSelection = data['phpSelection'] packageName = data['package'] websiteOwner = data['websiteOwner'] + + if not match(r'([\da-z\.-]+\.[a-z\.]{2,12}|[\d\.]+)([\/:?=&#]{1}[\da-z\.-]+)*[\/\?]?', 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: @@ -171,7 +196,6 @@ class WebsiteManager: ## Create Configurations - execPath = "sudo /usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" execPath = execPath + " createVirtualHost --virtualHostName " + domain + \ " --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + \ @@ -205,6 +229,12 @@ class WebsiteManager: path = data['path'] tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + if not match(r'([\da-z\.-]+\.[a-z\.]{2,12}|[\d\.]+)([\/:?=&#]{1}[\da-z\.-]+)*[\/\?]?', 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: @@ -312,6 +342,12 @@ class WebsiteManager: 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" @@ -400,6 +436,12 @@ class WebsiteManager: 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) @@ -518,6 +560,12 @@ class WebsiteManager: 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" @@ -621,7 +669,6 @@ class WebsiteManager: else: Data['ftp'] = 0 - return render(request, 'websiteFunctions/website.html', Data) else: @@ -724,12 +771,11 @@ class WebsiteManager: 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) + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) if output.find("1,None") > -1: final_json = json.dumps( @@ -738,7 +784,6 @@ class WebsiteManager: ## get log ends here. - data = output.split("\n") json_data = "[" @@ -786,11 +831,12 @@ class WebsiteManager: 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) + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) if output.find("1,None") > -1: final_json = json.dumps( @@ -816,7 +862,7 @@ class WebsiteManager: filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" command = 'sudo cat ' + filePath - configData = ProcessUtilities.outputExecutioner(command) + configData = ProcessUtilities.outputExecutioner(command, 'lsadm') if len(configData) == 0: status = {'status': 0, "configstatus": 0, "error_message": "Configuration file is currently empty!"} @@ -921,7 +967,7 @@ class WebsiteManager: ## writing data temporary to file mailUtilities.checkHome() - tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + tempPath = "/tmp/" + str(randint(1000, 9999)) vhost = open(tempPath, "w") vhost.write(rewriteRules) vhost.close() @@ -931,17 +977,21 @@ class WebsiteManager: 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) + 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) @@ -967,7 +1017,6 @@ class WebsiteManager: ## writing data temporary to file - tempKeyPath = "/home/cyberpanel/" + str(randint(1000, 9999)) vhost = open(tempKeyPath, "w") vhost.write(key) @@ -1039,12 +1088,16 @@ class WebsiteManager: 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) + f = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + CronUtil.CronPrem(0) if f.find("0,CyberPanel,") > -1: data_ret = {'getWebsiteCron': 0, "user": website.externalApp, "crons": {}} @@ -1099,9 +1152,12 @@ class WebsiteManager: website = Websites.objects.get(domain=self.domain) try: - # f = subprocess.check_output(["sudo", "cat", cronPath]) - f = ProcessUtilities.outputExecutioner(["sudo", "/usr/bin/crontab", "-u", website.externalApp, "-l"]) - print f + 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) @@ -1110,11 +1166,6 @@ class WebsiteManager: f = f.split("\n") cron = f[line] - if not cron: - dic = {'getWebsiteCron': 0, 'error_message': 'Cron line empty'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - cron = cron.split(" ", 5) if len(cron) != 6: dic = {'getWebsiteCron': 0, 'error_message': 'Cron line incorrect'} @@ -1154,7 +1205,7 @@ class WebsiteManager: monthday = data['monthday'] month = data['month'] weekday = data['weekday'] - command = data['command'] + command = data['cronCommand'] if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: pass @@ -1165,10 +1216,13 @@ class WebsiteManager: 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) + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + CronUtil.CronPrem(0) if output.find("1,") > -1: data_ret = {"getWebsiteCron": 1, @@ -1202,10 +1256,14 @@ class WebsiteManager: 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) + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + CronUtil.CronPrem(0) if output.find("1,") > -1: data_ret = {"remCronbyLine": 1, @@ -1237,7 +1295,7 @@ class WebsiteManager: monthday = data['monthday'] month = data['month'] weekday = data['weekday'] - command = data['command'] + command = data['cronCommand'] if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: pass @@ -1246,13 +1304,25 @@ class WebsiteManager: 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) + output = ProcessUtilities.outputExecutioner(execPath, website.externalApp) + + CronUtil.CronPrem(0) if output.find("1,") > -1: + data_ret = {"addNewCron": 1, "user": website.externalApp, "cron": finalCron} @@ -1279,6 +1349,12 @@ class WebsiteManager: aliasDomain = data['aliasDomain'] ssl = data['ssl'] + if not match(r'([\da-z\.-]+\.[a-z\.]{2,12}|[\d\.]+)([\/:?=&#]{1}[\da-z\.-]+)*[\/\?]?', 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: @@ -1449,7 +1525,7 @@ class WebsiteManager: extraArgs['home'] = data['home'] extraArgs['blogTitle'] = data['blogTitle'] extraArgs['adminUser'] = data['adminUser'] - extraArgs['adminPassword'] = data['adminPassword'] + extraArgs['adminPassword'] = data['passwordByPass'] extraArgs['adminEmail'] = data['adminEmail'] extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) @@ -1541,16 +1617,17 @@ class WebsiteManager: sitename = data['sitename'] username = data['username'] - password = data['password'] + password = data['passwordByPass'] prefix = data['prefix'] mailUtilities.checkHome() - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + tempStatusPath = "/tmp/" + str(randint(1000, 9999)) statusFile = open(tempStatusPath, 'w') statusFile.writelines('Setting up paths,0') statusFile.close() + os.chmod(tempStatusPath, 0777) finalPath = "" @@ -1585,8 +1662,6 @@ class WebsiteManager: ## - - try: website = ChildDomains.objects.get(domain=domainName) externalApp = website.master.externalApp @@ -1655,14 +1730,12 @@ class WebsiteManager: # return execPath - - ProcessUtilities.popenExecutioner(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, msg: @@ -1675,11 +1748,12 @@ class WebsiteManager: 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.loadError() + return ACLManager.loadErrorJson() path = '/home/cyberpanel/' + self.domain + '.git' @@ -1695,30 +1769,28 @@ class WebsiteManager: {'domainName': self.domain, 'installed': 1, 'webhookURL': webhookURL}) else: - command = "sudo ssh-keygen -f /root/.ssh/git -t rsa -N ''" - ProcessUtilities.executioner(command) + 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 /root/.ssh/git -Host gitlab.com - IdentityFile /root/.ssh/git -""" +IdentityFile /home/%s/.ssh/%s +""" % (self.domain, website.externalApp) path = "/home/cyberpanel/config" writeToFile = open(path, 'w') writeToFile.writelines(configContent) writeToFile.close() - command = 'sudo mv ' + path + ' /root/.ssh/config' + command = 'mv %s /home/%s/.ssh/config' % (path, self.domain) ProcessUtilities.executioner(command) - command = 'sudo chown root:root /root/.ssh/config' + command = 'sudo chown %s:%s /home/%s/.ssh/config' % (website.externalApp, website.externalApp, self.domain) ProcessUtilities.executioner(command) - command = 'sudo cat /root/.ssh/git.pub' - deploymentKey = ProcessUtilities.outputExecutioner(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}) @@ -1887,7 +1959,7 @@ Host gitlab.com extraArgs['lastName'] = data['lastName'] extraArgs['databasePrefix'] = data['databasePrefix'] extraArgs['email'] = data['email'] - extraArgs['password'] = data['password'] + extraArgs['password'] = data['passwordByPass'] extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) if data['home'] == '0': @@ -2064,8 +2136,6 @@ Host gitlab.com except: pass - - self.domain = data['domainName'] if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: @@ -2156,7 +2226,8 @@ Host gitlab.com 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.'} + 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) @@ -2207,3 +2278,48 @@ Host gitlab.com 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, 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) + + 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, msg: + data_ret = {'status': 0, 'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) diff --git a/requirments.txt b/requirments.txt index beea9ea4d..e4e5e0e04 100755 --- a/requirments.txt +++ b/requirments.txt @@ -1,6 +1,7 @@ acme==0.21.1 asn1crypto==0.24.0 Babel==0.9.6 +bcrypt==3.1.7 backports.ssl-match-hostname==3.5.0.1 boto3==1.9.64 botocore==1.12.64 diff --git a/s3Backups/s3Backups.py b/s3Backups/s3Backups.py index b2ed7d743..45f203d68 100755 --- a/s3Backups/s3Backups.py +++ b/s3Backups/s3Backups.py @@ -20,12 +20,15 @@ try: from plogical.processUtilities import ProcessUtilities from websiteFunctions.models import Websites, Backups from plogical.virtualHostUtilities import virtualHostUtilities + from multiprocessing import Process + import plogical.backupUtilities as backupUtil except: import threading as multi from random import randint import json import requests import subprocess, shlex + from multiprocessing import Process class S3Backups(multi.Thread): @@ -426,11 +429,9 @@ class S3Backups(multi.Thread): ## /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 ' + virtualHost - - ProcessUtilities.popenExecutioner(execPath) + p = Process(target=backupUtil.submitBackupCreation, + args=(tempStoragePath, backupName, backupPath, virtualHost)) + p.start() time.sleep(2) diff --git a/serverStatus/serverStatusUtil.py b/serverStatus/serverStatusUtil.py index d3c80dcd8..a31d158ff 100755 --- a/serverStatus/serverStatusUtil.py +++ b/serverStatus/serverStatusUtil.py @@ -103,6 +103,13 @@ class ServerStatusUtil: except: pass + + files = ['/usr/local/lsws/conf/httpd_config.xml', '/usr/local/lsws/conf/modsec.conf', '/usr/local/lsws/conf/httpd.conf'] + for items in files: + command = 'chmod 644 %s' % (items) + ServerStatusUtil.executioner(command, statusFile) + + return 1 except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg)) @@ -310,10 +317,10 @@ class ServerStatusUtil: "LiteSpeed Enterprise Web Server installed.\n", 1) - if ServerStatusUtil.setupFileManager(statusFile) == 0: - logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, "Failed to set up File Manager. [404]", 1) - ServerStatusUtil.recover() - return 0 + # if ServerStatusUtil.setupFileManager(statusFile) == 0: + # logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, "Failed to set up File Manager. [404]", 1) + # ServerStatusUtil.recover() + # return 0 logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, "Rebuilding vhost conf..\n", 1) diff --git a/serverStatus/static/serverStatus/serverStatus.js b/serverStatus/static/serverStatus/serverStatus.js index c31727c0c..db70955a0 100755 --- a/serverStatus/static/serverStatus/serverStatus.js +++ b/serverStatus/static/serverStatus/serverStatus.js @@ -390,11 +390,18 @@ app.controller('servicesManager', function ($scope, $http) { url = "/serverstatus/servicesStatus"; - $http.post(url).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + data = {}; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { - console.log(response.data) if (response.data.status.litespeed) { $scope.olsStatus = "Running"; diff --git a/serverStatus/templates/serverStatus/litespeedStatus.html b/serverStatus/templates/serverStatus/litespeedStatus.html index 9c3960b41..7125fa8a0 100755 --- a/serverStatus/templates/serverStatus/litespeedStatus.html +++ b/serverStatus/templates/serverStatus/litespeedStatus.html @@ -11,19 +11,20 @@ {% if OLS %}
    -

    {% trans "LiteSpeed Status:" %}

    +

    {% trans "LiteSpeed Status:" %}

    {% trans "On this page you can get information regarding your LiteSpeed processes." %}

    -
    + {% if processList %} +
    -
    +
    - {% if processList %}

    {% trans "LiteSpeed Processes" %} @@ -59,47 +60,44 @@ - {% else %} -
    -

    {% trans "Could not fetch details, either LiteSpeed is not running or some error occurred, please see CyberPanel Main log file." %}

    + +
    + + +
    - {% endif %} -
    - - -
    - - + -
    -

    {% trans "Action successful." %}

    -
    +
    +

    {% trans "Action successful." %}

    +
    -
    -

    {% trans "Error Occurred. See CyberPanel main log file." %}

    -
    +
    +

    {% trans "Error Occurred. See CyberPanel main log file." %}

    +
    + + +
    +

    {% trans "Could not connect to server." %}

    +
    -
    -

    {% trans "Could not connect to server." %}

    - - -

    + {% endif %}
    @@ -133,67 +131,69 @@
    -
    -
    -
    -

    - {% trans "Switch to LiteSpeed Enterprise Web Server" %} -

    +
    +
    +
    +

    + {% trans "Switch to LiteSpeed Enterprise Web Server" %} +

    -
    -
    -
    +
    +
    +
    -
    + -
    - -
    - +
    + +
    + +
    -
    -
    - -
    - +
    + +
    + +
    -
    - -
    + +
    - + -
    +
    -
    -
    -
    -

    {% trans "With great wisdom comes great responsibility." %} -

    -
    -
    + +
    +
    +

    {% trans "With great wisdom comes great responsibility." %} + +

    +
    +
    +
    -
    - + +
    + + + + +
    - - - - -
    -
    {% else %} @@ -204,14 +204,14 @@

    {% trans "LiteSpeed Status:" %}

    {% trans "On this page you can get information regarding your LiteSpeed processes." %}

    + {% if processList %} -
    -
    -
    -
    -
    +
    +
    +
    +
    +
    - {% if processList %}

    {% trans "LiteSpeed Processes" %} @@ -247,47 +247,44 @@ - {% else %} -
    -

    {% trans "Could not fetch details, either LiteSpeed is not running or some error occurred, please see CyberPanel Main log file." %}

    + + + + + + + + + +
    +

    {% trans "Action successful." %}

    - {% endif %} - - - - - - -
    -

    {% trans "Action successful." %}

    +
    +

    {% trans "Error Occurred. See CyberPanel main log file." %}

    +
    + + +
    +

    {% trans "Could not connect to server." %}

    +
    +
    - - -
    -

    {% trans "Error Occurred. See CyberPanel main log file." %}

    -
    - - -
    -

    {% trans "Could not connect to server." %}

    -
    -

    -
    + {% endif %}
    diff --git a/serverStatus/views.py b/serverStatus/views.py index 7cfda4cd5..0d9bb8fc8 100755 --- a/serverStatus/views.py +++ b/serverStatus/views.py @@ -186,6 +186,12 @@ def services(request): def servicesStatus(request): try: userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('serviceAction', 0) lsStatus = [] sqlStatus = [] @@ -384,7 +390,6 @@ def switchTOLSWSStatus(request): json_data = json.dumps(data_ret) return HttpResponse(json_data) - def licenseStatus(request): try: userID = request.session['userID'] @@ -484,6 +489,13 @@ def topProcesses(request): def topProcessesStatus(request): try: + userID = request.session['userID'] + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() with open("/home/cyberpanel/top", "w") as outfile: subprocess.call("top -n1 -b", shell=True, stdout=outfile) diff --git a/static/CLManager/CLManager.js b/static/CLManager/CLManager.js new file mode 100644 index 000000000..547a407d5 --- /dev/null +++ b/static/CLManager/CLManager.js @@ -0,0 +1,934 @@ +app.controller('installCageFS', function ($scope, $http, $timeout, $window) { + + $scope.installDockerStatus = true; + $scope.installBoxGen = true; + $scope.dockerInstallBTN = false; + + $scope.submitCageFSInstall = function () { + + $scope.installDockerStatus = false; + $scope.installBoxGen = true; + $scope.dockerInstallBTN = true; + + url = "/CloudLinux/submitCageFSInstall"; + + var data = {}; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + $scope.installBoxGen = false; + getRequestStatus(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + + function getRequestStatus() { + $scope.cyberPanelLoading = false; + + url = "/serverstatus/switchTOLSWSStatus"; + + var data = {}; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + if (response.data.abort === 0) { + $scope.requestData = response.data.requestStatus; + $timeout(getRequestStatus, 1000); + } else { + // Notifications + $scope.cyberPanelLoading = true; + $timeout.cancel(); + $scope.requestData = response.data.requestStatus; + if (response.data.installed === 1) { + $timeout(function () { + $window.location.reload(); + }, 3000); + } + + } + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + + + } + + } +}); + +app.controller('listWebsitesCage', function ($scope, $http) { + + var globalPageNumber; + $scope.getFurtherWebsitesFromDB = function (pageNumber) { + $scope.cyberPanelLoading = false; + globalPageNumber = pageNumber; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = {page: pageNumber}; + + + dataurl = "/CloudLinux/submitWebsiteListing"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + $scope.cyberPanelLoading = true; + if (response.data.listWebSiteStatus === 1) { + var finalData = JSON.parse(response.data.data); + $scope.WebSitesList = finalData; + $scope.pagination = response.data.pagination; + $scope.default = response.data.default; + $("#listFail").hide(); + } else { + $("#listFail").fadeIn(); + $scope.errorMessage = response.data.error_message; + console.log(response.data); + + } + } + + function cantLoadInitialData(response) { + $scope.cyberPanelLoading = true; + console.log("not good"); + } + + + }; + $scope.getFurtherWebsitesFromDB(1); + + $scope.cyberPanelLoading = true; + + $scope.searchWebsites = function () { + + $scope.cyberPanelLoading = false; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = { + patternAdded: $scope.patternAdded + }; + + dataurl = "/websites/searchWebsites"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + $scope.cyberPanelLoading = true; + if (response.data.listWebSiteStatus === 1) { + + var finalData = JSON.parse(response.data.data); + $scope.WebSitesList = finalData; + $("#listFail").hide(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + + } + } + + function cantLoadInitialData(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Connect disrupted, refresh the page.', + type: 'error' + }); + } + + + }; + + $scope.enableOrDisable = function (domain, all, mode, toggle = 0) { + $scope.cyberPanelLoading = false; + + url = "/CloudLinux/enableOrDisable"; + + var data = { + domain: domain, + all: all, + mode: mode, + toggle: toggle + }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: response.data.success, + type: 'success' + }); + + if (all === 0) { + $scope.getFurtherWebsitesFromDB(globalPageNumber); + } + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + + $scope.refreshStatus = function () { + $scope.getFurtherWebsitesFromDB(globalPageNumber); + } + + +}); + +app.controller('createCLPackage', function ($scope, $http) { + + $scope.cyberPanelLoading = true; + $scope.modifyPackageForm = true; + $scope.toggleView = function () { + $scope.modifyPackageForm = false; + }; + + $scope.createPackage = function () { + $scope.cyberPanelLoading = false; + + url = "/CloudLinux/submitCreatePackage"; + + var data = { + selectedPackage: $scope.selectedPackage, + name: $scope.name, + SPEED: $scope.SPEED, + VMEM: $scope.VMEM, + PMEM: $scope.PMEM, + IO: $scope.IO, + IOPS: $scope.IOPS, + EP: $scope.EP, + NPROC: $scope.NPROC, + INODESsoft: $scope.INODESsoft, + INODEShard: $scope.INODEShard, + }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully created.', + type: 'success' + }); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + +}); + +app.controller('listCloudLinuxPackages', function ($scope, $http) { + + $scope.cyberPanelLoading = true; + + $scope.fetchPackageas = function () { + $scope.cyberPanelLoading = false; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + var data = {}; + + + dataurl = "/CloudLinux/fetchPackages"; + + $http.post(dataurl, data, config).then(ListInitialData, cantLoadInitialData); + + + function ListInitialData(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + $scope.packages = JSON.parse(response.data.data); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + } + + function cantLoadInitialData(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + + }; + $scope.fetchPackageas(); + + $scope.deleteCLPackage = function (name) { + $scope.cyberPanelLoading = false; + + url = "/CloudLinux/deleteCLPackage"; + + var data = { + name: name + }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Successfully deleted.', + type: 'success' + }); + $scope.fetchPackageas(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + $scope.populatePackage = function (name, speed, vmem, pmem, io, iops, ep, nproc, inodessoft, inodeshard) { + $scope.name = name; + $scope.SPEED = speed; + $scope.VMEM = vmem; + $scope.PMEM = pmem; + $scope.IO = io; + $scope.IOPS = iops; + $scope.EP = ep; + $scope.NPROC = nproc; + $scope.inodessoft = inodessoft; + $scope.inodeshard = inodeshard; + + }; + + $scope.saveSettings = function () { + $scope.cyberPanelLoading = false; + + url = "/CloudLinux/saveSettings"; + + var data = { + name: $scope.name, + SPEED: $scope.SPEED, + VMEM: $scope.VMEM, + PMEM: $scope.PMEM, + IO: $scope.IO, + IOPS: $scope.IOPS, + EP: $scope.EP, + NPROC: $scope.NPROC, + INODESsoft: $scope.inodessoft, + INODEShard: $scope.inodeshard, + }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.cyberPanelLoading = true; + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Changes successfully applied.', + type: 'success' + }); + $scope.fetchPackageas(); + } else { + new PNotify({ + title: 'Operation Failed!', + text: response.data.error_message, + type: 'error' + }); + } + + } + + function cantLoadInitialDatas(response) { + $scope.cyberPanelLoading = true; + new PNotify({ + title: 'Operation Failed!', + text: 'Could not connect to server, please refresh this page', + type: 'error' + }); + } + + }; + +}); + + +app.controller('websiteContainerLimitCL', function ($scope, $http, $timeout, $window) { + + + // Get CPU Usage of User + + var cpu = []; + var dataset; + var totalPoints = 100; + var updateInterval = 1000; + var now = new Date().getTime(); + + var options = { + series: { + lines: { + lineWidth: 1.2 + }, + bars: { + align: "center", + fillColor: {colors: [{opacity: 1}, {opacity: 1}]}, + barWidth: 500, + lineWidth: 1 + } + }, + xaxis: { + mode: "time", + tickSize: [5, "second"], + tickFormatter: function (v, axis) { + var date = new Date(v); + + if (date.getSeconds() % 20 == 0) { + var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); + var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); + var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); + + return hours + ":" + minutes + ":" + seconds; + } else { + return ""; + } + }, + axisLabel: "Time", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 10 + }, + yaxes: [ + { + min: 0, + max: 100, + tickSize: 5, + tickFormatter: function (v, axis) { + if (v % 10 == 0) { + return v + "%"; + } else { + return ""; + } + }, + axisLabel: "CPU loading", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + }, { + max: 5120, + position: "right", + axisLabel: "Disk", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + } + ], + legend: { + noColumns: 0, + position: "nw" + }, + grid: { + backgroundColor: {colors: ["#ffffff", "#EDF5FF"]} + } + }; + + function initData() { + for (var i = 0; i < totalPoints; i++) { + var temp = [now += updateInterval, 0]; + + cpu.push(temp); + } + } + + function GetData() { + + var data = { + domain: $("#domain").text() + }; + $.ajaxSetup({cache: false}); + + $.ajax({ + url: "/CloudLinux/getUsageData", + dataType: 'json', + success: update, + type: "POST", + headers: {'X-CSRFToken': getCookie('csrftoken')}, + contentType: "application/json", + data: JSON.stringify(data), // Our valid JSON string + error: function () { + setTimeout(GetData, updateInterval); + } + }); + } + + var temp; + + function update(_data) { + cpu.shift(); + + now += updateInterval; + + temp = [now, _data.cpu]; + cpu.push(temp); + + + dataset = [ + {label: "CPU:" + _data.cpu + "%", data: cpu, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"} + ]; + + $.plot($("#flot-placeholder1"), dataset, options); + setTimeout(GetData, updateInterval); + } + + // Memory Usage of User + + var memory = []; + var datasetMemory; + var totalPointsMemory = 100; + var updateIntervalMemory = 1000; + var nowMemory = new Date().getTime(); + + var optionsMemory = { + series: { + lines: { + lineWidth: 1.2 + }, + bars: { + align: "center", + fillColor: {colors: [{opacity: 1}, {opacity: 1}]}, + barWidth: 500, + lineWidth: 1 + } + }, + xaxis: { + mode: "time", + tickSize: [5, "second"], + tickFormatter: function (v, axis) { + var date = new Date(v); + + if (date.getSeconds() % 20 == 0) { + var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); + var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); + var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); + + return hours + ":" + minutes + ":" + seconds; + } else { + return ""; + } + }, + axisLabel: "Time", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 10 + }, + yaxes: [ + { + min: 0, + max: $scope.memory, + tickSize: 5, + tickFormatter: function (v, axis) { + if (v % 10 == 0) { + return v + "MB"; + } else { + return ""; + } + }, + axisLabel: "CPU loading", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + }, { + max: 5120, + position: "right", + axisLabel: "Disk", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + } + ], + legend: { + noColumns: 0, + position: "nw" + }, + grid: { + backgroundColor: {colors: ["#ffffff", "#EDF5FF"]} + } + }; + + function initDataMemory() { + for (var i = 0; i < totalPointsMemory; i++) { + var temp = [nowMemory += updateIntervalMemory, 0]; + + memory.push(temp); + } + } + + function GetDataMemory() { + + var data = { + domain: $("#domain").text(), + type: 'memory' + }; + $.ajaxSetup({cache: false}); + + $.ajax({ + url: "/CloudLinux/getUsageData", + dataType: 'json', + headers: {'X-CSRFToken': getCookie('csrftoken')}, + success: updateMemory, + type: "POST", + contentType: "application/json", + data: JSON.stringify(data), // Our valid JSON string + error: function () { + setTimeout(GetDataMemory, updateIntervalMemory); + } + }); + } + + var tempMemory; + + function updateMemory(_data) { + memory.shift(); + + nowMemory += updateIntervalMemory; + + tempMemory = [nowMemory, _data.memory]; + memory.push(tempMemory); + + + datasetMemory = [ + { + label: "Memory:" + _data.memory + "MB", + data: memory, + lines: {fill: true, lineWidth: 1.2}, + color: "#00FF00" + } + ]; + + $.plot($("#memoryUsage"), datasetMemory, optionsMemory); + setTimeout(GetDataMemory, updateIntervalMemory); + } + + // Disk Usage + + var readRate = [], writeRate = []; + var datasetDisk; + var totalPointsDisk = 100; + var updateIntervalDisk = 5000; + var now = new Date().getTime(); + + var optionsDisk = { + series: { + lines: { + lineWidth: 1.2 + }, + bars: { + align: "center", + fillColor: {colors: [{opacity: 1}, {opacity: 1}]}, + barWidth: 500, + lineWidth: 1 + } + }, + xaxis: { + mode: "time", + tickSize: [30, "second"], + tickFormatter: function (v, axis) { + var date = new Date(v); + + if (date.getSeconds() % 20 == 0) { + var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); + var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); + var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); + + return hours + ":" + minutes + ":" + seconds; + } else { + return ""; + } + }, + axisLabel: "Time", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 10 + }, + yaxes: [ + { + min: 0, + max: $scope.networkSpeed, + tickSize: 5, + tickFormatter: function (v, axis) { + if (v % 10 == 0) { + return v + "mb/sec"; + } else { + return ""; + } + }, + axisLabel: "CPU loading", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + }, { + max: 5120, + position: "right", + axisLabel: "Disk", + axisLabelUseCanvas: true, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 6 + } + ], + legend: { + noColumns: 0, + position: "nw" + }, + grid: { + backgroundColor: {colors: ["#ffffff", "#EDF5FF"]} + } + }; + + function initDataDisk() { + for (var i = 0; i < totalPointsDisk; i++) { + var temp = [now += updateIntervalDisk, 0]; + + readRate.push(temp); + writeRate.push(temp); + } + } + + function GetDataDisk() { + + var data = { + domain: $("#domain").text(), + type: 'io' + }; + + $.ajaxSetup({cache: false}); + + $.ajax({ + url: "/CloudLinux/getUsageData", + dataType: 'json', + headers: {'X-CSRFToken': getCookie('csrftoken')}, + success: updateDisk, + type: "POST", + contentType: "application/json", + data: JSON.stringify(data), // Our valid JSON string + error: function () { + setTimeout(GetDataMemory, updateIntervalMemory); + } + }); + } + + var tempDisk; + + function updateDisk(_data) { + readRate.shift(); + writeRate.shift(); + + now += updateIntervalDisk; + + tempDisk = [now, _data.readRate]; + readRate.push(tempDisk); + + tempDisk = [now, _data.readRate]; + writeRate.push(tempDisk); + + datasetDisk = [ + { + label: "Read IO/s " + _data.readRate + " mb/s ", + data: readRate, + lines: {fill: true, lineWidth: 1.2}, + color: "#00FF00" + }, + { + label: "Write IO/s " + _data.writeRate + " mb/s ", + data: writeRate, + lines: {lineWidth: 1.2}, + color: "#FF0000" + } + ]; + + $.plot($("#diskUsage"), datasetDisk, optionsDisk); + setTimeout(GetDataDisk, updateIntervalDisk); + } + + + $(document).ready(function () { + + // Report Memory Usage + + initDataMemory(); + + datasetMemory = [ + {label: "Memory", data: memory, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"} + ]; + + $.plot($("#memoryUsage"), datasetMemory, optionsMemory); + setTimeout(GetDataMemory, updateIntervalMemory); + + // Report CPU Usage + + initData(); + + dataset = [ + {label: "CPU", data: cpu, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"} + ]; + + $.plot($("#flot-placeholder1"), dataset, options); + setTimeout(GetData, updateInterval); + + // Report Disk Usage + + initDataDisk(); + + datasetDisk = [ + {label: "Read IO/s: ", data: readRate, lines: {fill: true, lineWidth: 1.2}, color: "#00FF00"}, + {label: "Write IO/s: ", data: writeRate, color: "#0044FF", bars: {show: true}, yaxis: 2} + ]; + + $.plot($("#diskUsage"), datasetDisk, optionsDisk); + setTimeout(GetDataDisk, updateIntervalDisk); + }); +}); \ 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 134e67021..1bf3b0d8f 100644 --- a/static/baseTemplate/custom-js/system-status.js +++ b/static/baseTemplate/custom-js/system-status.js @@ -23,7 +23,7 @@ function getCookie(name) { } function randomPassword(length) { - var chars = "abcdefghijklmnopqrstuvwxyz!@#$%^*()-+<>ABCDEFGHIJKLMNOP1234567890"; + var chars = "abcdefghijklmnopqrstuvwxyz!@#%^*-+ABCDEFGHIJKLMNOP1234567890"; var pass = ""; for (var x = 0; x < length; x++) { var i = Math.floor(Math.random() * chars.length); diff --git a/static/containerization/containerization.js b/static/containerization/containerization.js old mode 100755 new mode 100644 index f0fad7a03..5f4e6b5c0 --- a/static/containerization/containerization.js +++ b/static/containerization/containerization.js @@ -200,6 +200,7 @@ app.controller('websiteContainerLimit', function ($scope, $http, $timeout, $wind dataType: 'json', success: update, type: "POST", + headers: { 'X-CSRFToken': getCookie('csrftoken') }, contentType: "application/json", data: JSON.stringify(data), // Our valid JSON string error: function () { @@ -324,6 +325,7 @@ app.controller('websiteContainerLimit', function ($scope, $http, $timeout, $wind $.ajax({ url: "/container/getUsageData", dataType: 'json', + headers: { 'X-CSRFToken': getCookie('csrftoken') }, success: updateMemory, type: "POST", contentType: "application/json", @@ -457,6 +459,7 @@ app.controller('websiteContainerLimit', function ($scope, $http, $timeout, $wind $.ajax({ url: "/container/getUsageData", dataType: 'json', + headers: { 'X-CSRFToken': getCookie('csrftoken') }, success: updateDisk, type: "POST", contentType: "application/json", diff --git a/static/filemanager/js/fileManager.js b/static/filemanager/js/fileManager.js old mode 100755 new mode 100644 index a76ebcb04..e21eafd01 --- a/static/filemanager/js/fileManager.js +++ b/static/filemanager/js/fileManager.js @@ -1,3 +1,20 @@ +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; +} + + var fileManager = angular.module('fileManager', ['angularFileUpload']); fileManager.config(['$interpolateProvider', function ($interpolateProvider) { @@ -5,6 +22,7 @@ fileManager.config(['$interpolateProvider', function ($interpolateProvider) { $interpolateProvider.endSymbol('$}'); }]); + fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, $window) { $(document.body).click(function () { @@ -58,8 +76,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (functionName === "primary") { nodeForChilds = element.currentTarget.parentNode; funcCompletePath = completePath; - } - else { + } else { nodeForChilds = element.parentNode; funcCompletePath = completePath; } @@ -74,7 +91,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -95,8 +119,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, for (var i = 0; i < keys.length; i++) { if (keys[i] === "error_message" | keys[i] === "status") { continue; - } - else { + } else { path = filesData[keys[i]][0]; completePath = filesData[keys[i]][1]; dropDown = filesData[keys[i]][2]; @@ -105,8 +128,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, } activateMinus(nodeForChilds, funcCompletePath); - } - else { + } else { } } @@ -185,8 +207,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, liNode.appendChild(secondANode); return liNode; - } - else { + } else { liNode.appendChild(iNodeFile); liNode.appendChild(pathNode); return liNode; @@ -430,8 +451,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var fileOrFolderNode = document.createTextNode("Folder"); fifthTDNode.appendChild(fileOrFolderNode) - } - else { + } else { thNode.appendChild(iNodeFile); trNode.appendChild(thNode); trNode.addEventListener("click", function () { @@ -475,40 +495,32 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (result[0] === "js") { aceEditorMode = "ace/mode/javascript"; editNotRight.style.display = "Block"; - } - else if (result[0] === "html") { + } else if (result[0] === "html") { aceEditorMode = "ace/mode/html"; editNotRight.style.display = "Block"; - } - else if (result[0] === "css") { + } else if (result[0] === "css") { aceEditorMode = "ace/mode/css"; editNotRight.style.display = "Block"; - } - else if (result[0] === "php") { + } else if (result[0] === "php") { aceEditorMode = "ace/mode/php"; editNotRight.style.display = "Block"; - } - else if (result[0] === "txt") { + } else if (result[0] === "txt") { aceEditorMode = ""; editNotRight.style.display = "Block"; - } - else if (result[0] === "htaccess") { + } else if (result[0] === "htaccess") { aceEditorMode = ""; editNotRight.style.display = "Block"; - } - else { + } else { var editNode = document.getElementById("editFile"); editNode.style.pointerEvents = "none"; editNotRight.style.display = "None"; } - } - else { + } else { var editNode = document.getElementById("editFile"); editNode.style.pointerEvents = "none"; editNotRight.style.display = "None"; } - } - else { + } else { var editNode = document.getElementById("editFile"); editNode.style.pointerEvents = "none"; } @@ -527,21 +539,18 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (result[0] === "gz") { extractFileNode.style.pointerEvents = "auto"; extractNodeRight.style.display = "Block"; - } - else if (result[0] === "zip") { + } else if (result[0] === "zip") { extractFileNode.style.pointerEvents = "auto"; extractNodeRight.style.display = "Block"; } else { extractFileNode.style.pointerEvents = "none"; extractNodeRight.style.display = "None"; } - } - else { + } else { extractFileNode.style.pointerEvents = "none"; extractNodeRight.style.display = "None"; } - } - else { + } else { var extractFileNode = document.getElementById("extractFile"); extractFileNode.style.pointerEvents = "none"; } @@ -553,8 +562,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var moveFileNode = document.getElementById("moveFile"); moveFileNode.style.pointerEvents = "auto"; - } - else { + } else { var moveFileNode = document.getElementById("moveFile"); moveFileNode.style.pointerEvents = "none"; } @@ -565,8 +573,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var copeFileNode = document.getElementById("copyFile"); copeFileNode.style.pointerEvents = "auto"; - } - else { + } else { var copeFileNode = document.getElementById("copyFile"); copeFileNode.style.pointerEvents = "none"; } @@ -578,8 +585,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var renameFileNode = document.getElementById("renameFile"); renameFileNode.style.pointerEvents = "auto"; - } - else { + } else { var renameFileNode = document.getElementById("renameFile"); renameFileNode.style.pointerEvents = "none"; } @@ -590,8 +596,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (allFilesAndFolders.length >= 1) { var compressFile = document.getElementById("compressFile"); compressFile.style.pointerEvents = "auto"; - } - else { + } else { var compressFile = document.getElementById("compressFile"); compressFile.style.pointerEvents = "none"; } @@ -603,8 +608,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var deleteFile = document.getElementById("deleteFile"); deleteFile.style.pointerEvents = "auto"; - } - else { + } else { var deleteFile = document.getElementById("deleteFile"); deleteFile.style.pointerEvents = "none"; } @@ -625,22 +629,17 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (functionName === "startPoint") { completePathToFile = $scope.currentPath; - } - else if (functionName === "doubleClick") { + } else if (functionName === "doubleClick") { completePathToFile = $scope.currentPath + "/" + node.innerHTML; - } - else if (functionName === "homeFetch") { + } else if (functionName === "homeFetch") { completePathToFile = homePathBack; - } - else if (functionName === "goBackOnPath") { + } else if (functionName === "goBackOnPath") { var pos = $scope.currentPath.lastIndexOf("/"); completePathToFile = $scope.currentPath.slice(0, pos); - } - else if (functionName === "refresh") { + } else if (functionName === "refresh") { completePathToFile = $scope.currentPath; var rightClickNode = document.getElementById("rightClick"); - } - else if (functionName === "fromTree") { + } else if (functionName === "fromTree") { completePathToFile = arguments[2]; } @@ -659,7 +658,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, tableBody.innerHTML = ''; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -678,8 +684,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, for (var i = 0; i < keys.length; i++) { if (keys[i] === "error_message" | keys[i] === "status") { continue; - } - else { + } else { var fileName = filesData[keys[i]][0]; var lastModified = filesData[keys[i]][2]; var fileSize = filesData[keys[i]][3]; @@ -694,8 +699,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, } } - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 10, function () { }); $scope.fetchForTableSecondary(null, 'homeFetch'); @@ -711,6 +715,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, function findFileExtension(fileName) { return (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName) : undefined; } + $scope.fetchForTableSecondary(null, "startPoint"); // html editor @@ -727,8 +732,15 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, domainName: domainName }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -741,8 +753,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, editor.getSession().setMode(aceEditorMode); editor.setValue(response.data.fileContents); - } - else { + } else { $scope.errorMessageEditor = false; $scope.error_message = response.data.error_message; } @@ -771,7 +782,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -780,8 +798,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (response.data.status === 1) { $scope.htmlEditorLoading = true; $scope.saveSuccess = false; - } - else { + } else { $scope.errorMessageEditor = false; $scope.error_message = response.data.error_message; } @@ -800,6 +817,9 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var uploader = $scope.uploader = new FileUploader({ url: "/filemanager/upload", + headers: { + 'X-CSRFToken': getCookie('csrftoken') // X-CSRF-TOKEN is used for Ruby on Rails Tokens + }, formData: [{ "method": "upload", "home": homePathBack @@ -810,8 +830,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (response.uploadStatus === 1) { $scope.errorMessage = true; $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { $scope.errorMessage = false; $scope.fileName = response.fileName; $scope.error_message = response.error_message; @@ -863,7 +882,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; var url = '/filemanager/controller'; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -871,8 +897,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, $scope.createSuccess = false; $scope.fetchForTableSecondary(null, 'refresh'); $('#showCreateFolder').modal('hide'); - } - else { + } else { $scope.errorMessageFolder = false; $scope.error_message = response.data.error_message; } @@ -915,7 +940,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -923,8 +955,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, $scope.createSuccess = false; $scope.fetchForTableSecondary(null, 'refresh'); $('#showCreateFile').modal('hide'); - } - else { + } else { $scope.errorMessageFile = false; $scope.error_message = response.data.error_message; } @@ -960,7 +991,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { $scope.deleteLoading = true; @@ -969,8 +1007,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var notification = alertify.notify('Successfully Deleted!', 'success', 5, function () { }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify('Files/Folders can not be deleted', 'error', 5, function () { console.log('dismissed'); }); @@ -1015,7 +1052,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -1025,8 +1069,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var notification = alertify.notify('Successfully Compressed!', 'success', 5, function () { }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 5, function () { }); } @@ -1058,8 +1101,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if (findFileExtension(completeFileToExtract) == "gz") { extractionType = "tar.gz"; - } - else { + } else { extractionType = "zip"; } @@ -1075,7 +1117,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -1087,8 +1136,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, console.log('dismissed'); }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 10, function () { console.log('dismissed'); }); @@ -1134,7 +1182,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -1145,8 +1200,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var notification = alertify.notify('Successfully Moved!', 'success', 5, function () { }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 5, function () { }); } @@ -1190,7 +1244,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { $scope.copyLoading = true; @@ -1201,8 +1262,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var notification = alertify.notify('Successfully Copied!', 'success', 5, function () { }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 5, function () { }); } @@ -1311,7 +1371,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -1323,8 +1390,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var notification = alertify.notify('Successfully Renamed!', 'success', 5, function () { }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 5, function () { }); } @@ -1351,7 +1417,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -1361,8 +1434,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, console.log('dismissed'); }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 5, function () { console.log('dismissed'); }); @@ -1410,8 +1482,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if ($scope.userRead === true) { $scope.userPermissions = $scope.userPermissions + 4; - } - else { + } else { if ($scope.userRead !== undefined) { $scope.userPermissions = $scope.userPermissions - 4; } @@ -1450,8 +1521,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if ($scope.userWrite === true) { $scope.userPermissions = $scope.userPermissions + 2; - } - else { + } else { if ($scope.userWrite !== undefined) { $scope.userPermissions = $scope.userPermissions - 2; } @@ -1490,8 +1560,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, if ($scope.userExecute === true) { $scope.userPermissions = $scope.userPermissions + 1; - } - else { + } else { if ($scope.userExecute !== undefined) { $scope.userPermissions = $scope.userPermissions - 1; } @@ -1544,7 +1613,14 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, }; - $http.post(url, data).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { @@ -1555,8 +1631,7 @@ fileManager.controller('fileManagerCtrl', function ($scope, $http, FileUploader, var notification = alertify.notify('Permissions Successfully Changed!', 'success', 5, function () { }); $scope.fetchForTableSecondary(null, 'refresh'); - } - else { + } else { var notification = alertify.notify(response.data.error_message, 'error', 5, function () { }); } diff --git a/static/ftp/ftp.js b/static/ftp/ftp.js old mode 100755 new mode 100644 index 88a7c3806..8e2d41bdf --- a/static/ftp/ftp.js +++ b/static/ftp/ftp.js @@ -4,7 +4,7 @@ /* Java script code to create account */ -app.controller('createFTPAccount', function($scope,$http) { +app.controller('createFTPAccount', function ($scope, $http) { $scope.ftpLoading = true; $scope.ftpDetails = true; @@ -12,7 +12,7 @@ app.controller('createFTPAccount', function($scope,$http) { $scope.successfullyCreated = true; $scope.couldNotConnect = true; - $scope.showFTPDetails = function(){ + $scope.showFTPDetails = function () { $scope.ftpLoading = true; $scope.ftpDetails = false; @@ -23,91 +23,84 @@ app.controller('createFTPAccount', function($scope,$http) { }; - $scope.createFTPAccount = function(){ + $scope.createFTPAccount = function () { - $scope.ftpLoading = false; + $scope.ftpLoading = false; + $scope.ftpDetails = false; + $scope.canNotCreate = true; + $scope.successfullyCreated = true; + $scope.couldNotConnect = true; + + var ftpDomain = $scope.ftpDomain; + var ftpUserName = $scope.ftpUserName; + var ftpPassword = $scope.ftpPassword; + var path = $scope.ftpPath; + + if (typeof path === 'undefined') { + path = ""; + } + + var url = "/ftp/submitFTPCreation"; + + + var data = { + ftpDomain: ftpDomain, + ftpUserName: ftpUserName, + passwordByPass: ftpPassword, + path: path, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.creatFTPStatus == 1) { + + $scope.ftpLoading = true; $scope.ftpDetails = false; $scope.canNotCreate = true; + $scope.successfullyCreated = false; + $scope.couldNotConnect = true; + + + } else { + $scope.ftpLoading = true; + $scope.ftpDetails = false; + $scope.canNotCreate = false; $scope.successfullyCreated = true; $scope.couldNotConnect = true; - var ftpDomain = $scope.ftpDomain; - var ftpUserName = $scope.ftpUserName; - var ftpPassword = $scope.ftpPassword; - var path = $scope.ftpPath; - - if (typeof path === 'undefined'){ - path = ""; - } - - var url = "/ftp/submitFTPCreation"; + $scope.errorMessage = response.data.error_message; - var data = { - ftpDomain:ftpDomain, - ftpUserName:ftpUserName, - ftpPassword:ftpPassword, - path:path, - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + } - function ListInitialDatas(response) { - - - if(response.data.creatFTPStatus == 1){ - - $scope.ftpLoading = true; - $scope.ftpDetails = false; - $scope.canNotCreate = true; - $scope.successfullyCreated = false; - $scope.couldNotConnect = true; - - - } - - else - { - $scope.ftpLoading = true; - $scope.ftpDetails = false; - $scope.canNotCreate = false; - $scope.successfullyCreated = true; - $scope.couldNotConnect = true; - - $scope.errorMessage = response.data.error_message; - - - } - - - - } - function cantLoadInitialDatas(response) { - - $scope.ftpLoading = true; - $scope.ftpDetails = false; - $scope.canNotCreate = true; - $scope.successfullyCreated = true; - $scope.couldNotConnect = false; - - - - } - + } + + function cantLoadInitialDatas(response) { + + $scope.ftpLoading = true; + $scope.ftpDetails = false; + $scope.canNotCreate = true; + $scope.successfullyCreated = true; + $scope.couldNotConnect = false; + } }; - $scope.hideFewDetails = function(){ + $scope.hideFewDetails = function () { $scope.successfullyCreated = true; @@ -119,8 +112,8 @@ app.controller('createFTPAccount', function($scope,$http) { $scope.generatedPasswordView = true; $scope.generatePassword = function () { - $scope.generatedPasswordView = false; - $scope.ftpPassword = randomPassword(12); + $scope.generatedPasswordView = false; + $scope.ftpPassword = randomPassword(12); }; $scope.usePassword = function () { @@ -134,7 +127,7 @@ app.controller('createFTPAccount', function($scope,$http) { /* Java script code to delete ftp account */ -app.controller('deleteFTPAccount', function($scope,$http) { +app.controller('deleteFTPAccount', function ($scope, $http) { $scope.ftpAccountsOfDomain = true; $scope.deleteFTPButton = true; @@ -143,7 +136,7 @@ app.controller('deleteFTPAccount', function($scope,$http) { $scope.couldNotConnect = true; $scope.deleteFTPButtonInit = true; - $scope.getFTPAccounts = function(){ + $scope.getFTPAccounts = function () { $scope.ftpAccountsOfDomain = true; $scope.deleteFTPButton = true; @@ -156,152 +149,138 @@ app.controller('deleteFTPAccount', function($scope,$http) { var url = "/ftp/fetchFTPAccounts"; - var data = { - ftpDomain:$scope.selectedDomain, - }; + var data = { + ftpDomain: $scope.selectedDomain, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus == 1){ + if (response.data.fetchStatus == 1) { - $scope.ftpAccountsFeteched = JSON.parse(response.data.data); - - $scope.ftpAccountsOfDomain = false; - $scope.deleteFTPButton = true; - $scope.deleteFailure = true; - $scope.deleteSuccess = true; - $scope.couldNotConnect = true; - $scope.deleteFTPButtonInit = false; - - - } - - else - { - - $scope.ftpAccountsOfDomain = true; - $scope.deleteFTPButton = true; - $scope.deleteFailure = true; - $scope.deleteSuccess = true; - $scope.couldNotConnect = false; - $scope.deleteFTPButtonInit = true; - - } - - - - } - function cantLoadInitialDatas(response) { - - $scope.ftpAccountsOfDomain = true; - $scope.deleteFTPButton = true; - $scope.deleteFailure = true; - $scope.deleteSuccess = true; - $scope.couldNotConnect = false; - $scope.deleteFTPButtonInit = true; - - - } - - - - - - }; - - $scope.deleteFTPAccount = function(){ + $scope.ftpAccountsFeteched = JSON.parse(response.data.data); $scope.ftpAccountsOfDomain = false; - $scope.deleteFTPButton = false; + $scope.deleteFTPButton = true; $scope.deleteFailure = true; $scope.deleteSuccess = true; $scope.couldNotConnect = true; $scope.deleteFTPButtonInit = false; + + } else { + + $scope.ftpAccountsOfDomain = true; + $scope.deleteFTPButton = true; + $scope.deleteFailure = true; + $scope.deleteSuccess = true; + $scope.couldNotConnect = false; + $scope.deleteFTPButtonInit = true; + + } + + + } + + function cantLoadInitialDatas(response) { + + $scope.ftpAccountsOfDomain = true; + $scope.deleteFTPButton = true; + $scope.deleteFailure = true; + $scope.deleteSuccess = true; + $scope.couldNotConnect = false; + $scope.deleteFTPButtonInit = true; + + + } + + + }; + + $scope.deleteFTPAccount = function () { + + $scope.ftpAccountsOfDomain = false; + $scope.deleteFTPButton = false; + $scope.deleteFailure = true; + $scope.deleteSuccess = true; + $scope.couldNotConnect = true; + $scope.deleteFTPButtonInit = false; + }; - - $scope.deleteFTPFinal = function(){ - + $scope.deleteFTPFinal = function () { var url = "/ftp/submitFTPDelete"; - var data = { - ftpUsername:$scope.selectedFTPAccount, - }; + var data = { + ftpUsername: $scope.selectedFTPAccount, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.deleteStatus == 1){ + if (response.data.deleteStatus == 1) { - $scope.ftpAccountsOfDomain = true; - $scope.deleteFTPButton = true; - $scope.deleteFailure = true; - $scope.deleteSuccess = false; - $scope.couldNotConnect = true; - $scope.deleteFTPButtonInit = true; + $scope.ftpAccountsOfDomain = true; + $scope.deleteFTPButton = true; + $scope.deleteFailure = true; + $scope.deleteSuccess = false; + $scope.couldNotConnect = true; + $scope.deleteFTPButtonInit = true; - $scope.ftpUserNameDeleted = $scope.selectedFTPAccount; + $scope.ftpUserNameDeleted = $scope.selectedFTPAccount; - } + } else { - else - { + $scope.ftpAccountsOfDomain = true; + $scope.deleteFTPButton = true; + $scope.deleteFailure = false; + $scope.deleteSuccess = true; + $scope.couldNotConnect = true; + $scope.deleteFTPButtonInit = false; - $scope.ftpAccountsOfDomain = true; - $scope.deleteFTPButton = true; - $scope.deleteFailure = false; - $scope.deleteSuccess = true; - $scope.couldNotConnect = true; - $scope.deleteFTPButtonInit = false; + $scope.errorMessage = response.data.error_message; - $scope.errorMessage = response.data.error_message; - - } + } + } - } - function cantLoadInitialDatas(response) { - - $scope.ftpAccountsOfDomain = true; - $scope.deleteFTPButton = true; - $scope.deleteFailure = false; - $scope.deleteSuccess = true; - $scope.couldNotConnect = false; - $scope.deleteFTPButtonInit = true; - - - } + function cantLoadInitialDatas(response) { + $scope.ftpAccountsOfDomain = true; + $scope.deleteFTPButton = true; + $scope.deleteFailure = false; + $scope.deleteSuccess = true; + $scope.couldNotConnect = false; + $scope.deleteFTPButtonInit = true; + } }; @@ -310,7 +289,7 @@ app.controller('deleteFTPAccount', function($scope,$http) { /* Java script code to delete ftp account ends here */ -app.controller('listFTPAccounts', function($scope,$http) { +app.controller('listFTPAccounts', function ($scope, $http) { $scope.recordsFetched = true; $scope.passwordChanged = true; @@ -324,157 +303,155 @@ app.controller('listFTPAccounts', function($scope,$http) { var globalFTPUsername = ""; $scope.fetchFTPAccounts = function () { - populateCurrentRecords(); + populateCurrentRecords(); }; $scope.changePassword = function (ftpUsername) { - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.ftpLoading = true; - $scope.changePasswordBox = false; - $scope.notificationsBox = true; - $scope.ftpUsername = ftpUsername; - globalFTPUsername = ftpUsername; + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.ftpLoading = true; + $scope.changePasswordBox = false; + $scope.notificationsBox = true; + $scope.ftpUsername = ftpUsername; + globalFTPUsername = ftpUsername; }; $scope.changePasswordBtn = function () { - $scope.ftpLoading = false; + $scope.ftpLoading = false; - url = "/ftp/changePassword"; + url = "/ftp/changePassword"; - var data = { - ftpUserName:globalFTPUsername, - ftpPassword: $scope.ftpPassword, - }; + var data = { + ftpUserName: globalFTPUsername, + ftpPassword: $scope.ftpPassword, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.changePasswordStatus == 1){ - $scope.notificationsBox = false; - $scope.passwordChanged = false; - $scope.ftpLoading = true; - $scope.domainFeteched = $scope.selectedDomain; + if (response.data.changePasswordStatus == 1) { + $scope.notificationsBox = false; + $scope.passwordChanged = false; + $scope.ftpLoading = true; + $scope.domainFeteched = $scope.selectedDomain; - } - else{ - $scope.notificationsBox = false; - $scope.canNotChangePassword = false; - $scope.ftpLoading = true; - $scope.canNotChangePassword = false; - $scope.errorMessage = response.data.error_message; - } + } else { + $scope.notificationsBox = false; + $scope.canNotChangePassword = false; + $scope.ftpLoading = true; + $scope.canNotChangePassword = false; + $scope.errorMessage = response.data.error_message; + } - } - function cantLoadInitialDatas(response) { - $scope.notificationsBox = false; - $scope.couldNotConnect = false; - $scope.ftpLoading = true; + } - } + function cantLoadInitialDatas(response) { + $scope.notificationsBox = false; + $scope.couldNotConnect = false; + $scope.ftpLoading = true; - }; + } - function populateCurrentRecords(){ - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.ftpLoading = false; - $scope.ftpAccounts = true; - $scope.changePasswordBox = true; + }; - var selectedDomain = $scope.selectedDomain; + function populateCurrentRecords() { + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.ftpLoading = false; + $scope.ftpAccounts = true; + $scope.changePasswordBox = true; - url = "/ftp/getAllFTPAccounts"; + var selectedDomain = $scope.selectedDomain; - var data = { - selectedDomain:selectedDomain, - }; + url = "/ftp/getAllFTPAccounts"; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var data = { + selectedDomain: selectedDomain, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus == 1){ + if (response.data.fetchStatus == 1) { - $scope.records = JSON.parse(response.data.data); + $scope.records = JSON.parse(response.data.data); - $scope.notificationsBox = false; - $scope.recordsFetched = false; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.ftpLoading = true; - $scope.ftpAccounts = false; - $scope.changePasswordBox = true; + $scope.notificationsBox = false; + $scope.recordsFetched = false; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.ftpLoading = true; + $scope.ftpAccounts = false; + $scope.changePasswordBox = true; - $scope.domainFeteched = $scope.selectedDomain; + $scope.domainFeteched = $scope.selectedDomain; - } - else{ - $scope.notificationsBox = false; - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.ftpLoading = true; - $scope.ftpAccounts = true; - $scope.changePasswordBox = true; + } else { + $scope.notificationsBox = false; + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.ftpLoading = true; + $scope.ftpAccounts = true; + $scope.changePasswordBox = true; - $scope.errorMessage = response.data.error_message; - } + $scope.errorMessage = response.data.error_message; + } - } - function cantLoadInitialDatas(response) { - $scope.notificationsBox = false; - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = false; - $scope.ftpLoading = true; - $scope.ftpAccounts = true; - $scope.changePasswordBox = true; + } + + function cantLoadInitialDatas(response) { + $scope.notificationsBox = false; + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = false; + $scope.ftpLoading = true; + $scope.ftpAccounts = true; + $scope.changePasswordBox = true; - } + } - } + } //// $scope.generatedPasswordView = true; $scope.generatePassword = function () { - $scope.generatedPasswordView = false; - $scope.ftpPassword = randomPassword(12); + $scope.generatedPasswordView = false; + $scope.ftpPassword = randomPassword(12); }; $scope.usePassword = function () { diff --git a/static/mailServer/mailServer.js b/static/mailServer/mailServer.js old mode 100755 new mode 100644 index c5d8e512d..96403c507 --- a/static/mailServer/mailServer.js +++ b/static/mailServer/mailServer.js @@ -4,7 +4,7 @@ /* Java script code to create account */ -app.controller('createEmailAccount', function($scope,$http) { +app.controller('createEmailAccount', function ($scope, $http) { $scope.emailDetails = true; $scope.emailLoading = true; @@ -12,7 +12,7 @@ app.controller('createEmailAccount', function($scope,$http) { $scope.successfullyCreated = true; $scope.couldNotConnect = true; - $scope.showEmailDetails = function(){ + $scope.showEmailDetails = function () { $scope.emailDetails = false; $scope.emailLoading = true; @@ -26,100 +26,91 @@ app.controller('createEmailAccount', function($scope,$http) { }; - $scope.createEmailAccount = function(){ + $scope.createEmailAccount = function () { + + $scope.emailDetails = false; + $scope.emailLoading = false; + $scope.canNotCreate = true; + $scope.successfullyCreated = true; + $scope.couldNotConnect = true; + + + var url = "/email/submitEmailCreation"; + + var domain = $scope.emailDomain; + var username = $scope.emailUsername; + var password = $scope.emailPassword; + + + var data = { + domain: domain, + username: username, + passwordByPass: password, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.createEmailStatus === 1) { $scope.emailDetails = false; - $scope.emailLoading = false; + $scope.emailLoading = true; $scope.canNotCreate = true; + $scope.successfullyCreated = false; + $scope.couldNotConnect = true; + + $scope.createdID = username + "@" + domain; + + + } else { + $scope.emailDetails = false; + $scope.emailLoading = true; + $scope.canNotCreate = false; $scope.successfullyCreated = true; $scope.couldNotConnect = true; + $scope.errorMessage = response.data.error_message; - var url = "/email/submitEmailCreation"; - - var domain = $scope.emailDomain; - var username = $scope.emailUsername; - var password = $scope.emailPassword; + } - var data = { - domain:domain, - username:username, - password:password, - }; + } - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if(response.data.createEmailStatus === 1){ - - $scope.emailDetails = false; - $scope.emailLoading = true; - $scope.canNotCreate = true; - $scope.successfullyCreated = false; - $scope.couldNotConnect = true; - - $scope.createdID = username + "@" + domain; - - - } - - else - { - $scope.emailDetails = false; - $scope.emailLoading = true; - $scope.canNotCreate = false; - $scope.successfullyCreated = true; - $scope.couldNotConnect = true; - - $scope.errorMessage = response.data.error_message; - - - } - - - - } - function cantLoadInitialDatas(response) { - - $scope.emailDetails = false; - $scope.emailLoading = true; - $scope.canNotCreate = true; - $scope.successfullyCreated = true; - $scope.couldNotConnect = false; - - - - } + function cantLoadInitialDatas(response) { + $scope.emailDetails = false; + $scope.emailLoading = true; + $scope.canNotCreate = true; + $scope.successfullyCreated = true; + $scope.couldNotConnect = false; + } }; - $scope.hideFewDetails = function(){ + $scope.hideFewDetails = function () { $scope.successfullyCreated = true; - }; $scope.generatedPasswordView = true; $scope.generatePassword = function () { - $scope.generatedPasswordView = false; - $scope.emailPassword = randomPassword(12); + $scope.generatedPasswordView = false; + $scope.emailPassword = randomPassword(12); }; $scope.usePassword = function () { @@ -131,7 +122,7 @@ app.controller('createEmailAccount', function($scope,$http) { /* Java script code to create account */ -app.controller('deleteEmailAccount', function($scope,$http) { +app.controller('deleteEmailAccount', function ($scope, $http) { $scope.emailDetails = true; $scope.emailLoading = true; @@ -141,7 +132,7 @@ app.controller('deleteEmailAccount', function($scope,$http) { $scope.emailDetailsFinal = true; $scope.noEmails = true; - $scope.showEmailDetails = function(){ + $scope.showEmailDetails = function () { $scope.emailDetails = true; $scope.emailLoading = false; @@ -157,80 +148,68 @@ app.controller('deleteEmailAccount', function($scope,$http) { var domain = $scope.emailDomain; + var data = { + domain: domain, + }; - var data = { - domain:domain, - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus == 1){ + if (response.data.fetchStatus == 1) { - $scope.emails = JSON.parse(response.data.data); + $scope.emails = JSON.parse(response.data.data); - $scope.emailDetails = false; - $scope.emailLoading = true; - $scope.canNotDelete = true; - $scope.successfullyDeleted = true; - $scope.couldNotConnect = true; - $scope.emailDetailsFinal = true; - $scope.noEmails = true; + $scope.emailDetails = false; + $scope.emailLoading = true; + $scope.canNotDelete = true; + $scope.successfullyDeleted = true; + $scope.couldNotConnect = true; + $scope.emailDetailsFinal = true; + $scope.noEmails = true; + } else { + $scope.emailDetails = true; + $scope.emailLoading = true; + $scope.canNotDelete = true; + $scope.successfullyDeleted = true; + $scope.couldNotConnect = true; + $scope.emailDetailsFinal = true; + $scope.noEmails = false; + + } + } - } - - else - { - $scope.emailDetails = true; - $scope.emailLoading = true; - $scope.canNotDelete = true; - $scope.successfullyDeleted = true; - $scope.couldNotConnect = true; - $scope.emailDetailsFinal = true; - $scope.noEmails = false; - - } - - - - } - function cantLoadInitialDatas(response) { - - $scope.emailDetails = true; - $scope.emailLoading = true; - $scope.canNotDelete = true; - $scope.successfullyDeleted = true; - $scope.couldNotConnect = false; - $scope.emailDetailsFinal = true; - $scope.noEmails = true; - - - - } - + function cantLoadInitialDatas(response) { + $scope.emailDetails = true; + $scope.emailLoading = true; + $scope.canNotDelete = true; + $scope.successfullyDeleted = true; + $scope.couldNotConnect = false; + $scope.emailDetailsFinal = true; + $scope.noEmails = true; + } }; - $scope.deleteEmailAccountFinal = function(){ + $scope.deleteEmailAccountFinal = function () { $scope.emailLoading = false; @@ -240,83 +219,73 @@ app.controller('deleteEmailAccount', function($scope,$http) { var email = $scope.selectedEmail; + var data = { + email: email, + }; - var data = { - email:email, - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.deleteEmailStatus === 1){ + if (response.data.deleteEmailStatus === 1) { - $scope.emailDetails = true; - $scope.emailLoading = true; - $scope.canNotDelete = true; - $scope.successfullyDeleted = false; - $scope.couldNotConnect = true; - $scope.emailDetailsFinal = true; - $scope.noEmails = true; + $scope.emailDetails = true; + $scope.emailLoading = true; + $scope.canNotDelete = true; + $scope.successfullyDeleted = false; + $scope.couldNotConnect = true; + $scope.emailDetailsFinal = true; + $scope.noEmails = true; - $scope.deletedID = email; + $scope.deletedID = email; - } + } else { + $scope.emailDetails = true; + $scope.emailLoading = true; + $scope.canNotDelete = false; + $scope.successfullyDeleted = true; + $scope.couldNotConnect = true; + $scope.emailDetailsFinal = true; + $scope.noEmails = true; - else - { - $scope.emailDetails = true; - $scope.emailLoading = true; - $scope.canNotDelete = false; - $scope.successfullyDeleted = true; - $scope.couldNotConnect = true; - $scope.emailDetailsFinal = true; - $scope.noEmails = true; + $scope.errorMessage = response.data.error_message; - $scope.errorMessage = response.data.error_message; - - } + } + } - } - function cantLoadInitialDatas(response) { - - $scope.emailDetails = true; - $scope.emailLoading = true; - $scope.canNotDelete = true; - $scope.successfullyDeleted = true; - $scope.couldNotConnect = false; - $scope.emailDetailsFinal = true; - $scope.noEmails = true; - - - - } - + function cantLoadInitialDatas(response) { + $scope.emailDetails = true; + $scope.emailLoading = true; + $scope.canNotDelete = true; + $scope.successfullyDeleted = true; + $scope.couldNotConnect = false; + $scope.emailDetailsFinal = true; + $scope.noEmails = true; + } }; - - $scope.deleteEmailAccount = function(){ + $scope.deleteEmailAccount = function () { var domain = $scope.selectedEmail; - if(domain.length>0) { + if (domain.length > 0) { $scope.emailDetailsFinal = false; } @@ -327,7 +296,7 @@ app.controller('deleteEmailAccount', function($scope,$http) { /* Java script code to create account */ -app.controller('changeEmailPassword', function($scope,$http) { +app.controller('changeEmailPassword', function ($scope, $http) { $scope.emailLoading = true; $scope.emailDetails = true; @@ -336,7 +305,7 @@ app.controller('changeEmailPassword', function($scope,$http) { $scope.couldNotConnect = true; $scope.noEmails = true; - $scope.showEmailDetails = function(){ + $scope.showEmailDetails = function () { $scope.emailLoading = false; $scope.emailDetails = true; @@ -351,71 +320,63 @@ app.controller('changeEmailPassword', function($scope,$http) { var domain = $scope.emailDomain; + var data = { + domain: domain, + }; - var data = { - domain:domain, - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus == 1){ + if (response.data.fetchStatus == 1) { - $scope.emails = JSON.parse(response.data.data); + $scope.emails = JSON.parse(response.data.data); - $scope.emailLoading = true; - $scope.emailDetails = false; - $scope.canNotChangePassword = true; - $scope.passwordChanged = true; - $scope.couldNotConnect = true; - $scope.noEmails = true; + $scope.emailLoading = true; + $scope.emailDetails = false; + $scope.canNotChangePassword = true; + $scope.passwordChanged = true; + $scope.couldNotConnect = true; + $scope.noEmails = true; + } else { + $scope.emailLoading = true; + $scope.emailDetails = true; + $scope.canNotChangePassword = true; + $scope.passwordChanged = true; + $scope.couldNotConnect = true; + $scope.noEmails = false; + + } + } - } + function cantLoadInitialDatas(response) { - else - { - $scope.emailLoading = true; - $scope.emailDetails = true; - $scope.canNotChangePassword = true; - $scope.passwordChanged = true; - $scope.couldNotConnect = true; - $scope.noEmails = false; - - } + $scope.emailLoading = true; + $scope.emailDetails = true; + $scope.canNotChangePassword = true; + $scope.passwordChanged = true; + $scope.couldNotConnect = false; + $scope.noEmails = true; - - } - function cantLoadInitialDatas(response) { - - $scope.emailLoading = true; - $scope.emailDetails = true; - $scope.canNotChangePassword = true; - $scope.passwordChanged = true; - $scope.couldNotConnect = false; - $scope.noEmails = true; - - - - } + } }; - $scope.changePassword = function(){ + $scope.changePassword = function () { $scope.emailLoading = false; @@ -427,83 +388,72 @@ app.controller('changeEmailPassword', function($scope,$http) { var domain = $scope.emailDomain; + var data = { + domain: domain, + email: email, + password: password, + }; - var data = { - domain:domain, - email:email, - password:password, - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.passChangeStatus == 1){ + if (response.data.passChangeStatus == 1) { - $scope.emailLoading = true; - $scope.emailDetails = true; - $scope.canNotChangePassword = true; - $scope.passwordChanged = false; - $scope.couldNotConnect = true; - $scope.noEmails = true; + $scope.emailLoading = true; + $scope.emailDetails = true; + $scope.canNotChangePassword = true; + $scope.passwordChanged = false; + $scope.couldNotConnect = true; + $scope.noEmails = true; - $scope.passEmail = email; + $scope.passEmail = email; - } - - else - { - $scope.emailLoading = true; - $scope.emailDetails = false; - $scope.canNotChangePassword = false; - $scope.passwordChanged = true; - $scope.couldNotConnect = true; - $scope.noEmails = true; + } else { + $scope.emailLoading = true; + $scope.emailDetails = false; + $scope.canNotChangePassword = false; + $scope.passwordChanged = true; + $scope.couldNotConnect = true; + $scope.noEmails = true; - $scope.errorMessage = response.data.error_message; + $scope.errorMessage = response.data.error_message; - } + } + } - } - function cantLoadInitialDatas(response) { - - $scope.emailLoading = true; - $scope.emailDetails = false; - $scope.canNotChangePassword = true; - $scope.passwordChanged = true; - $scope.couldNotConnect = false; - $scope.noEmails = true; - - - - - - } - + function cantLoadInitialDatas(response) { + $scope.emailLoading = true; + $scope.emailDetails = false; + $scope.canNotChangePassword = true; + $scope.passwordChanged = true; + $scope.couldNotConnect = false; + $scope.noEmails = true; + } }; - $scope.deleteEmailAccount = function(){ + $scope.deleteEmailAccount = function () { var domain = $scope.selectedEmail; - if(domain.length>0) { + if (domain.length > 0) { $scope.emailDetailsFinal = false; } @@ -514,8 +464,8 @@ app.controller('changeEmailPassword', function($scope,$http) { $scope.generatedPasswordView = true; $scope.generatePassword = function () { - $scope.generatedPasswordView = false; - $scope.emailPassword = randomPassword(12); + $scope.generatedPasswordView = false; + $scope.emailPassword = randomPassword(12); }; $scope.usePassword = function () { @@ -523,331 +473,322 @@ app.controller('changeEmailPassword', function($scope,$http) { }; - }); /* Java script code to create account ends here */ - /* Java script code for DKIM Manager */ -app.controller('dkimManager', function($scope, $http, $timeout, $window) { +app.controller('dkimManager', function ($scope, $http, $timeout, $window) { - $scope.manageDKIMLoading = true; - $scope.dkimError = true; - $scope.dkimSuccess = true; - $scope.couldNotConnect = true; - $scope.domainRecords = true; - $scope.noKeysAvailable = true; + $scope.manageDKIMLoading = true; + $scope.dkimError = true; + $scope.dkimSuccess = true; + $scope.couldNotConnect = true; + $scope.domainRecords = true; + $scope.noKeysAvailable = true; + $scope.fetchKeys = function () { - $scope.fetchKeys = function(){ - - $scope.manageDKIMLoading = false; - $scope.dkimError = true; - $scope.dkimSuccess = true; - $scope.couldNotConnect = true; - $scope.domainRecords = true; - $scope.noKeysAvailable = true; + $scope.manageDKIMLoading = false; + $scope.dkimError = true; + $scope.dkimSuccess = true; + $scope.couldNotConnect = true; + $scope.domainRecords = true; + $scope.noKeysAvailable = true; - url = "/email/fetchDKIMKeys"; + url = "/email/fetchDKIMKeys"; - var data = { - domainName: $scope.domainName - }; + var data = { + domainName: $scope.domainName + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus === 1){ + if (response.data.fetchStatus === 1) { - if(response.data.keysAvailable === 1){ - - $scope.manageDKIMLoading = true; - $scope.dkimError = true; - $scope.dkimSuccess = false; - $scope.couldNotConnect = true; - $scope.domainRecords = false; - $scope.noKeysAvailable = true; - - $scope.privateKey = response.data.privateKey; - $scope.publicKey = response.data.publicKey; - $scope.dkimSuccessMessage = response.data.dkimSuccessMessage; - - - - }else{ - $scope.manageDKIMLoading = true; - $scope.dkimError = true; - $scope.dkimSuccess = true; - $scope.couldNotConnect = true; - $scope.domainRecords = true; - $scope.noKeysAvailable = false; - } - - - - } - else{ - $scope.errorMessage = response.data.error_message; - - $scope.manageDKIMLoading = true; - $scope.dkimError = false; - $scope.dkimSuccess = true; - $scope.couldNotConnect = true; - $scope.domainRecords = true; - $scope.noKeysAvailable = true; - } - - } - function cantLoadInitialDatas(response) { + if (response.data.keysAvailable === 1) { $scope.manageDKIMLoading = true; $scope.dkimError = true; - $scope.dkimSuccess = true; - $scope.couldNotConnect = false; - $scope.domainRecords = true; + $scope.dkimSuccess = false; + $scope.couldNotConnect = true; + $scope.domainRecords = false; $scope.noKeysAvailable = true; - - } - - }; - - $scope.createDomainDKIMKeys = function () { - - $scope.manageDKIMLoading = false; - $scope.dkimError = true; - $scope.dkimSuccess = true; - $scope.couldNotConnect = true; - $scope.domainRecords = true; - $scope.noKeysAvailable = false; - - url = "/email/generateDKIMKeys"; - - var data = { - domainName: $scope.domainName - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + $scope.privateKey = response.data.privateKey; + $scope.publicKey = response.data.publicKey; + $scope.dkimSuccessMessage = response.data.dkimSuccessMessage; - $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if(response.data.generateStatus === 1){ - - $scope.manageDKIMLoading = true; - $scope.dkimError = true; - $scope.dkimSuccess = true; - $scope.couldNotConnect = true; - $scope.domainRecords = true; - $scope.noKeysAvailable = true; - - $scope.fetchKeys(); - - - } - else{ - $scope.errorMessage = response.data.error_message; - - $scope.manageDKIMLoading = true; - $scope.dkimError = false; - $scope.dkimSuccess = true; - $scope.couldNotConnect = true; - $scope.domainRecords = true; - $scope.noKeysAvailable = false; - } - - } - function cantLoadInitialDatas(response) { - + } else { $scope.manageDKIMLoading = true; $scope.dkimError = true; $scope.dkimSuccess = true; - $scope.couldNotConnect = false; + $scope.couldNotConnect = true; $scope.domainRecords = true; - $scope.noKeysAvailable = true; - - + $scope.noKeysAvailable = false; } + } else { + $scope.errorMessage = response.data.error_message; - }; + $scope.manageDKIMLoading = true; + $scope.dkimError = false; + $scope.dkimSuccess = true; + $scope.couldNotConnect = true; + $scope.domainRecords = true; + $scope.noKeysAvailable = true; + } - // Installation + } + + function cantLoadInitialDatas(response) { + + $scope.manageDKIMLoading = true; + $scope.dkimError = true; + $scope.dkimSuccess = true; + $scope.couldNotConnect = false; + $scope.domainRecords = true; + $scope.noKeysAvailable = true; - $scope.openDKIMNotifyBox = true; - $scope.openDKIMError = true; - $scope.couldNotConnect = true; - $scope.openDKIMSuccessfullyInstalled = true; - $scope.openDKIMInstallBox = true; - $scope.manageDKIMLoading = true; + } + + }; + + $scope.createDomainDKIMKeys = function () { + + $scope.manageDKIMLoading = false; + $scope.dkimError = true; + $scope.dkimSuccess = true; + $scope.couldNotConnect = true; + $scope.domainRecords = true; + $scope.noKeysAvailable = false; + + url = "/email/generateDKIMKeys"; + + var data = { + domainName: $scope.domainName + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $scope.installOpenDKIM = function(){ - - $scope.openDKIMNotifyBox = true; - $scope.openDKIMError = true; - $scope.couldNotConnect = true; - $scope.openDKIMSuccessfullyInstalled = true; - $scope.openDKIMInstallBox = true; - $scope.manageDKIMLoading = false; - - url = "/email/installOpenDKIM"; - - var data = {}; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + if (response.data.generateStatus === 1) { + + $scope.manageDKIMLoading = true; + $scope.dkimError = true; + $scope.dkimSuccess = true; + $scope.couldNotConnect = true; + $scope.domainRecords = true; + $scope.noKeysAvailable = true; + + $scope.fetchKeys(); - function ListInitialDatas(response) { + } else { + $scope.errorMessage = response.data.error_message; + + $scope.manageDKIMLoading = true; + $scope.dkimError = false; + $scope.dkimSuccess = true; + $scope.couldNotConnect = true; + $scope.domainRecords = true; + $scope.noKeysAvailable = false; + } + + } + + function cantLoadInitialDatas(response) { + + $scope.manageDKIMLoading = true; + $scope.dkimError = true; + $scope.dkimSuccess = true; + $scope.couldNotConnect = false; + $scope.domainRecords = true; + $scope.noKeysAvailable = true; - if(response.data.installOpenDKIM === 1){ + } - $scope.openDKIMNotifyBox = true; - $scope.openDKIMError = true; - $scope.couldNotConnect = true; - $scope.openDKIMSuccessfullyInstalled = true; - $scope.openDKIMInstallBox = false; - $scope.manageDKIMLoading = true; - getRequestStatus(); + }; - } - else{ - $scope.errorMessage = response.data.error_message; + // Installation - $scope.openDKIMNotifyBox = false; - $scope.openDKIMError = false; - $scope.couldNotConnect = true; - $scope.openDKIMSuccessfullyInstalled = true; - $scope.openDKIMInstallBox = true; - $scope.manageDKIMLoading = true; - } - } - function cantLoadInitialDatas(response) { + $scope.openDKIMNotifyBox = true; + $scope.openDKIMError = true; + $scope.couldNotConnect = true; + $scope.openDKIMSuccessfullyInstalled = true; + $scope.openDKIMInstallBox = true; + $scope.manageDKIMLoading = true; - $scope.openDKIMNotifyBox = false; - $scope.openDKIMError = true; - $scope.couldNotConnect = false; - $scope.openDKIMSuccessfullyInstalled = true; - $scope.openDKIMInstallBox = true; - $scope.manageDKIMLoading = false; + + $scope.installOpenDKIM = function () { + + $scope.openDKIMNotifyBox = true; + $scope.openDKIMError = true; + $scope.couldNotConnect = true; + $scope.openDKIMSuccessfullyInstalled = true; + $scope.openDKIMInstallBox = true; + $scope.manageDKIMLoading = false; + + url = "/email/installOpenDKIM"; + + var data = {}; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.installOpenDKIM === 1) { + + $scope.openDKIMNotifyBox = true; + $scope.openDKIMError = true; + $scope.couldNotConnect = true; + $scope.openDKIMSuccessfullyInstalled = true; + $scope.openDKIMInstallBox = false; + $scope.manageDKIMLoading = true; + + getRequestStatus(); + + } else { + $scope.errorMessage = response.data.error_message; + + $scope.openDKIMNotifyBox = false; + $scope.openDKIMError = false; + $scope.couldNotConnect = true; + $scope.openDKIMSuccessfullyInstalled = true; + $scope.openDKIMInstallBox = true; + $scope.manageDKIMLoading = true; + } + + } + + function cantLoadInitialDatas(response) { + + $scope.openDKIMNotifyBox = false; + $scope.openDKIMError = true; + $scope.couldNotConnect = false; + $scope.openDKIMSuccessfullyInstalled = true; + $scope.openDKIMInstallBox = true; + $scope.manageDKIMLoading = false; + } + + }; + + + function getRequestStatus() { + + $scope.openDKIMNotifyBox = true; + $scope.openDKIMError = true; + $scope.couldNotConnect = true; + $scope.openDKIMSuccessfullyInstalled = true; + $scope.openDKIMInstallBox = false; + $scope.manageDKIMLoading = false; + + + url = "/email/installStatusOpenDKIM"; + + var data = {}; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.abort === 0) { + $scope.requestData = response.data.requestStatus; + $timeout(getRequestStatus, 1000); + } else { + // Notifications + $timeout.cancel(); + + $scope.openDKIMNotifyBox = false; + $scope.openDKIMError = true; + $scope.couldNotConnect = true; + $scope.openDKIMSuccessfullyInstalled = true; + $scope.openDKIMInstallBox = true; + $scope.manageDKIMLoading = true; + + $scope.requestData = response.data.requestStatus; + + if (response.data.installed === 0) { + $scope.openDKIMError = false; + $scope.errorMessage = response.data.error_message; + } else { + $scope.openDKIMSuccessfullyInstalled = false; + $timeout(function () { + $window.location.reload(); + }, 3000); } - }; + } + + } + + function cantLoadInitialDatas(response) { + + $scope.modSecNotifyBox = false; + $scope.modeSecInstallBox = false; + $scope.modsecLoading = true; + $scope.failedToStartInallation = true; + $scope.couldNotConnect = false; + $scope.modSecSuccessfullyInstalled = true; + $scope.installationFailed = true; - function getRequestStatus(){ - - $scope.openDKIMNotifyBox = true; - $scope.openDKIMError = true; - $scope.couldNotConnect = true; - $scope.openDKIMSuccessfullyInstalled = true; - $scope.openDKIMInstallBox = false; - $scope.manageDKIMLoading = false; - - - - url = "/email/installStatusOpenDKIM"; - - var data = {}; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if(response.data.abort === 0){ - $scope.requestData = response.data.requestStatus; - $timeout(getRequestStatus,1000); - } - else{ - // Notifications - $timeout.cancel(); - - $scope.openDKIMNotifyBox = false; - $scope.openDKIMError = true; - $scope.couldNotConnect = true; - $scope.openDKIMSuccessfullyInstalled = true; - $scope.openDKIMInstallBox = true; - $scope.manageDKIMLoading = true; - - $scope.requestData = response.data.requestStatus; - - if(response.data.installed === 0) { - $scope.openDKIMError = false; - $scope.errorMessage = response.data.error_message; - }else{ - $scope.openDKIMSuccessfullyInstalled = false; - $timeout(function() { $window.location.reload(); }, 3000); - } - - } - - } - function cantLoadInitialDatas(response) { - - $scope.modSecNotifyBox = false; - $scope.modeSecInstallBox = false; - $scope.modsecLoading = true; - $scope.failedToStartInallation = true; - $scope.couldNotConnect = false; - $scope.modSecSuccessfullyInstalled = true; - $scope.installationFailed = true; - - - } - - } + } + } }); /* Java script code for email forwarding */ -app.controller('emailForwarding', function($scope,$http) { +app.controller('emailForwarding', function ($scope, $http) { $scope.creationBox = true; $scope.emailDetails = true; @@ -858,7 +799,7 @@ app.controller('emailForwarding', function($scope,$http) { $scope.notifyBox = true; - $scope.showEmailDetails = function(){ + $scope.showEmailDetails = function () { $scope.creationBox = true; $scope.emailDetails = true; @@ -871,69 +812,62 @@ app.controller('emailForwarding', function($scope,$http) { var url = "/email/getEmailsForDomain"; - var data = { - domain:$scope.emailDomain - }; + var data = { + domain: $scope.emailDomain + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus === 1){ + if (response.data.fetchStatus === 1) { - $scope.emails = JSON.parse(response.data.data); + $scope.emails = JSON.parse(response.data.data); - $scope.creationBox = true; - $scope.emailDetails = false; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = false; + $scope.creationBox = true; + $scope.emailDetails = false; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = false; - } + } else { + $scope.creationBox = true; + $scope.emailDetails = true; + $scope.forwardLoading = true; + $scope.forwardError = false; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = false; - else - { - $scope.creationBox = true; - $scope.emailDetails = true; - $scope.forwardLoading = true; - $scope.forwardError = false; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = false; + $scope.errorMessage = response.data.error_message; - $scope.errorMessage = response.data.error_message; - - } + } + } - } - function cantLoadInitialDatas(response) { - - $scope.creationBox = true; - $scope.emailDetails = true; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = false; - $scope.notifyBox = false; - - - } - + function cantLoadInitialDatas(response) { + $scope.creationBox = true; + $scope.emailDetails = true; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = false; + $scope.notifyBox = false; + } }; @@ -950,7 +884,7 @@ app.controller('emailForwarding', function($scope,$http) { $scope.fetchCurrentForwardings(); }; - $scope.fetchCurrentForwardings = function(){ + $scope.fetchCurrentForwardings = function () { $scope.creationBox = false; $scope.emailDetails = false; @@ -963,74 +897,67 @@ app.controller('emailForwarding', function($scope,$http) { var url = "/email/fetchCurrentForwardings"; - var data = { - emailAddress:$scope.selectedEmail - }; + var data = { + emailAddress: $scope.selectedEmail + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus === 1){ + if (response.data.fetchStatus === 1) { - $scope.records = JSON.parse(response.data.data); + $scope.records = JSON.parse(response.data.data); - $scope.creationBox = false; - $scope.emailDetails = false; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = true; + $scope.creationBox = false; + $scope.emailDetails = false; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = true; - } + } else { + $scope.creationBox = true; + $scope.emailDetails = true; + $scope.forwardLoading = true; + $scope.forwardError = false; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = false; - else - { - $scope.creationBox = true; - $scope.emailDetails = true; - $scope.forwardLoading = true; - $scope.forwardError = false; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = false; + $scope.errorMessage = response.data.error_message; - $scope.errorMessage = response.data.error_message; - - } + } + } - } - function cantLoadInitialDatas(response) { - - $scope.creationBox = true; - $scope.emailDetails = true; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = false; - $scope.notifyBox = false; - - - } - + function cantLoadInitialDatas(response) { + $scope.creationBox = true; + $scope.emailDetails = true; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = false; + $scope.notifyBox = false; + } }; - $scope.deleteForwarding = function(source, destination){ + $scope.deleteForwarding = function (source, destination) { $scope.creationBox = true; $scope.emailDetails = true; @@ -1043,75 +970,68 @@ app.controller('emailForwarding', function($scope,$http) { var url = "/email/submitForwardDeletion"; - var data = { - destination:destination, - source: source - }; + var data = { + destination: destination, + source: source + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.deleteForwardingStatus === 1){ + if (response.data.deleteForwardingStatus === 1) { - $scope.creationBox = false; - $scope.emailDetails = false; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = true; + $scope.creationBox = false; + $scope.emailDetails = false; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = true; - $scope.fetchCurrentForwardings(); + $scope.fetchCurrentForwardings(); - } + } else { + $scope.creationBox = false; + $scope.emailDetails = false; + $scope.forwardLoading = true; + $scope.forwardError = false; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = false; - else - { - $scope.creationBox = false; - $scope.emailDetails = false; - $scope.forwardLoading = true; - $scope.forwardError = false; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = false; + $scope.errorMessage = response.data.error_message; - $scope.errorMessage = response.data.error_message; - - } + } + } - } - function cantLoadInitialDatas(response) { - - $scope.creationBox = true; - $scope.emailDetails = true; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = false; - $scope.notifyBox = false; - - - } - + function cantLoadInitialDatas(response) { + $scope.creationBox = true; + $scope.emailDetails = true; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = false; + $scope.notifyBox = false; + } }; - $scope.forwardEmail = function(){ + $scope.forwardEmail = function () { $scope.creationBox = false; $scope.emailDetails = false; @@ -1124,70 +1044,63 @@ app.controller('emailForwarding', function($scope,$http) { var url = "/email/submitEmailForwardingCreation"; - var data = { - source: $scope.selectedEmail, - destination:$scope.destinationEmail - }; + var data = { + source: $scope.selectedEmail, + destination: $scope.destinationEmail + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.createStatus === 1){ + if (response.data.createStatus === 1) { - $scope.creationBox = false; - $scope.emailDetails = false; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = true; + $scope.creationBox = false; + $scope.emailDetails = false; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = true; - $scope.fetchCurrentForwardings(); + $scope.fetchCurrentForwardings(); - } + } else { + $scope.creationBox = false; + $scope.emailDetails = false; + $scope.forwardLoading = true; + $scope.forwardError = false; + $scope.forwardSuccess = true; + $scope.couldNotConnect = true; + $scope.notifyBox = false; - else - { - $scope.creationBox = false; - $scope.emailDetails = false; - $scope.forwardLoading = true; - $scope.forwardError = false; - $scope.forwardSuccess = true; - $scope.couldNotConnect = true; - $scope.notifyBox = false; + $scope.errorMessage = response.data.error_message; - $scope.errorMessage = response.data.error_message; - - } + } + } - } - function cantLoadInitialDatas(response) { - - $scope.creationBox = true; - $scope.emailDetails = true; - $scope.forwardLoading = true; - $scope.forwardError = true; - $scope.forwardSuccess = true; - $scope.couldNotConnect = false; - $scope.notifyBox = false; - - - } - + function cantLoadInitialDatas(response) { + $scope.creationBox = true; + $scope.emailDetails = true; + $scope.forwardLoading = true; + $scope.forwardError = true; + $scope.forwardSuccess = true; + $scope.couldNotConnect = false; + $scope.notifyBox = false; + } }; diff --git a/static/serverStatus/serverStatus.js b/static/serverStatus/serverStatus.js old mode 100755 new mode 100644 index c31727c0c..db70955a0 --- a/static/serverStatus/serverStatus.js +++ b/static/serverStatus/serverStatus.js @@ -390,11 +390,18 @@ app.controller('servicesManager', function ($scope, $http) { url = "/serverstatus/servicesStatus"; - $http.post(url).then(ListInitialDatas, cantLoadInitialDatas); + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + data = {}; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); function ListInitialDatas(response) { - console.log(response.data) if (response.data.status.litespeed) { $scope.olsStatus = "Running"; diff --git a/static/userManagment/userManagment.js b/static/userManagment/userManagment.js old mode 100755 new mode 100644 index f1591bbb3..e5a215b0c --- a/static/userManagment/userManagment.js +++ b/static/userManagment/userManagment.js @@ -1479,10 +1479,10 @@ app.controller('apiAccessCTRL', function($scope,$http) { function cantLoadInitialDatas(response) { $scope.cyberpanelLoading = true; new PNotify({ - title: 'Error!', - text: 'Could not connect to server, please refresh this page.', - type:'error' - }); + title: 'Error!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); } diff --git a/static/websiteFunctions/websiteFunctions.js b/static/websiteFunctions/websiteFunctions.js old mode 100755 new mode 100644 index fbf022336..0cd60be54 --- a/static/websiteFunctions/websiteFunctions.js +++ b/static/websiteFunctions/websiteFunctions.js @@ -2,6 +2,24 @@ * Created by usman on 7/26/17. */ + +function getCookie(name) { + var cookieValue = null; + var t = document.cookie; + 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; +} + /* Java script code to create account */ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { @@ -31,22 +49,19 @@ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { if ($scope.sslCheck === true) { ssl = 1; - } - else { + } else { ssl = 0 } if ($scope.dkimCheck === true) { dkimCheck = 1; - } - else { + } else { dkimCheck = 0 } if ($scope.openBasedir === true) { openBasedir = 1; - } - else { + } else { openBasedir = 0 } @@ -84,8 +99,7 @@ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { if (response.data.createWebSiteStatus === 1) { statusFile = response.data.tempStatusPath; getCreationStatus(); - } - else { + } else { $scope.webSiteCreationLoading = true; $scope.installationDetailsForm = true; @@ -125,6 +139,7 @@ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { $scope.goBackDisable = true; $("#installProgress").css("width", "0%"); }; + function getCreationStatus() { url = "/websites/installWordpressStatus"; @@ -163,8 +178,7 @@ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { $scope.currentStatus = response.data.currentStatus; $timeout.cancel(); - } - else { + } else { $scope.webSiteCreationLoading = true; $scope.installationDetailsForm = true; @@ -182,8 +196,7 @@ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { } - } - else { + } else { $("#installProgress").css("width", response.data.installationProgress + "%"); $scope.installPercentage = response.data.installationProgress; $scope.currentStatus = response.data.currentStatus; @@ -238,8 +251,7 @@ app.controller('listWebsites', function ($scope, $http) { $scope.WebSitesList = finalData; $scope.pagination = response.data.pagination; $("#listFail").hide(); - } - else { + } else { $("#listFail").fadeIn(); $scope.errorMessage = response.data.error_message; @@ -271,8 +283,7 @@ app.controller('listWebsites', function ($scope, $http) { var finalData = JSON.parse(response.data.data); $scope.WebSitesList = finalData; $("#listFail").hide(); - } - else { + } else { $("#listFail").fadeIn(); $scope.errorMessage = response.data.error_message; console.log(response.data); @@ -316,8 +327,7 @@ app.controller('listWebsites', function ($scope, $http) { text: 'SSL successfully issued.', type: 'success' }); - } - else { + } else { new PNotify({ title: 'Operation Failed!', text: response.data.error_message, @@ -367,8 +377,7 @@ app.controller('listWebsites', function ($scope, $http) { var finalData = JSON.parse(response.data.data); $scope.WebSitesList = finalData; $("#listFail").hide(); - } - else { + } else { new PNotify({ title: 'Operation Failed!', text: response.data.error_message, @@ -381,23 +390,21 @@ app.controller('listWebsites', function ($scope, $http) { function cantLoadInitialData(response) { $scope.cyberPanelLoading = true; new PNotify({ - title: 'Operation Failed!', - text: 'Connect disrupted, refresh the page.', - type: 'error' - }); + title: 'Operation Failed!', + text: 'Connect disrupted, refresh the page.', + type: 'error' + }); } }; - }); /* Java script code to list accounts ends here */ - /* Java script code to delete Website */ @@ -451,8 +458,7 @@ app.controller('deleteWebsiteControl', function ($scope, $http) { $("#deleteLoading").hide(); - } - else { + } else { $("#websiteDeleteFailure").hide(); $("#websiteDeleteSuccess").fadeIn(); $("#deleteWebsiteButton").hide(); @@ -523,8 +529,7 @@ app.controller('modifyWebsitesController', function ($scope, $http) { $("#canNotModify").hide(); - } - else { + } else { console.log(response.data); $("#modifyWebsiteButton").fadeIn(); @@ -600,8 +605,7 @@ app.controller('modifyWebsitesController', function ($scope, $http) { $("#modifyWebsiteLoading").hide(); - } - else { + } else { $("#modifyWebsiteButton").hide(); $("#canNotModify").hide(); $("#websiteModifyFailure").hide(); @@ -670,12 +674,10 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { if (type == 3) { pageNumber = $scope.pageNumber + 1; $scope.pageNumber = pageNumber; - } - else if (type == 4) { + } else if (type == 4) { pageNumber = $scope.pageNumber - 1; $scope.pageNumber = pageNumber; - } - else { + } else { logType = type; } @@ -723,9 +725,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.records = JSON.parse(response.data.data); - } - - else { + } else { $scope.logFileLoading = true; $scope.logsFeteched = true; @@ -768,12 +768,10 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { if (type == 3) { errorPageNumber = $scope.errorPageNumber + 1; $scope.errorPageNumber = errorPageNumber; - } - else if (type == 4) { + } else if (type == 4) { errorPageNumber = $scope.errorPageNumber - 1; $scope.errorPageNumber = errorPageNumber; - } - else { + } else { logType = type; } @@ -825,9 +823,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.errorLogsData = response.data.data; - } - - else { + } else { // notifications @@ -949,9 +945,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.configData = response.data.configData; - } - - else { + } else { //Rewrite rules $scope.configurationsBoxRewrite = true; @@ -1047,9 +1041,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.saveConfigBtn = true; - } - - else { + } else { $scope.configurationsBox = false; $scope.configsFetched = true; $scope.couldNotFetchConfigs = true; @@ -1171,9 +1163,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.rewriteRules = response.data.rewriteRules; - } - - else { + } else { // from main $scope.configurationsBox = true; $scope.configsFetched = true; @@ -1279,9 +1269,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.configFileLoading = true; - } - - else { + } else { $scope.configurationsBoxRewrite = false; $scope.rewriteRulesFetched = false; $scope.couldNotFetchRewriteRules = true; @@ -1385,8 +1373,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { if (response.data.installStatus == 1) { if (typeof path != 'undefined') { $scope.installationURL = "http://" + domain + "/" + path; - } - else { + } else { $scope.installationURL = domain; } @@ -1396,8 +1383,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.installationSuccessfull = false; $scope.couldNotConnect = true; - } - else { + } else { $scope.installationDetailsForm = false; $scope.applicationInstallerLoading = true; @@ -1474,8 +1460,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { if (response.data.installStatus == 1) { if (typeof path != 'undefined') { $scope.installationURL = "http://" + domain + "/" + path; - } - else { + } else { $scope.installationURL = domain; } @@ -1485,8 +1470,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.installationSuccessfull = false; $scope.couldNotConnect = true; - } - else { + } else { $scope.installationDetailsFormJoomla = false; $scope.applicationInstallerLoading = true; @@ -1570,9 +1554,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.configFileLoading = true; - } - - else { + } else { $scope.sslSaved = true; $scope.couldNotSaveSSL = false; @@ -1656,8 +1638,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.couldNotConnect = true; - } - else { + } else { $scope.configFileLoading = true; $scope.errorMessage = response.data.error_message; @@ -1727,22 +1708,19 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { if ($scope.sslCheck === true) { ssl = 1; - } - else { + } else { ssl = 0 } if ($scope.dkimCheck === true) { dkimCheck = 1; - } - else { + } else { dkimCheck = 0 } if ($scope.openBasedir === true) { openBasedir = 1; - } - else { + } else { openBasedir = 0 } @@ -1782,8 +1760,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { if (response.data.createWebSiteStatus === 1) { statusFile = response.data.tempStatusPath; getCreationStatus(); - } - else { + } else { $scope.domainLoading = true; $scope.installationDetailsForm = true; @@ -1863,8 +1840,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.currentStatus = response.data.currentStatus; $timeout.cancel(); - } - else { + } else { $scope.domainLoading = true; $scope.installationDetailsForm = true; @@ -1882,8 +1858,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { } - } - else { + } else { $("#installProgress").css("width", response.data.installationProgress + "%"); $scope.installPercentage = response.data.installationProgress; $scope.currentStatus = response.data.currentStatus; @@ -1960,8 +1935,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.domainLoading = true; - } - else { + } else { $scope.domainError = false; $scope.errorMessage = response.data.error_message; $scope.domainLoading = true; @@ -2027,8 +2001,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.childBaseDirChanged = true; - } - else { + } else { $scope.errorMessage = response.data.error_message; $scope.domainLoading = true; @@ -2104,8 +2077,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.domainLoading = true; $scope.childBaseDirChanged = false; - } - else { + } else { $scope.phpChanged = true; $scope.domainError = false; @@ -2183,8 +2155,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.sslIssued = true; - } - else { + } else { $scope.errorMessage = response.data.error_message; $scope.domainLoading = true; @@ -2265,9 +2236,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.sslDomainIssued = childDomain; - } - - else { + } else { $scope.domainLoading = true; $scope.errorMessage = response.data.error_message; @@ -2359,8 +2328,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.couldNotConnect = true; $scope.openBaseDirBox = false; - } - else { + } else { $scope.baseDirLoading = true; $scope.operationFailed = false; @@ -2413,11 +2381,11 @@ RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] $scope.applyRewriteTemplate = function () { - if($scope.rewriteTemplate === "Force HTTP -> HTTPS"){ - $scope.rewriteRules = httpToHTTPS + $scope.rewriteRules; - }else if($scope.rewriteTemplate === "Force NON-WWW -> WWW"){ - $scope.rewriteRules = nonWWWToWWW + $scope.rewriteRules; - } + if ($scope.rewriteTemplate === "Force HTTP -> HTTPS") { + $scope.rewriteRules = httpToHTTPS + $scope.rewriteRules; + } else if ($scope.rewriteTemplate === "Force NON-WWW -> WWW") { + $scope.rewriteRules = nonWWWToWWW + $scope.rewriteRules; + } }; @@ -2484,8 +2452,7 @@ app.controller('suspendWebsiteControl', function ($scope, $http) { $scope.websiteStatus = websiteName; $scope.finalStatus = "Suspended"; - } - else { + } else { $scope.suspendLoading = true; $scope.stateView = false; @@ -2499,8 +2466,7 @@ app.controller('suspendWebsiteControl', function ($scope, $http) { } - } - else { + } else { if (state == "Suspend") { @@ -2513,8 +2479,7 @@ app.controller('suspendWebsiteControl', function ($scope, $http) { $scope.couldNotConnect = true; - } - else { + } else { $scope.suspendLoading = true; $scope.stateView = false; @@ -2595,8 +2560,7 @@ app.controller('manageCronController', function ($scope, $http) { $("#modifyCronForm").hide(); $("#saveCronButton").hide(); $("#addCronButton").hide(); - } - else { + } else { console.log(response.data); var finalData = response.data.crons; $scope.cronList = finalData; @@ -2646,6 +2610,7 @@ app.controller('manageCronController', function ($scope, $http) { }; $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { console.log(response); @@ -2657,8 +2622,7 @@ app.controller('manageCronController', function ($scope, $http) { $("#modifyCronForm").hide(); $("#saveCronButton").hide(); $("#addCronButton").hide(); - } - else { + } else { console.log(response.data); $scope.minute = response.data.cron.minute @@ -2703,8 +2667,7 @@ app.controller('manageCronController', function ($scope, $http) { $("#manageCronLoading").hide(); if (!$scope.websiteToBeModified) { alert("Please select a domain first"); - } - else { + } else { $scope.minute = $scope.hour = $scope.monthday = $scope.month = $scope.weekday = $scope.command = $scope.line = ""; $("#cronTable").hide(); @@ -2732,7 +2695,7 @@ app.controller('manageCronController', function ($scope, $http) { monthday: $scope.monthday, month: $scope.month, weekday: $scope.weekday, - command: $scope.command + cronCommand: $scope.command }; var config = { @@ -2742,6 +2705,7 @@ app.controller('manageCronController', function ($scope, $http) { }; $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { console.log(response); @@ -2751,8 +2715,7 @@ app.controller('manageCronController', function ($scope, $http) { $("#cronEditSuccess").hide(); $("#fetchCronFailure").hide(); $("#addCronFailure").show(); - } - else { + } else { $("#cronTable").hide(); $("#manageCronLoading").hide(); $("#cronEditSuccess").show(); @@ -2792,6 +2755,7 @@ app.controller('manageCronController', function ($scope, $http) { }; $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { console.log(response); @@ -2801,8 +2765,7 @@ app.controller('manageCronController', function ($scope, $http) { $("#cronEditSuccess").hide(); $("#fetchCronFailure").hide(); $("#addCronFailure").show(); - } - else { + } else { $("#cronTable").hide(); $("#manageCronLoading").hide(); $("#cronEditSuccess").show(); @@ -2838,7 +2801,7 @@ app.controller('manageCronController', function ($scope, $http) { monthday: $scope.monthday, month: $scope.month, weekday: $scope.weekday, - command: $scope.command + cronCommand: $scope.command }; var config = { @@ -2848,6 +2811,7 @@ app.controller('manageCronController', function ($scope, $http) { }; $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { if (response.data.addNewCron === 0) { @@ -2857,8 +2821,7 @@ app.controller('manageCronController', function ($scope, $http) { $("#cronEditSuccess").hide(); $("#fetchCronFailure").hide(); $("#addCronFailure").show(); - } - else { + } else { console.log(response.data); $("#cronTable").hide(); $("#manageCronLoading").hide(); @@ -2915,8 +2878,7 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind if ($scope.sslCheck === true) { ssl = 1; - } - else { + } else { ssl = 0 } @@ -2957,8 +2919,7 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind }, 3000); - } - else { + } else { $scope.aliasTable = true; $scope.addAliasButton = true; @@ -3028,8 +2989,7 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind $scope.operationSuccess = false; - } - else { + } else { $scope.aliasTable = false; $scope.addAliasButton = true; @@ -3102,8 +3062,7 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind }, 3000); - } - else { + } else { $scope.aliasTable = false; $scope.addAliasButton = true; @@ -3178,12 +3137,10 @@ app.controller('launchChild', function ($scope, $http) { if (type == 3) { pageNumber = $scope.pageNumber + 1; $scope.pageNumber = pageNumber; - } - else if (type == 4) { + } else if (type == 4) { pageNumber = $scope.pageNumber - 1; $scope.pageNumber = pageNumber; - } - else { + } else { logType = type; } @@ -3231,9 +3188,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.records = JSON.parse(response.data.data); - } - - else { + } else { $scope.logFileLoading = true; $scope.logsFeteched = true; @@ -3276,12 +3231,10 @@ app.controller('launchChild', function ($scope, $http) { if (type === 3) { errorPageNumber = $scope.errorPageNumber + 1; $scope.errorPageNumber = errorPageNumber; - } - else if (type === 4) { + } else if (type === 4) { errorPageNumber = $scope.errorPageNumber - 1; $scope.errorPageNumber = errorPageNumber; - } - else { + } else { logType = type; } @@ -3333,9 +3286,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.errorLogsData = response.data.data; - } - - else { + } else { // notifications @@ -3457,9 +3408,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.configData = response.data.configData; - } - - else { + } else { //Rewrite rules $scope.configurationsBoxRewrite = true; @@ -3555,9 +3504,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.saveConfigBtn = true; - } - - else { + } else { $scope.configurationsBox = false; $scope.configsFetched = true; $scope.couldNotFetchConfigs = true; @@ -3680,9 +3627,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.rewriteRules = response.data.rewriteRules; - } - - else { + } else { // from main $scope.configurationsBox = true; $scope.configsFetched = true; @@ -3788,9 +3733,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.configFileLoading = true; - } - - else { + } else { $scope.configurationsBoxRewrite = false; $scope.rewriteRulesFetched = false; $scope.couldNotFetchRewriteRules = true; @@ -3887,9 +3830,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.configFileLoading = true; - } - - else { + } else { $scope.sslSaved = true; $scope.couldNotSaveSSL = false; @@ -3975,8 +3916,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.couldNotConnect = true; - } - else { + } else { $scope.configFileLoading = true; $scope.errorMessage = response.data.error_message; @@ -4062,8 +4002,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.couldNotConnect = true; $scope.openBaseDirBox = false; - } - else { + } else { $scope.baseDirLoading = true; $scope.operationFailed = false; @@ -4150,7 +4089,7 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { path: path, blogTitle: $scope.blogTitle, adminUser: $scope.adminUser, - adminPassword: $scope.adminPassword, + passwordByPass: $scope.adminPassword, adminEmail: $scope.adminEmail }; @@ -4168,8 +4107,7 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { if (response.data.installStatus === 1) { statusFile = response.data.tempStatusPath; getInstallStatus(); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4229,8 +4167,7 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { if (typeof path !== 'undefined') { $scope.installationURL = "http://" + domain + "/" + path; - } - else { + } else { $scope.installationURL = domain; } @@ -4240,8 +4177,7 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { $scope.currentStatus = response.data.currentStatus; $timeout.cancel(); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4258,8 +4194,7 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { } - } - else { + } else { $("#installProgress").css("width", response.data.installationProgress + "%"); $scope.installPercentage = response.data.installationProgress; $scope.currentStatus = response.data.currentStatus; @@ -4349,8 +4284,7 @@ app.controller('installJoomlaCTRL', function ($scope, $http, $timeout) { if (typeof path !== 'undefined') { $scope.installationURL = "http://" + domain + "/" + path; - } - else { + } else { $scope.installationURL = domain; } @@ -4360,8 +4294,7 @@ app.controller('installJoomlaCTRL', function ($scope, $http, $timeout) { $scope.currentStatus = response.data.currentStatus; $timeout.cancel(); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4378,8 +4311,7 @@ app.controller('installJoomlaCTRL', function ($scope, $http, $timeout) { } - } - else { + } else { $("#installProgress").css("width", response.data.installationProgress + "%"); $scope.installPercentage = response.data.installationProgress; $scope.currentStatus = response.data.currentStatus; @@ -4431,7 +4363,7 @@ app.controller('installJoomlaCTRL', function ($scope, $http, $timeout) { path: path, sitename: $scope.blogTitle, username: $scope.adminUser, - password: $scope.adminPassword, + passwordByPass: $scope.adminPassword, prefix: $scope.databasePrefix }; @@ -4449,8 +4381,7 @@ app.controller('installJoomlaCTRL', function ($scope, $http, $timeout) { if (response.data.installStatus === 1) { statusFile = response.data.tempStatusPath; getInstallStatus(); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4543,8 +4474,7 @@ app.controller('setupGit', function ($scope, $http, $timeout, $window) { $window.location.reload(); }, 3000); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4562,8 +4492,7 @@ app.controller('setupGit', function ($scope, $http, $timeout, $window) { } - } - else { + } else { $("#installProgress").css("width", response.data.installationProgress + "%"); $scope.installPercentage = response.data.installationProgress; $scope.currentStatus = response.data.currentStatus; @@ -4623,8 +4552,7 @@ app.controller('setupGit', function ($scope, $http, $timeout, $window) { if (response.data.installStatus === 1) { statusFile = response.data.tempStatusPath; getInstallStatus(); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4705,8 +4633,7 @@ app.controller('setupGit', function ($scope, $http, $timeout, $window) { $window.location.reload(); }, 3000); - } - else { + } else { $scope.failedMesg = false; $scope.successMessage = true; @@ -4764,8 +4691,7 @@ app.controller('setupGit', function ($scope, $http, $timeout, $window) { $scope.couldNotConnect = true; $scope.successMessageBranch = false; - } - else { + } else { $scope.failedMesg = false; $scope.successMessage = true; @@ -4857,8 +4783,7 @@ app.controller('installPrestaShopCTRL', function ($scope, $http, $timeout) { if (typeof path !== 'undefined') { $scope.installationURL = "http://" + domain + "/" + path; - } - else { + } else { $scope.installationURL = domain; } @@ -4868,8 +4793,7 @@ app.controller('installPrestaShopCTRL', function ($scope, $http, $timeout) { $scope.currentStatus = response.data.currentStatus; $timeout.cancel(); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4886,8 +4810,7 @@ app.controller('installPrestaShopCTRL', function ($scope, $http, $timeout) { } - } - else { + } else { $("#installProgress").css("width", response.data.installationProgress + "%"); $scope.installPercentage = response.data.installationProgress; $scope.currentStatus = response.data.currentStatus; @@ -4942,7 +4865,7 @@ app.controller('installPrestaShopCTRL', function ($scope, $http, $timeout) { lastName: $scope.lastName, databasePrefix: $scope.databasePrefix, email: $scope.email, - password: $scope.password + passwordByPass: $scope.password }; var config = { @@ -4959,8 +4882,7 @@ app.controller('installPrestaShopCTRL', function ($scope, $http, $timeout) { if (response.data.installStatus === 1) { statusFile = response.data.tempStatusPath; getInstallStatus(); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4983,4 +4905,68 @@ app.controller('installPrestaShopCTRL', function ($scope, $http, $timeout) { }; +}); + +app.controller('sshAccess', function ($scope, $http, $timeout) { + + $scope.wpInstallLoading = true; + + $scope.setupSSHAccess = function () { + $scope.wpInstallLoading = false; + + url = "/websites/saveSSHAccessChanges"; + + var data = { + domain: $("#domainName").text(), + externalApp: $("#externalApp").text(), + password: $scope.password + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.wpInstallLoading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Changes Successfully Applied.', + type: 'success' + }); + } else { + + + + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + + } + + + } + + function cantLoadInitialDatas(response) { + + new PNotify({ + title: 'Error!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + + }; + + }); \ No newline at end of file diff --git a/tuning/tuning.py b/tuning/tuning.py index 6f42cf603..4bac5143d 100755 --- a/tuning/tuning.py +++ b/tuning/tuning.py @@ -70,6 +70,13 @@ class tuningManager: def tuneLitespeed(self, userID, data): try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() + status = data['status'] if status == "fetch": @@ -137,6 +144,14 @@ class tuningManager: def tunePHP(self, userID, data): try: + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() + status = data['status'] domainSelection = str(data['domainSelection']) diff --git a/userManagment/static/userManagment/userManagment.js b/userManagment/static/userManagment/userManagment.js index f1591bbb3..e5a215b0c 100755 --- a/userManagment/static/userManagment/userManagment.js +++ b/userManagment/static/userManagment/userManagment.js @@ -1479,10 +1479,10 @@ app.controller('apiAccessCTRL', function($scope,$http) { function cantLoadInitialDatas(response) { $scope.cyberpanelLoading = true; new PNotify({ - title: 'Error!', - text: 'Could not connect to server, please refresh this page.', - type:'error' - }); + title: 'Error!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); } diff --git a/userManagment/views.py b/userManagment/views.py index ba985e7b6..bbf0b9af8 100755 --- a/userManagment/views.py +++ b/userManagment/views.py @@ -237,6 +237,20 @@ def fetchUserDetails(request): user = Administrator.objects.get(userName=accountUsername) + currentACL = ACLManager.loadedACL(val) + loggedUser = Administrator.objects.get(pk=val) + + if currentACL['admin'] == 1: + pass + elif user.owner == loggedUser.pk: + pass + elif user.pk == loggedUser.pk: + pass + else: + data_ret = {'fetchStatus': 0, 'error_message': 'Un-authorized access.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + firstName = user.firstName lastName = user.lastName email = user.email @@ -278,9 +292,22 @@ def saveModifications(request): lastName = data['lastName'] email = data['email'] - admin = Administrator.objects.get(pk=val) user = Administrator.objects.get(userName=accountUsername) + currentACL = ACLManager.loadedACL(val) + loggedUser = Administrator.objects.get(pk=val) + + if currentACL['admin'] == 1: + pass + elif user.owner == loggedUser.pk: + pass + elif user.pk == loggedUser.pk: + pass + else: + data_ret = {'fetchStatus': 0, 'error_message': 'Un-authorized access.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + token = hashPassword.generateToken(accountUsername, data['password']) password = hashPassword.hash_password(data['password']) @@ -323,7 +350,6 @@ def deleteUser(request): else: return ACLManager.loadError() - except KeyError: return redirect(loadLoginPage) @@ -352,7 +378,7 @@ def submitUserDeletion(request): json_data = json.dumps(data_ret) return HttpResponse(json_data) else: - data_ret = {'status': 0, 'deleteStatus': 1, 'error_message': 'Not enough privileges'} + data_ret = {'status': 0, 'deleteStatus': 1, 'error_message': 'Not enough privileges.'} json_data = json.dumps(data_ret) return HttpResponse(json_data) @@ -814,9 +840,19 @@ def saveResellerChanges(request): json_data = json.dumps(finalResponse) return HttpResponse(json_data) + currentACL = ACLManager.loadedACL(val) + + if currentACL['admin'] == 1: + pass + elif currentACL['resellerCenter'] == 1: + pass + else: + return ACLManager.loadErrorJson() + userToBeModified = Administrator.objects.get(userName=data['userToBeModified']) newOwner = Administrator.objects.get(userName=data['newOwner']) + if ACLManager.websitesLimitCheck(newOwner, data['websitesLimit'], userToBeModified) == 0: finalResponse = {'status': 0, 'errorMessage': "You've reached maximum websites limit as a reseller.", diff --git a/websiteFunctions/static/websiteFunctions/websiteFunctions.js b/websiteFunctions/static/websiteFunctions/websiteFunctions.js index fbf022336..0cd60be54 100755 --- a/websiteFunctions/static/websiteFunctions/websiteFunctions.js +++ b/websiteFunctions/static/websiteFunctions/websiteFunctions.js @@ -2,6 +2,24 @@ * Created by usman on 7/26/17. */ + +function getCookie(name) { + var cookieValue = null; + var t = document.cookie; + 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; +} + /* Java script code to create account */ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { @@ -31,22 +49,19 @@ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { if ($scope.sslCheck === true) { ssl = 1; - } - else { + } else { ssl = 0 } if ($scope.dkimCheck === true) { dkimCheck = 1; - } - else { + } else { dkimCheck = 0 } if ($scope.openBasedir === true) { openBasedir = 1; - } - else { + } else { openBasedir = 0 } @@ -84,8 +99,7 @@ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { if (response.data.createWebSiteStatus === 1) { statusFile = response.data.tempStatusPath; getCreationStatus(); - } - else { + } else { $scope.webSiteCreationLoading = true; $scope.installationDetailsForm = true; @@ -125,6 +139,7 @@ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { $scope.goBackDisable = true; $("#installProgress").css("width", "0%"); }; + function getCreationStatus() { url = "/websites/installWordpressStatus"; @@ -163,8 +178,7 @@ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { $scope.currentStatus = response.data.currentStatus; $timeout.cancel(); - } - else { + } else { $scope.webSiteCreationLoading = true; $scope.installationDetailsForm = true; @@ -182,8 +196,7 @@ app.controller('createWebsite', function ($scope, $http, $timeout, $window) { } - } - else { + } else { $("#installProgress").css("width", response.data.installationProgress + "%"); $scope.installPercentage = response.data.installationProgress; $scope.currentStatus = response.data.currentStatus; @@ -238,8 +251,7 @@ app.controller('listWebsites', function ($scope, $http) { $scope.WebSitesList = finalData; $scope.pagination = response.data.pagination; $("#listFail").hide(); - } - else { + } else { $("#listFail").fadeIn(); $scope.errorMessage = response.data.error_message; @@ -271,8 +283,7 @@ app.controller('listWebsites', function ($scope, $http) { var finalData = JSON.parse(response.data.data); $scope.WebSitesList = finalData; $("#listFail").hide(); - } - else { + } else { $("#listFail").fadeIn(); $scope.errorMessage = response.data.error_message; console.log(response.data); @@ -316,8 +327,7 @@ app.controller('listWebsites', function ($scope, $http) { text: 'SSL successfully issued.', type: 'success' }); - } - else { + } else { new PNotify({ title: 'Operation Failed!', text: response.data.error_message, @@ -367,8 +377,7 @@ app.controller('listWebsites', function ($scope, $http) { var finalData = JSON.parse(response.data.data); $scope.WebSitesList = finalData; $("#listFail").hide(); - } - else { + } else { new PNotify({ title: 'Operation Failed!', text: response.data.error_message, @@ -381,23 +390,21 @@ app.controller('listWebsites', function ($scope, $http) { function cantLoadInitialData(response) { $scope.cyberPanelLoading = true; new PNotify({ - title: 'Operation Failed!', - text: 'Connect disrupted, refresh the page.', - type: 'error' - }); + title: 'Operation Failed!', + text: 'Connect disrupted, refresh the page.', + type: 'error' + }); } }; - }); /* Java script code to list accounts ends here */ - /* Java script code to delete Website */ @@ -451,8 +458,7 @@ app.controller('deleteWebsiteControl', function ($scope, $http) { $("#deleteLoading").hide(); - } - else { + } else { $("#websiteDeleteFailure").hide(); $("#websiteDeleteSuccess").fadeIn(); $("#deleteWebsiteButton").hide(); @@ -523,8 +529,7 @@ app.controller('modifyWebsitesController', function ($scope, $http) { $("#canNotModify").hide(); - } - else { + } else { console.log(response.data); $("#modifyWebsiteButton").fadeIn(); @@ -600,8 +605,7 @@ app.controller('modifyWebsitesController', function ($scope, $http) { $("#modifyWebsiteLoading").hide(); - } - else { + } else { $("#modifyWebsiteButton").hide(); $("#canNotModify").hide(); $("#websiteModifyFailure").hide(); @@ -670,12 +674,10 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { if (type == 3) { pageNumber = $scope.pageNumber + 1; $scope.pageNumber = pageNumber; - } - else if (type == 4) { + } else if (type == 4) { pageNumber = $scope.pageNumber - 1; $scope.pageNumber = pageNumber; - } - else { + } else { logType = type; } @@ -723,9 +725,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.records = JSON.parse(response.data.data); - } - - else { + } else { $scope.logFileLoading = true; $scope.logsFeteched = true; @@ -768,12 +768,10 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { if (type == 3) { errorPageNumber = $scope.errorPageNumber + 1; $scope.errorPageNumber = errorPageNumber; - } - else if (type == 4) { + } else if (type == 4) { errorPageNumber = $scope.errorPageNumber - 1; $scope.errorPageNumber = errorPageNumber; - } - else { + } else { logType = type; } @@ -825,9 +823,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.errorLogsData = response.data.data; - } - - else { + } else { // notifications @@ -949,9 +945,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.configData = response.data.configData; - } - - else { + } else { //Rewrite rules $scope.configurationsBoxRewrite = true; @@ -1047,9 +1041,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.saveConfigBtn = true; - } - - else { + } else { $scope.configurationsBox = false; $scope.configsFetched = true; $scope.couldNotFetchConfigs = true; @@ -1171,9 +1163,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.rewriteRules = response.data.rewriteRules; - } - - else { + } else { // from main $scope.configurationsBox = true; $scope.configsFetched = true; @@ -1279,9 +1269,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.configFileLoading = true; - } - - else { + } else { $scope.configurationsBoxRewrite = false; $scope.rewriteRulesFetched = false; $scope.couldNotFetchRewriteRules = true; @@ -1385,8 +1373,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { if (response.data.installStatus == 1) { if (typeof path != 'undefined') { $scope.installationURL = "http://" + domain + "/" + path; - } - else { + } else { $scope.installationURL = domain; } @@ -1396,8 +1383,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.installationSuccessfull = false; $scope.couldNotConnect = true; - } - else { + } else { $scope.installationDetailsForm = false; $scope.applicationInstallerLoading = true; @@ -1474,8 +1460,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { if (response.data.installStatus == 1) { if (typeof path != 'undefined') { $scope.installationURL = "http://" + domain + "/" + path; - } - else { + } else { $scope.installationURL = domain; } @@ -1485,8 +1470,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.installationSuccessfull = false; $scope.couldNotConnect = true; - } - else { + } else { $scope.installationDetailsFormJoomla = false; $scope.applicationInstallerLoading = true; @@ -1570,9 +1554,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.configFileLoading = true; - } - - else { + } else { $scope.sslSaved = true; $scope.couldNotSaveSSL = false; @@ -1656,8 +1638,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.couldNotConnect = true; - } - else { + } else { $scope.configFileLoading = true; $scope.errorMessage = response.data.error_message; @@ -1727,22 +1708,19 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { if ($scope.sslCheck === true) { ssl = 1; - } - else { + } else { ssl = 0 } if ($scope.dkimCheck === true) { dkimCheck = 1; - } - else { + } else { dkimCheck = 0 } if ($scope.openBasedir === true) { openBasedir = 1; - } - else { + } else { openBasedir = 0 } @@ -1782,8 +1760,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { if (response.data.createWebSiteStatus === 1) { statusFile = response.data.tempStatusPath; getCreationStatus(); - } - else { + } else { $scope.domainLoading = true; $scope.installationDetailsForm = true; @@ -1863,8 +1840,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.currentStatus = response.data.currentStatus; $timeout.cancel(); - } - else { + } else { $scope.domainLoading = true; $scope.installationDetailsForm = true; @@ -1882,8 +1858,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { } - } - else { + } else { $("#installProgress").css("width", response.data.installationProgress + "%"); $scope.installPercentage = response.data.installationProgress; $scope.currentStatus = response.data.currentStatus; @@ -1960,8 +1935,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.domainLoading = true; - } - else { + } else { $scope.domainError = false; $scope.errorMessage = response.data.error_message; $scope.domainLoading = true; @@ -2027,8 +2001,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.childBaseDirChanged = true; - } - else { + } else { $scope.errorMessage = response.data.error_message; $scope.domainLoading = true; @@ -2104,8 +2077,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.domainLoading = true; $scope.childBaseDirChanged = false; - } - else { + } else { $scope.phpChanged = true; $scope.domainError = false; @@ -2183,8 +2155,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.sslIssued = true; - } - else { + } else { $scope.errorMessage = response.data.error_message; $scope.domainLoading = true; @@ -2265,9 +2236,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.sslDomainIssued = childDomain; - } - - else { + } else { $scope.domainLoading = true; $scope.errorMessage = response.data.error_message; @@ -2359,8 +2328,7 @@ app.controller('websitePages', function ($scope, $http, $timeout, $window) { $scope.couldNotConnect = true; $scope.openBaseDirBox = false; - } - else { + } else { $scope.baseDirLoading = true; $scope.operationFailed = false; @@ -2413,11 +2381,11 @@ RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] $scope.applyRewriteTemplate = function () { - if($scope.rewriteTemplate === "Force HTTP -> HTTPS"){ - $scope.rewriteRules = httpToHTTPS + $scope.rewriteRules; - }else if($scope.rewriteTemplate === "Force NON-WWW -> WWW"){ - $scope.rewriteRules = nonWWWToWWW + $scope.rewriteRules; - } + if ($scope.rewriteTemplate === "Force HTTP -> HTTPS") { + $scope.rewriteRules = httpToHTTPS + $scope.rewriteRules; + } else if ($scope.rewriteTemplate === "Force NON-WWW -> WWW") { + $scope.rewriteRules = nonWWWToWWW + $scope.rewriteRules; + } }; @@ -2484,8 +2452,7 @@ app.controller('suspendWebsiteControl', function ($scope, $http) { $scope.websiteStatus = websiteName; $scope.finalStatus = "Suspended"; - } - else { + } else { $scope.suspendLoading = true; $scope.stateView = false; @@ -2499,8 +2466,7 @@ app.controller('suspendWebsiteControl', function ($scope, $http) { } - } - else { + } else { if (state == "Suspend") { @@ -2513,8 +2479,7 @@ app.controller('suspendWebsiteControl', function ($scope, $http) { $scope.couldNotConnect = true; - } - else { + } else { $scope.suspendLoading = true; $scope.stateView = false; @@ -2595,8 +2560,7 @@ app.controller('manageCronController', function ($scope, $http) { $("#modifyCronForm").hide(); $("#saveCronButton").hide(); $("#addCronButton").hide(); - } - else { + } else { console.log(response.data); var finalData = response.data.crons; $scope.cronList = finalData; @@ -2646,6 +2610,7 @@ app.controller('manageCronController', function ($scope, $http) { }; $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { console.log(response); @@ -2657,8 +2622,7 @@ app.controller('manageCronController', function ($scope, $http) { $("#modifyCronForm").hide(); $("#saveCronButton").hide(); $("#addCronButton").hide(); - } - else { + } else { console.log(response.data); $scope.minute = response.data.cron.minute @@ -2703,8 +2667,7 @@ app.controller('manageCronController', function ($scope, $http) { $("#manageCronLoading").hide(); if (!$scope.websiteToBeModified) { alert("Please select a domain first"); - } - else { + } else { $scope.minute = $scope.hour = $scope.monthday = $scope.month = $scope.weekday = $scope.command = $scope.line = ""; $("#cronTable").hide(); @@ -2732,7 +2695,7 @@ app.controller('manageCronController', function ($scope, $http) { monthday: $scope.monthday, month: $scope.month, weekday: $scope.weekday, - command: $scope.command + cronCommand: $scope.command }; var config = { @@ -2742,6 +2705,7 @@ app.controller('manageCronController', function ($scope, $http) { }; $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { console.log(response); @@ -2751,8 +2715,7 @@ app.controller('manageCronController', function ($scope, $http) { $("#cronEditSuccess").hide(); $("#fetchCronFailure").hide(); $("#addCronFailure").show(); - } - else { + } else { $("#cronTable").hide(); $("#manageCronLoading").hide(); $("#cronEditSuccess").show(); @@ -2792,6 +2755,7 @@ app.controller('manageCronController', function ($scope, $http) { }; $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { console.log(response); @@ -2801,8 +2765,7 @@ app.controller('manageCronController', function ($scope, $http) { $("#cronEditSuccess").hide(); $("#fetchCronFailure").hide(); $("#addCronFailure").show(); - } - else { + } else { $("#cronTable").hide(); $("#manageCronLoading").hide(); $("#cronEditSuccess").show(); @@ -2838,7 +2801,7 @@ app.controller('manageCronController', function ($scope, $http) { monthday: $scope.monthday, month: $scope.month, weekday: $scope.weekday, - command: $scope.command + cronCommand: $scope.command }; var config = { @@ -2848,6 +2811,7 @@ app.controller('manageCronController', function ($scope, $http) { }; $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + function ListInitialDatas(response) { if (response.data.addNewCron === 0) { @@ -2857,8 +2821,7 @@ app.controller('manageCronController', function ($scope, $http) { $("#cronEditSuccess").hide(); $("#fetchCronFailure").hide(); $("#addCronFailure").show(); - } - else { + } else { console.log(response.data); $("#cronTable").hide(); $("#manageCronLoading").hide(); @@ -2915,8 +2878,7 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind if ($scope.sslCheck === true) { ssl = 1; - } - else { + } else { ssl = 0 } @@ -2957,8 +2919,7 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind }, 3000); - } - else { + } else { $scope.aliasTable = true; $scope.addAliasButton = true; @@ -3028,8 +2989,7 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind $scope.operationSuccess = false; - } - else { + } else { $scope.aliasTable = false; $scope.addAliasButton = true; @@ -3102,8 +3062,7 @@ app.controller('manageAliasController', function ($scope, $http, $timeout, $wind }, 3000); - } - else { + } else { $scope.aliasTable = false; $scope.addAliasButton = true; @@ -3178,12 +3137,10 @@ app.controller('launchChild', function ($scope, $http) { if (type == 3) { pageNumber = $scope.pageNumber + 1; $scope.pageNumber = pageNumber; - } - else if (type == 4) { + } else if (type == 4) { pageNumber = $scope.pageNumber - 1; $scope.pageNumber = pageNumber; - } - else { + } else { logType = type; } @@ -3231,9 +3188,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.records = JSON.parse(response.data.data); - } - - else { + } else { $scope.logFileLoading = true; $scope.logsFeteched = true; @@ -3276,12 +3231,10 @@ app.controller('launchChild', function ($scope, $http) { if (type === 3) { errorPageNumber = $scope.errorPageNumber + 1; $scope.errorPageNumber = errorPageNumber; - } - else if (type === 4) { + } else if (type === 4) { errorPageNumber = $scope.errorPageNumber - 1; $scope.errorPageNumber = errorPageNumber; - } - else { + } else { logType = type; } @@ -3333,9 +3286,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.errorLogsData = response.data.data; - } - - else { + } else { // notifications @@ -3457,9 +3408,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.configData = response.data.configData; - } - - else { + } else { //Rewrite rules $scope.configurationsBoxRewrite = true; @@ -3555,9 +3504,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.saveConfigBtn = true; - } - - else { + } else { $scope.configurationsBox = false; $scope.configsFetched = true; $scope.couldNotFetchConfigs = true; @@ -3680,9 +3627,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.rewriteRules = response.data.rewriteRules; - } - - else { + } else { // from main $scope.configurationsBox = true; $scope.configsFetched = true; @@ -3788,9 +3733,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.configFileLoading = true; - } - - else { + } else { $scope.configurationsBoxRewrite = false; $scope.rewriteRulesFetched = false; $scope.couldNotFetchRewriteRules = true; @@ -3887,9 +3830,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.configFileLoading = true; - } - - else { + } else { $scope.sslSaved = true; $scope.couldNotSaveSSL = false; @@ -3975,8 +3916,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.couldNotConnect = true; - } - else { + } else { $scope.configFileLoading = true; $scope.errorMessage = response.data.error_message; @@ -4062,8 +4002,7 @@ app.controller('launchChild', function ($scope, $http) { $scope.couldNotConnect = true; $scope.openBaseDirBox = false; - } - else { + } else { $scope.baseDirLoading = true; $scope.operationFailed = false; @@ -4150,7 +4089,7 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { path: path, blogTitle: $scope.blogTitle, adminUser: $scope.adminUser, - adminPassword: $scope.adminPassword, + passwordByPass: $scope.adminPassword, adminEmail: $scope.adminEmail }; @@ -4168,8 +4107,7 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { if (response.data.installStatus === 1) { statusFile = response.data.tempStatusPath; getInstallStatus(); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4229,8 +4167,7 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { if (typeof path !== 'undefined') { $scope.installationURL = "http://" + domain + "/" + path; - } - else { + } else { $scope.installationURL = domain; } @@ -4240,8 +4177,7 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { $scope.currentStatus = response.data.currentStatus; $timeout.cancel(); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4258,8 +4194,7 @@ app.controller('installWordPressCTRL', function ($scope, $http, $timeout) { } - } - else { + } else { $("#installProgress").css("width", response.data.installationProgress + "%"); $scope.installPercentage = response.data.installationProgress; $scope.currentStatus = response.data.currentStatus; @@ -4349,8 +4284,7 @@ app.controller('installJoomlaCTRL', function ($scope, $http, $timeout) { if (typeof path !== 'undefined') { $scope.installationURL = "http://" + domain + "/" + path; - } - else { + } else { $scope.installationURL = domain; } @@ -4360,8 +4294,7 @@ app.controller('installJoomlaCTRL', function ($scope, $http, $timeout) { $scope.currentStatus = response.data.currentStatus; $timeout.cancel(); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4378,8 +4311,7 @@ app.controller('installJoomlaCTRL', function ($scope, $http, $timeout) { } - } - else { + } else { $("#installProgress").css("width", response.data.installationProgress + "%"); $scope.installPercentage = response.data.installationProgress; $scope.currentStatus = response.data.currentStatus; @@ -4431,7 +4363,7 @@ app.controller('installJoomlaCTRL', function ($scope, $http, $timeout) { path: path, sitename: $scope.blogTitle, username: $scope.adminUser, - password: $scope.adminPassword, + passwordByPass: $scope.adminPassword, prefix: $scope.databasePrefix }; @@ -4449,8 +4381,7 @@ app.controller('installJoomlaCTRL', function ($scope, $http, $timeout) { if (response.data.installStatus === 1) { statusFile = response.data.tempStatusPath; getInstallStatus(); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4543,8 +4474,7 @@ app.controller('setupGit', function ($scope, $http, $timeout, $window) { $window.location.reload(); }, 3000); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4562,8 +4492,7 @@ app.controller('setupGit', function ($scope, $http, $timeout, $window) { } - } - else { + } else { $("#installProgress").css("width", response.data.installationProgress + "%"); $scope.installPercentage = response.data.installationProgress; $scope.currentStatus = response.data.currentStatus; @@ -4623,8 +4552,7 @@ app.controller('setupGit', function ($scope, $http, $timeout, $window) { if (response.data.installStatus === 1) { statusFile = response.data.tempStatusPath; getInstallStatus(); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4705,8 +4633,7 @@ app.controller('setupGit', function ($scope, $http, $timeout, $window) { $window.location.reload(); }, 3000); - } - else { + } else { $scope.failedMesg = false; $scope.successMessage = true; @@ -4764,8 +4691,7 @@ app.controller('setupGit', function ($scope, $http, $timeout, $window) { $scope.couldNotConnect = true; $scope.successMessageBranch = false; - } - else { + } else { $scope.failedMesg = false; $scope.successMessage = true; @@ -4857,8 +4783,7 @@ app.controller('installPrestaShopCTRL', function ($scope, $http, $timeout) { if (typeof path !== 'undefined') { $scope.installationURL = "http://" + domain + "/" + path; - } - else { + } else { $scope.installationURL = domain; } @@ -4868,8 +4793,7 @@ app.controller('installPrestaShopCTRL', function ($scope, $http, $timeout) { $scope.currentStatus = response.data.currentStatus; $timeout.cancel(); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4886,8 +4810,7 @@ app.controller('installPrestaShopCTRL', function ($scope, $http, $timeout) { } - } - else { + } else { $("#installProgress").css("width", response.data.installationProgress + "%"); $scope.installPercentage = response.data.installationProgress; $scope.currentStatus = response.data.currentStatus; @@ -4942,7 +4865,7 @@ app.controller('installPrestaShopCTRL', function ($scope, $http, $timeout) { lastName: $scope.lastName, databasePrefix: $scope.databasePrefix, email: $scope.email, - password: $scope.password + passwordByPass: $scope.password }; var config = { @@ -4959,8 +4882,7 @@ app.controller('installPrestaShopCTRL', function ($scope, $http, $timeout) { if (response.data.installStatus === 1) { statusFile = response.data.tempStatusPath; getInstallStatus(); - } - else { + } else { $scope.installationDetailsForm = true; $scope.installationProgress = false; @@ -4983,4 +4905,68 @@ app.controller('installPrestaShopCTRL', function ($scope, $http, $timeout) { }; +}); + +app.controller('sshAccess', function ($scope, $http, $timeout) { + + $scope.wpInstallLoading = true; + + $scope.setupSSHAccess = function () { + $scope.wpInstallLoading = false; + + url = "/websites/saveSSHAccessChanges"; + + var data = { + domain: $("#domainName").text(), + externalApp: $("#externalApp").text(), + password: $scope.password + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + $scope.wpInstallLoading = true; + + if (response.data.status === 1) { + new PNotify({ + title: 'Success', + text: 'Changes Successfully Applied.', + type: 'success' + }); + } else { + + + + new PNotify({ + title: 'Error!', + text: response.data.error_message, + type: 'error' + }); + + } + + + } + + function cantLoadInitialDatas(response) { + + new PNotify({ + title: 'Error!', + text: 'Could not connect to server, please refresh this page.', + type: 'error' + }); + + + } + + }; + + }); \ No newline at end of file diff --git a/websiteFunctions/templates/websiteFunctions/sshAccess.html b/websiteFunctions/templates/websiteFunctions/sshAccess.html new file mode 100755 index 000000000..4efbe3818 --- /dev/null +++ b/websiteFunctions/templates/websiteFunctions/sshAccess.html @@ -0,0 +1,57 @@ +{% extends "baseTemplate/index.html" %} +{% load i18n %} +{% block title %}{% trans "SSH and CageFS - CyberPanel" %}{% endblock %} +{% block content %} + +{% load static %} +{% get_current_language as LANGUAGE_CODE %} + + +
    +
    +

    {% trans "SSH Access" %}

    +

    {% trans "Set up SSH access and enable/disable CageFS for " %} {{ domainName }}. {% trans " CageFS require CloudLinux OS." %}

    +
    + + +
    +
    +

    + {% trans "Set up SSH access for " %} {{ domainName }}. +

    +
    + + +
    + +
    + + +
    + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    + +
    + +
    +
    +
    + + + +
    + + +{% endblock %} \ No newline at end of file diff --git a/websiteFunctions/templates/websiteFunctions/website.html b/websiteFunctions/templates/websiteFunctions/website.html index a7fdb7473..7d90b5918 100755 --- a/websiteFunctions/templates/websiteFunctions/website.html +++ b/websiteFunctions/templates/websiteFunctions/website.html @@ -26,9 +26,11 @@

    {% trans "Resource Usage" %} + {% trans "Set up SSH Access" %}

    +
    @@ -67,7 +69,7 @@
    -
    +

    diff --git a/websiteFunctions/urls.py b/websiteFunctions/urls.py index 25d2d2c4b..b69739854 100755 --- a/websiteFunctions/urls.py +++ b/websiteFunctions/urls.py @@ -92,6 +92,11 @@ urlpatterns = [ url(r'^(?P(.*))/setupGit$', views.setupGit, name='setupGit'), url(r'^setupGitRepo$', views.setupGitRepo, name='setupGitRepo'), + ## Set up SSH Access + url(r'^(?P(.*))/sshAccess$', views.sshAccess, name='sshAccess'), + url(r'^saveSSHAccessChanges$', views.saveSSHAccessChanges, name='saveSSHAccessChanges'), + + url(r'^(?P(.*))/gitNotify$', views.gitNotify, name='gitNotify'), url(r'^detachRepo$', views.detachRepo, name='detachRepo'), url(r'^changeBranch$', views.changeBranch, name='changeBranch'), diff --git a/websiteFunctions/views.py b/websiteFunctions/views.py index 7dabd234f..8794bb5a1 100755 --- a/websiteFunctions/views.py +++ b/websiteFunctions/views.py @@ -8,6 +8,7 @@ from loginSystem.views import loadLoginPage import json from plogical.website import WebsiteManager from websiteFunctions.pluginManager import pluginManager +from django.views.decorators.csrf import csrf_exempt def loadWebsitesHome(request): try: @@ -565,6 +566,7 @@ def setupGitRepo(request): except KeyError: return redirect(loadLoginPage) +@csrf_exempt def gitNotify(request, domain): try: wm = WebsiteManager(domain) @@ -603,3 +605,20 @@ def prestaShopInstall(request): return wm.prestaShopInstall(userID, json.loads(request.body)) except KeyError: return redirect(loadLoginPage) + +def sshAccess(request, domain): + try: + userID = request.session['userID'] + wm = WebsiteManager(domain) + return wm.sshAccess(request, userID) + except KeyError: + return redirect(loadLoginPage) + + +def saveSSHAccessChanges(request): + try: + userID = request.session['userID'] + wm = WebsiteManager() + return wm.saveSSHAccessChanges(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) \ No newline at end of file