centralized execution ph3

This commit is contained in:
usmannasir
2019-03-30 14:21:52 +05:00
parent 34410360c7
commit 40b6093d3e
27 changed files with 766 additions and 457 deletions

View File

@@ -21,11 +21,7 @@ urlpatterns = [
url(r'^cancelRemoteTransfer', views.cancelRemoteTransfer, name='cancelRemoteTransfer'), url(r'^cancelRemoteTransfer', views.cancelRemoteTransfer, name='cancelRemoteTransfer'),
url(r'^cyberPanelVersion', views.cyberPanelVersion, name='cyberPanelVersion'), url(r'^cyberPanelVersion', views.cyberPanelVersion, name='cyberPanelVersion'),
url(r'^putSSHkey', views.putSSHkey, name='putSSHkey'),
url(r'^changeAdminPassword', views.changeAdminPassword, name='changeAdminPassword'),
url(r'^runAWSBackups$', views.runAWSBackups, name='runAWSBackups'), url(r'^runAWSBackups$', views.runAWSBackups, name='runAWSBackups'),
] ]

View File

@@ -33,6 +33,11 @@ def verifyConn(request):
admin = Administrator.objects.get(userName=adminUser) admin = Administrator.objects.get(userName=adminUser)
if admin.api == 0:
data_ret = {"verifyConn": 0, 'error_message': "API Access Disabled."}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
if hashPassword.check_password(admin.password, adminPass): if hashPassword.check_password(admin.password, adminPass):
data_ret = {"verifyConn": 1} data_ret = {"verifyConn": 1}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
@@ -48,6 +53,16 @@ def verifyConn(request):
return HttpResponse(json_data) return HttpResponse(json_data)
def createWebsite(request): def createWebsite(request):
data = json.loads(request.body)
adminUser = data['adminUser']
admin = Administrator.objects.get(userName=adminUser)
if admin.api == 0:
data_ret = {"existsStatus": 0, 'createWebSiteStatus': 0,
'error_message': "API Access Disabled."}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
wm = WebsiteManager() wm = WebsiteManager()
return wm.createWebsiteAPI(json.loads(request.body)) return wm.createWebsiteAPI(json.loads(request.body))
@@ -63,6 +78,11 @@ def getUserInfo(request):
admin = Administrator.objects.get(userName=adminUser) admin = Administrator.objects.get(userName=adminUser)
if admin.api == 0:
data_ret = {"status": 0, 'error_message': "API Access Disabled."}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
if hashPassword.check_password(admin.password, adminPass): if hashPassword.check_password(admin.password, adminPass):
pass pass
else: else:
@@ -106,6 +126,11 @@ def changeUserPassAPI(request):
admin = Administrator.objects.get(userName=adminUser) admin = Administrator.objects.get(userName=adminUser)
if admin.api == 0:
data_ret = {"changeStatus": 0, 'error_message': "API Access Disabled."}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
if hashPassword.check_password(admin.password, adminPass): if hashPassword.check_password(admin.password, adminPass):
pass pass
else: else:
@@ -143,6 +168,11 @@ def changePackageAPI(request):
admin = Administrator.objects.get(userName=adminUser) admin = Administrator.objects.get(userName=adminUser)
if admin.api == 0:
data_ret = {"changePackage": 0, 'error_message': "API Access Disabled."}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
if hashPassword.check_password(admin.password, adminPass): if hashPassword.check_password(admin.password, adminPass):
pass pass
else: else:
@@ -173,12 +203,19 @@ def deleteWebsite(request):
try: try:
if request.method == 'POST': if request.method == 'POST':
data = json.loads(request.body) data = json.loads(request.body)
data['websiteName'] = data['domainName']
adminUser = data['adminUser'] adminUser = data['adminUser']
adminPass = data['adminPass'] adminPass = data['adminPass']
admin = Administrator.objects.get(userName=adminUser) admin = Administrator.objects.get(userName=adminUser)
if admin.api == 0:
data_ret = {"websiteDeleteStatus": 0, 'error_message': "API Access Disabled."}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
data['websiteName'] = data['domainName']
if hashPassword.check_password(admin.password, adminPass): if hashPassword.check_password(admin.password, adminPass):
pass pass
else: else:
@@ -212,6 +249,11 @@ def submitWebsiteStatus(request):
admin = Administrator.objects.get(userName=adminUser) admin = Administrator.objects.get(userName=adminUser)
if admin.api == 0:
data_ret = {"websiteStatus": 0, 'error_message': "API Access Disabled."}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
if hashPassword.check_password(admin.password, adminPass): if hashPassword.check_password(admin.password, adminPass):
pass pass
else: else:
@@ -235,6 +277,11 @@ def loginAPI(request):
admin = Administrator.objects.get(userName=username) admin = Administrator.objects.get(userName=username)
if admin.api == 0:
data_ret = {"userID": 0, 'error_message': "API Access Disabled."}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
if hashPassword.check_password(admin.password, password): if hashPassword.check_password(admin.password, password):
request.session['userID'] = admin.pk request.session['userID'] = admin.pk
return redirect(renderBase) return redirect(renderBase)
@@ -255,6 +302,11 @@ def fetchSSHkey(request):
admin = Administrator.objects.get(userName=username) admin = Administrator.objects.get(userName=username)
if admin.api == 0:
data_ret = {"status": 0, 'error_message': "API Access Disabled."}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
if hashPassword.check_password(admin.password, password): if hashPassword.check_password(admin.password, password):
pubKey = os.path.join("/root",".ssh",'cyberpanel.pub') pubKey = os.path.join("/root",".ssh",'cyberpanel.pub')
@@ -290,11 +342,18 @@ def remoteTransfer(request):
data = json.loads(request.body) data = json.loads(request.body)
username = data['username'] username = data['username']
password = data['password'] password = data['password']
ipAddress = data['ipAddress']
accountsToTransfer = data['accountsToTransfer']
admin = Administrator.objects.get(userName=username) admin = Administrator.objects.get(userName=username)
if admin.api == 0:
data_ret = {"transferStatus": 0, 'error_message': "API Access Disabled."}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
ipAddress = data['ipAddress']
accountsToTransfer = data['accountsToTransfer']
if hashPassword.check_password(admin.password, password): if hashPassword.check_password(admin.password, password):
dir = str(randint(1000, 9999)) dir = str(randint(1000, 9999))
@@ -335,6 +394,12 @@ def fetchAccountsFromRemoteServer(request):
password = data['password'] password = data['password']
admin = Administrator.objects.get(userName=username) admin = Administrator.objects.get(userName=username)
if admin.api == 0:
data_ret = {"fetchStatus": 0, 'error_message': "API Access Disabled."}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
if hashPassword.check_password(admin.password, password): if hashPassword.check_password(admin.password, password):
records = Websites.objects.all() records = Websites.objects.all()
@@ -377,13 +442,20 @@ def FetchRemoteTransferStatus(request):
username = data['username'] username = data['username']
password = data['password'] password = data['password']
admin = Administrator.objects.get(userName=username)
if admin.api == 0:
data_ret = {"fetchStatus": 0, 'error_message': "API Access Disabled."}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
dir = "/home/backup/transfer-"+str(data['dir'])+"/backup_log" dir = "/home/backup/transfer-"+str(data['dir'])+"/backup_log"
try: try:
command = "sudo cat "+ dir command = "sudo cat "+ dir
status = ProcessUtilities.outputExecutioner(command) status = ProcessUtilities.outputExecutioner(command)
admin = Administrator.objects.get(userName=username)
if hashPassword.check_password(admin.password, password): if hashPassword.check_password(admin.password, password):
final_json = json.dumps({'fetchStatus': 1, 'error_message': "None", "status": status}) final_json = json.dumps({'fetchStatus': 1, 'error_message': "None", "status": status})
@@ -409,10 +481,18 @@ def cancelRemoteTransfer(request):
data = json.loads(request.body) data = json.loads(request.body)
username = data['username'] username = data['username']
password = data['password'] password = data['password']
dir = "/home/backup/transfer-"+str(data['dir'])
admin = Administrator.objects.get(userName=username) admin = Administrator.objects.get(userName=username)
if admin.api == 0:
data_ret = {"cancelStatus": 0, 'error_message': "API Access Disabled."}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
dir = "/home/backup/transfer-"+str(data['dir'])
if hashPassword.check_password(admin.password, password): if hashPassword.check_password(admin.password, password):
path = dir + "/pid" path = dir + "/pid"
@@ -453,6 +533,11 @@ def cyberPanelVersion(request):
admin = Administrator.objects.get(userName=adminUser) admin = Administrator.objects.get(userName=adminUser)
if admin.api == 0:
data_ret = {"getVersion": 0, 'error_message': "API Access Disabled."}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
if hashPassword.check_password(admin.password, adminPass): if hashPassword.check_password(admin.password, adminPass):
Version = version.objects.get(pk=1) Version = version.objects.get(pk=1)
@@ -482,167 +567,6 @@ def cyberPanelVersion(request):
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
def putSSHkey(request):
try:
if request.method == 'POST':
data = json.loads(request.body)
adminUser = data['username']
adminPass = data['password']
pubKey = data['putSSHKey']
admin = Administrator.objects.get(userName=adminUser)
if hashPassword.check_password(admin.password, adminPass):
keyPath = "/home/cyberpanel/.ssh"
if not os.path.exists(keyPath):
os.makedirs(keyPath)
## writeKey
authorized_keys = keyPath+"/authorized_keys"
presenseCheck = 0
try:
data = open(authorized_keys, "r").readlines()
for items in data:
if items.find(pubKey) > -1:
presenseCheck = 1
except:
pass
if presenseCheck == 0:
writeToFile = open(authorized_keys, 'a')
writeToFile.writelines("#Added by CyberPanel\n")
writeToFile.writelines("\n")
writeToFile.writelines(pubKey)
writeToFile.writelines("\n")
writeToFile.close()
##
command = "sudo chmod g-w /home/cyberpanel"
ProcessUtilities.executioner(command)
os.chmod(keyPath,0700)
os.chmod(authorized_keys, 0600)
data_ret = {"putSSHKey": 1,
'error_message': "None",}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
else:
data_ret = {"putSSHKey": 0,
'error_message': "Could not authorize access to API"}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except BaseException, msg:
data_ret = {"putSSHKey": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
def changeAdminPassword(request):
try:
data = json.loads(request.body)
adminPass = data['password']
randomFile = data['randomFile']
if os.path.exists(randomFile):
numberOfAdministrator = Administrator.objects.count()
if numberOfAdministrator == 0:
ACLManager.createDefaultACLs()
acl = ACL.objects.get(name='admin')
token = hashPassword.generateToken('admin', '1234567')
email = 'usman@cyberpersons.com'
admin = Administrator(userName="admin", password=hashPassword.hash_password(adminPass), type=1, email=email,
firstName="Cyber", lastName="Panel", acl=acl, token=token)
admin.save()
vers = version(currentVersion="1.8", build=1)
vers.save()
package = Package(admin=admin, packageName="Default", diskSpace=1000,
bandwidth=1000, ftpAccounts=1000, dataBases=1000,
emailAccounts=1000, allowedDomains=20)
package.save()
newFWRule = FirewallRules(name="panel", proto="tcp", port="8090")
newFWRule.save()
newFWRule = FirewallRules(name="http", proto="tcp", port="80")
newFWRule.save()
newFWRule = FirewallRules(name="https", proto="tcp", port="443")
newFWRule.save()
newFWRule = FirewallRules(name="ftp", proto="tcp", port="21")
newFWRule.save()
newFWRule = FirewallRules(name="smtp", proto="tcp", port="25")
newFWRule.save()
newFWRule = FirewallRules(name="smtps", proto="tcp", port="587")
newFWRule.save()
newFWRule = FirewallRules(name="ssmtp", proto="tcp", port="465")
newFWRule.save()
newFWRule = FirewallRules(name="pop3", proto="tcp", port="110")
newFWRule.save()
newFWRule = FirewallRules(name="imap", proto="tcp", port="143")
newFWRule.save()
newFWRule = FirewallRules(name="simap", proto="tcp", port="993")
newFWRule.save()
newFWRule = FirewallRules(name="dns", proto="udp", port="53")
newFWRule.save()
newFWRule = FirewallRules(name="dnstcp", proto="tcp", port="53")
newFWRule.save()
newFWRule = FirewallRules(name="ftptls", proto="tcp", port="40110-40210")
newFWRule.save()
data_ret = {"changed": 1,
'error_message': "None"}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
os.remove(randomFile)
token = hashPassword.generateToken('admin', adminPass)
admin = Administrator.objects.get(userName="admin")
admin.password = hashPassword.hash_password(adminPass)
admin.token = token
admin.save()
data_ret = {"changed": 1,
'error_message': "None"}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
else:
data_ret = {"changed": 0,
'error_message': "Failed to authorize access to change password!"}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except BaseException, msg:
data_ret = {"changed": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
def runAWSBackups(request): def runAWSBackups(request):
try: try:

View File

@@ -401,6 +401,9 @@
<li class="serverACL"><a href="{% url 'modifyACL' %}" <li class="serverACL"><a href="{% url 'modifyACL' %}"
title="{% trans 'Modify ACL' %}"><span>{% trans "Modify ACL" %}</span></a> title="{% trans 'Modify ACL' %}"><span>{% trans "Modify ACL" %}</span></a>
</li> </li>
<li class="serverACL"><a href="{% url 'apiAccess' %}"
title="{% trans 'API Access' %}"><span>{% trans "API Access" %}</span></a>
</li>
</ul> </ul>
</div><!-- .sidebar-submenu --> </div><!-- .sidebar-submenu -->

View File

@@ -17,6 +17,9 @@ def router(request):
cm = CloudManager(data, admin) cm = CloudManager(data, admin)
if admin.api == 0:
return cm.ajaxPre(0, 'API Access Disabled.')
if controller == 'statusFunc': if controller == 'statusFunc':
pass pass
else: else:

0
containerization/container.py Executable file → Normal file
View File

View File

@@ -86,6 +86,8 @@ class ContainerManager(multi.Thread):
execPath = "sudo python /usr/local/CyberCP/dockerManager/dockerInstall.py" execPath = "sudo python /usr/local/CyberCP/dockerManager/dockerInstall.py"
ProcessUtilities.executioner(execPath) ProcessUtilities.executioner(execPath)
time.sleep(2)
except BaseException, msg: except BaseException, msg:
logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, str(msg) + ' [404].', 1) logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, str(msg) + ' [404].', 1)

View File

@@ -2,7 +2,6 @@
import sys import sys
sys.path.append('/usr/local/CyberCP') sys.path.append('/usr/local/CyberCP')
import plogical.CyberCPLogFileWriter as logging import plogical.CyberCPLogFileWriter as logging
from plogical.mailUtilities import mailUtilities
from serverStatus.serverStatusUtil import ServerStatusUtil from serverStatus.serverStatusUtil import ServerStatusUtil
from plogical.processUtilities import ProcessUtilities from plogical.processUtilities import ProcessUtilities
import time import time
@@ -14,8 +13,6 @@ class DockerInstall:
def submitInstallDocker(): def submitInstallDocker():
try: try:
mailUtilities.checkHome()
statusFile = open(ServerStatusUtil.lswsInstallStatusPath, 'w') statusFile = open(ServerStatusUtil.lswsInstallStatusPath, 'w')
logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath,

View File

@@ -248,8 +248,8 @@ class FirewallManager:
command = 'sudo systemctl status firewalld' command = 'sudo systemctl status firewalld'
status = ProcessUtilities.outputExecutioner(command) status = ProcessUtilities.outputExecutioner(command)
if status.find("active") > -1: if status.find("dead") > -1:
final_dic = {'status': 1, 'error_message': "none", 'firewallStatus': 1} final_dic = {'status': 1, 'error_message': "none", 'firewallStatus': 0}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
return HttpResponse(final_json) return HttpResponse(final_json)
else: else:
@@ -552,8 +552,6 @@ class FirewallManager:
}) })
return HttpResponse(final_json) return HttpResponse(final_json)
installUtilities.reStartLiteSpeed()
final_json = json.dumps({ final_json = json.dumps({
'error_message': "None", 'error_message': "None",
'requestStatus': installStatus, 'requestStatus': installStatus,
@@ -790,7 +788,6 @@ class FirewallManager:
output = ProcessUtilities.outputExecutioner(execPath) output = ProcessUtilities.outputExecutioner(execPath)
if output.find("1,None") > -1: if output.find("1,None") > -1:
installUtilities.reStartLiteSpeed()
data_ret = {'saveStatus': 1, 'error_message': "None"} data_ret = {'saveStatus': 1, 'error_message': "None"}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@@ -846,7 +843,6 @@ class FirewallManager:
output = ProcessUtilities.outputExecutioner(execPath) output = ProcessUtilities.outputExecutioner(execPath)
if output.find("1,None") > -1: if output.find("1,None") > -1:
installUtilities.reStartLiteSpeed()
data_ret = {'saveStatus': 1, 'error_message': "None"} data_ret = {'saveStatus': 1, 'error_message': "None"}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@@ -971,7 +967,6 @@ class FirewallManager:
output = ProcessUtilities.outputExecutioner(execPath).split('\n') output = ProcessUtilities.outputExecutioner(execPath).split('\n')
if output.find("1,None") > -1: if output.find("1,None") > -1:
installUtilities.reStartLiteSpeed()
data_ret = {'saveStatus': 1, 'error_message': "None"} data_ret = {'saveStatus': 1, 'error_message': "None"}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@@ -1115,7 +1110,6 @@ class FirewallManager:
output = ProcessUtilities.outputExecutioner(execPath) output = ProcessUtilities.outputExecutioner(execPath)
if output.find("1,None") > -1: if output.find("1,None") > -1:
installUtilities.reStartLiteSpeed()
data_ret = {'installStatus': 1, 'error_message': "None"} data_ret = {'installStatus': 1, 'error_message': "None"}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@@ -1133,7 +1127,6 @@ class FirewallManager:
output = ProcessUtilities.outputExecutioner(execPath) output = ProcessUtilities.outputExecutioner(execPath)
if output.find("1,None") > -1: if output.find("1,None") > -1:
installUtilities.reStartLiteSpeed()
data_ret = {'installStatus': 1, 'error_message': "None"} data_ret = {'installStatus': 1, 'error_message': "None"}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@@ -1276,7 +1269,6 @@ class FirewallManager:
output = ProcessUtilities.outputExecutioner(execPath) output = ProcessUtilities.outputExecutioner(execPath)
if output.find("1,None") > -1: if output.find("1,None") > -1:
installUtilities.reStartLiteSpeed()
data_ret = {'saveStatus': 1, 'error_message': "None"} data_ret = {'saveStatus': 1, 'error_message': "None"}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)

View File

@@ -96,22 +96,25 @@ class preFlightsChecks:
def mountTemp(self): def mountTemp(self):
try: try:
command = "mkdir -p /root/images/" command = "dd if=/dev/zero of=/usr/.tempdisk bs=100M count=15"
preFlightsChecks.call(command, self.distro, '[mountTemp]', preFlightsChecks.call(command, self.distro, '[mountTemp]',
'mountTemp', 'mountTemp',
1, 0, os.EX_OSERR) 1, 0, os.EX_OSERR)
command = "dd if=/dev/zero of=/root/images/tmpfile.bin bs=1 count=0 seek=4G" command = "mkfs.ext4 -F /usr/.tempdisk"
preFlightsChecks.call(command, self.distro, '[mountTemp]', preFlightsChecks.call(command, self.distro, '[mountTemp]',
'mountTemp', 'mountTemp',
1, 0, os.EX_OSERR) 1, 0, os.EX_OSERR)
command = "mkfs.ext4 -F /root/images/tmpfile.bin" command = "mkdir -p /usr/.tmpbak/"
preFlightsChecks.call(command, self.distro, '[mountTemp]', preFlightsChecks.call(command, self.distro, '[mountTemp]',
'mountTemp', 'mountTemp',
1, 0, os.EX_OSERR) 1, 0, os.EX_OSERR)
command = "mount -o loop,rw,nodev,nosuid,noexec /root/images/tmpfile.bin /tmp" command = "cp -pr /tmp/* /usr/.tmpbak/"
subprocess.call(command, shell=True)
command = "mount -o loop,rw,nodev,nosuid,noexec,nofail /usr/.tempdisk /tmp"
preFlightsChecks.call(command, self.distro, '[mountTemp]', preFlightsChecks.call(command, self.distro, '[mountTemp]',
'mountTemp', 'mountTemp',
1, 0, os.EX_OSERR) 1, 0, os.EX_OSERR)
@@ -121,17 +124,26 @@ class preFlightsChecks:
'mountTemp', 'mountTemp',
1, 0, os.EX_OSERR) 1, 0, os.EX_OSERR)
command = "mount -o rw,noexec,nosuid,nodev,bind /tmp /var/tmp" command = "cp -pr /usr/.tmpbak/* /tmp/"
subprocess.call(command, shell=True)
command = "rm -rf /usr/.tmpbak"
preFlightsChecks.call(command, self.distro, '[mountTemp]', preFlightsChecks.call(command, self.distro, '[mountTemp]',
'mountTemp', 'mountTemp',
1, 0, os.EX_OSERR) 1, 0, os.EX_OSERR)
tmp = "/root/images/tmpfile.bin /tmp ext4 loop,rw,noexec,nosuid,nodev 0 0\n" command = "mount --bind /tmp /var/tmp"
varTmp = "/tmp /var/tmp none rw,noexec,nosuid,nodev,bind 0 0\n" preFlightsChecks.call(command, self.distro, '[mountTemp]',
'mountTemp',
1, 0, os.EX_OSERR)
tmp = "/usr/.tempdisk /tmp ext4 loop,rw,noexec,nosuid,nodev,nofail 0 0\n"
varTmp = "/tmp /var/tmp none bind 0 0\n"
fstab = "/etc/fstab" fstab = "/etc/fstab"
writeToFile = open(fstab, "a") writeToFile = open(fstab, "a")
writeToFile.writelines(tmp); writeToFile.writelines(tmp)
writeToFile.writelines(varTmp) writeToFile.writelines(varTmp)
writeToFile.close() writeToFile.close()
@@ -218,23 +230,23 @@ class preFlightsChecks:
count = 0 count = 0
if self.distro == ubuntu: if self.distro == ubuntu:
self.stdOut("Fix sudoers") # self.stdOut("Fix sudoers")
try: # try:
fileName = '/etc/sudoers' # fileName = '/etc/sudoers'
data = open(fileName, 'r').readlines() # data = open(fileName, 'r').readlines()
#
writeDataToFile = open(fileName, 'w') # writeDataToFile = open(fileName, 'w')
for line in data: # for line in data:
if line[:5] == '%sudo': # if line[:5] == '%sudo':
writeDataToFile.write('%sudo ALL=(ALL:ALL) NOPASSWD: ALL\n') # writeDataToFile.write('%sudo ALL=(ALL:ALL) NOPASSWD: ALL\n')
else: # else:
writeDataToFile.write(line) # writeDataToFile.write(line)
writeDataToFile.close() # writeDataToFile.close()
except IOError as err: # except IOError as err:
self.stdOut("Error in fixing sudoers file: " + str(err), 1, 1, os.EX_OSERR) # self.stdOut("Error in fixing sudoers file: " + str(err), 1, 1, os.EX_OSERR)
self.stdOut("Add Cyberpanel user") self.stdOut("Add Cyberpanel user")
command = "useradd cyberpanel -m -U -G sudo" command = "adduser --disabled-login cyberpanel"
cmd = shlex.split(command) cmd = shlex.split(command)
res = subprocess.call(cmd) res = subprocess.call(cmd)
if res != 0 and res != 9: if res != 0 and res != 9:
@@ -246,33 +258,33 @@ class preFlightsChecks:
preFlightsChecks.stdOut("CyberPanel user added") preFlightsChecks.stdOut("CyberPanel user added")
else: else:
command = "adduser cyberpanel" command = "useradd -s /bin/false cyberpanel"
preFlightsChecks.call(command, self.distro, '[setup_account_cyberpanel]', preFlightsChecks.call(command, self.distro, '[setup_account_cyberpanel]',
'add user cyberpanel', 'add user cyberpanel',
1, 0, os.EX_OSERR) 1, 0, os.EX_OSERR)
## # ##
#
command = "usermod -aG wheel cyberpanel" # command = "usermod -aG wheel cyberpanel"
preFlightsChecks.call(command, self.distro, '[setup_account_cyberpanel]', # preFlightsChecks.call(command, self.distro, '[setup_account_cyberpanel]',
'add user cyberpanel', # 'add user cyberpanel',
1, 0, os.EX_OSERR) # 1, 0, os.EX_OSERR)
############################### ###############################
path = "/etc/sudoers" # path = "/etc/sudoers"
#
data = open(path, 'r').readlines() # data = open(path, 'r').readlines()
#
writeToFile = open(path, 'w') # writeToFile = open(path, 'w')
#
for items in data: # for items in data:
if items.find("wheel ALL=(ALL) NOPASSWD: ALL") > -1: # if items.find("wheel ALL=(ALL) NOPASSWD: ALL") > -1:
writeToFile.writelines("%wheel ALL=(ALL) NOPASSWD: ALL") # writeToFile.writelines("%wheel ALL=(ALL) NOPASSWD: ALL")
else: # else:
writeToFile.writelines(items) # writeToFile.writelines(items)
#
writeToFile.close() # writeToFile.close()
############################### ###############################
@@ -708,65 +720,65 @@ class preFlightsChecks:
os._exit(os.EX_OSERR) os._exit(os.EX_OSERR)
def install_gunicorn(self): def install_gunicorn(self):
self.stdOut("Install GUnicorn") self.stdOut("Install Gunicorn")
count = 0 count = 0
while (1): # while (1):
if self.distro == ubuntu: # if self.distro == ubuntu:
command = "pip install gunicorn" # command = "pip install gunicorn"
else: # else:
command = "easy_install gunicorn" # command = "easy_install gunicorn"
res = subprocess.call(shlex.split(command)) # res = subprocess.call(shlex.split(command))
if preFlightsChecks.resFailed(self.distro, res): # if preFlightsChecks.resFailed(self.distro, res):
count = count + 1 # count = count + 1
preFlightsChecks.stdOut("Unable to install GUNICORN, trying again, try number: " + str(count)) # preFlightsChecks.stdOut("Unable to install GUNICORN, trying again, try number: " + str(count))
if count == 3: # if count == 3:
logging.InstallLog.writeToFile("Unable to install GUNICORN, exiting installer! [install_gunicorn]") # logging.InstallLog.writeToFile("Unable to install GUNICORN, exiting installer! [install_gunicorn]")
preFlightsChecks.stdOut("Installation failed, consult: /var/log/installLogs.txt") # preFlightsChecks.stdOut("Installation failed, consult: /var/log/installLogs.txt")
os._exit(0) # os._exit(0)
else: # else:
logging.InstallLog.writeToFile("GUNICORN successfully installed!") # logging.InstallLog.writeToFile("GUNICORN successfully installed!")
preFlightsChecks.stdOut("GUNICORN successfully installed!") # preFlightsChecks.stdOut("GUNICORN successfully installed!")
break # break
def setup_gunicorn(self): def setup_gunicorn(self):
try: try:
os.chdir(self.cwd) os.chdir(self.cwd)
#
## # ##
#
logging.InstallLog.writeToFile("Configuring Gunicorn..") # logging.InstallLog.writeToFile("Configuring Gunicorn..")
#
service = "/etc/systemd/system/gunicorn.service" # service = "/etc/systemd/system/gunicorn.service"
socket = "/etc/systemd/system/gunicorn.socket" # socket = "/etc/systemd/system/gunicorn.socket"
conf = "/etc/tmpfiles.d/gunicorn.conf" # conf = "/etc/tmpfiles.d/gunicorn.conf"
#
shutil.copy("gun-configs/gunicorn.service", service) # shutil.copy("gun-configs/gunicorn.service", service)
shutil.copy("gun-configs/gunicorn.socket", socket) # shutil.copy("gun-configs/gunicorn.socket", socket)
shutil.copy("gun-configs/gunicorn.conf", conf) # shutil.copy("gun-configs/gunicorn.conf", conf)
#
logging.InstallLog.writeToFile("Gunicorn Configured!") # logging.InstallLog.writeToFile("Gunicorn Configured!")
#
### Enable at system startup # ### Enable at system startup
#
count = 0 # count = 0
#
while (1): # while (1):
command = "systemctl enable gunicorn.socket" # command = "systemctl enable gunicorn.socket"
res = subprocess.call(shlex.split(command)) # res = subprocess.call(shlex.split(command))
#
if preFlightsChecks.resFailed(self.distro, res): # if preFlightsChecks.resFailed(self.distro, res):
count = count + 1 # count = count + 1
preFlightsChecks.stdOut("Trying to enable Gunicorn at system startup, try number: " + str(count)) # preFlightsChecks.stdOut("Trying to enable Gunicorn at system startup, try number: " + str(count))
if count == 3: # if count == 3:
logging.InstallLog.writeToFile( # logging.InstallLog.writeToFile(
"Gunicorn will not start after system restart, you can manually enable using systemctl enable gunicorn.socket! [setup_gunicorn]") # "Gunicorn will not start after system restart, you can manually enable using systemctl enable gunicorn.socket! [setup_gunicorn]")
preFlightsChecks.stdOut("Installation failed, consult: /var/log/installLogs.txt") # preFlightsChecks.stdOut("Installation failed, consult: /var/log/installLogs.txt")
break # break
else: # else:
logging.InstallLog.writeToFile("Gunicorn can now start after system restart!") # logging.InstallLog.writeToFile("Gunicorn can now start after system restart!")
preFlightsChecks.stdOut("Gunicorn can now start after system restart!") # preFlightsChecks.stdOut("Gunicorn can now start after system restart!")
break # break
except BaseException, msg: except BaseException, msg:
logging.InstallLog.writeToFile(str(msg) + " [setup_gunicorn]") logging.InstallLog.writeToFile(str(msg) + " [setup_gunicorn]")
@@ -956,8 +968,11 @@ class preFlightsChecks:
'CyberPanel Migrate',1, 1, os.EX_OSERR) 'CyberPanel Migrate',1, 1, os.EX_OSERR)
if not os.path.exists("/usr/local/CyberCP/public"):
os.mkdir("/usr/local/CyberCP/public")
## Moving static content to lscpd location ## Moving static content to lscpd location
command = 'mv static /usr/local/lscp/cyberpanel' command = 'mv static /usr/local/CyberCP/public/'
preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]',
'Move static content', 1, 1, os.EX_OSERR) 'Move static content', 1, 1, os.EX_OSERR)
@@ -965,41 +980,49 @@ class preFlightsChecks:
###### fix Core CyberPanel permissions ###### fix Core CyberPanel permissions
command = "find /usr/local/CyberCP -type d -exec chmod 0755 {} \;" command = "find /usr/local/CyberCP -type d -exec chmod 0755 {} \;"
preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', preFlightsChecks.call(command, self.distro, '[fixCyberPanelPermissions]',
'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR) 'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR)
command = "find /usr/local/CyberCP -type f -exec chmod 0644 {} \;" command = "find /usr/local/CyberCP -type f -exec chmod 0644 {} \;"
preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', preFlightsChecks.call(command, self.distro, '[fixCyberPanelPermissions]',
'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR) 'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR)
command = "chmod -R 755 /usr/local/CyberCP/bin" command = "chmod -R 755 /usr/local/CyberCP/bin"
preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', preFlightsChecks.call(command, self.distro, '[fixCyberPanelPermissions]',
'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR) 'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR)
## change owner ## change owner
command = "chown -R root:root /usr/local/CyberCP" command = "chown -R root:root /usr/local/CyberCP"
preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', preFlightsChecks.call(command, self.distro, '[fixCyberPanelPermissions]',
'change owner /usr/local/CyberCP', 1, 0, os.EX_OSERR) 'change owner /usr/local/CyberCP', 1, 0, os.EX_OSERR)
########### Fix LSCPD ########### Fix LSCPD
command = "find /usr/local/lscp -type d -exec chmod 0755 {} \;" command = "find /usr/local/lscp -type d -exec chmod 0755 {} \;"
preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', preFlightsChecks.call(command, self.distro, '[fixCyberPanelPermissions]',
'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR) 'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR)
command = "find /usr/local/lscp -type f -exec chmod 0644 {} \;" command = "find /usr/local/lscp -type f -exec chmod 0644 {} \;"
preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', preFlightsChecks.call(command, self.distro, '[fixCyberPanelPermissions]',
'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR) 'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR)
command = "chmod -R 755 /usr/local/lscp/bin" command = "chmod -R 755 /usr/local/lscp/bin"
preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', preFlightsChecks.call(command, self.distro, '[fixCyberPanelPermissions]',
'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR)
command = "chmod -R 755 /usr/local/lscp/fcgi-bin"
preFlightsChecks.call(command, self.distro, '[fixCyberPanelPermissions]',
'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR)
command = "chown -R lscpd:lscpd /usr/local/CyberCP/public/rainloop/data"
preFlightsChecks.call(command, self.distro, '[fixCyberPanelPermissions]',
'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR) 'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR)
## change owner ## change owner
command = "chown -R root:root /usr/local/lscp" command = "chown -R root:root /usr/local/lscp"
preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', preFlightsChecks.call(command, self.distro, '[fixCyberPanelPermissions]',
'change owner /usr/local/CyberCP', 1, 0, os.EX_OSERR) 'change owner /usr/local/CyberCP', 1, 0, os.EX_OSERR)
@@ -1032,7 +1055,10 @@ class preFlightsChecks:
def download_install_phpmyadmin(self): def download_install_phpmyadmin(self):
try: try:
os.chdir("/usr/local/lscp/cyberpanel/") if not os.path.exists("/usr/local/CyberCP/public"):
os.mkdir("/usr/local/CyberCP/public")
os.chdir("/usr/local/CyberCP/public")
command = 'composer create-project phpmyadmin/phpmyadmin' command = 'composer create-project phpmyadmin/phpmyadmin'
preFlightsChecks.call(command, self.distro, '[download_install_phpmyadmin]', preFlightsChecks.call(command, self.distro, '[download_install_phpmyadmin]',
@@ -1053,13 +1079,13 @@ class preFlightsChecks:
else: else:
writeToFile.writelines(items) writeToFile.writelines(items)
writeToFile.writelines("$cfg['TempDir'] = '/usr/local/lscp/cyberpanel/phpmyadmin/tmp';\n") writeToFile.writelines("$cfg['TempDir'] = '/usr/local/CyberCP/public/phpmyadmin/tmp';\n")
writeToFile.close() writeToFile.close()
os.mkdir('/usr/local/lscp/cyberpanel/phpmyadmin/tmp') os.mkdir('/usr/local/CyberCP/public/phpmyadmin/tmp')
command = 'chown -R lscpd:lscpd /usr/local/lscp/cyberpanel/phpmyadmin' command = 'chown -R lscpd:lscpd /usr/local/CyberCP/public/phpmyadmin'
subprocess.call(shlex.split(command)) subprocess.call(shlex.split(command))
except BaseException, msg: except BaseException, msg:
@@ -2027,31 +2053,13 @@ class preFlightsChecks:
def downoad_and_install_raindloop(self): def downoad_and_install_raindloop(self):
try: try:
###########
count = 0
while (1):
command = 'chown -R lscpd:lscpd /usr/local/lscp/cyberpanel/'
cmd = shlex.split(command)
res = subprocess.call(cmd)
if preFlightsChecks.resFailed(self.distro, res):
count = count + 1
preFlightsChecks.stdOut(
"Trying to change owner for /usr/local/lscp/cyberpanel/, trying again, try number: " + str(
count))
if count == 3:
logging.InstallLog.writeToFile(
"Failed to change owner for /usr/local/lscp/cyberpanel/, but installer can continue! [downoad_and_install_raindloop]")
break
else:
logging.InstallLog.writeToFile("Owner changed for /usr/local/lscp/cyberpanel/!")
preFlightsChecks.stdOut("Owner changed for /usr/local/lscp/cyberpanel/!")
break
####### #######
os.chdir("/usr/local/lscp/cyberpanel") if not os.path.exists("/usr/local/CyberCP/public"):
os.mkdir("/usr/local/CyberCP/public")
os.chdir("/usr/local/CyberCP/public")
count = 1 count = 1
@@ -2079,7 +2087,7 @@ class preFlightsChecks:
count = 0 count = 0
while (1): while (1):
command = 'unzip rainloop-community-latest.zip -d /usr/local/lscp/cyberpanel/rainloop' command = 'unzip rainloop-community-latest.zip -d /usr/local/CyberCP/public/rainloop'
cmd = shlex.split(command) cmd = shlex.split(command)
@@ -2101,7 +2109,7 @@ class preFlightsChecks:
####### #######
os.chdir("/usr/local/lscp/cyberpanel/rainloop") os.chdir("/usr/local/CyberCP/public/rainloop")
count = 0 count = 0
@@ -2148,29 +2156,6 @@ class preFlightsChecks:
break break
###### ######
count = 0
while (1):
command = 'chown -R lscpd:lscpd .'
cmd = shlex.split(command)
res = subprocess.call(cmd)
if preFlightsChecks.resFailed(self.distro, res):
count = count + 1
preFlightsChecks.stdOut(
"Trying to change owner for Rainloop, trying again, try number: " + str(count))
if count == 3:
logging.InstallLog.writeToFile(
"Failed to change owner for Rainloop, so you will not be able to send emails!! [downoad_and_install_raindloop]")
break
else:
logging.InstallLog.writeToFile("Rainloop owner changed!")
preFlightsChecks.stdOut("Rainloop owner changed!")
break
except OSError, msg: except OSError, msg:
logging.InstallLog.writeToFile(str(msg) + " [downoad_and_install_rainloop]") logging.InstallLog.writeToFile(str(msg) + " [downoad_and_install_rainloop]")
@@ -2380,6 +2365,7 @@ class preFlightsChecks:
self.setupComodoRules() self.setupComodoRules()
self.setupPort() self.setupPort()
self.setupPythonWSGI()
logging.InstallLog.writeToFile("LSCPD successfully installed!") logging.InstallLog.writeToFile("LSCPD successfully installed!")
@@ -2428,7 +2414,7 @@ class preFlightsChecks:
SecAuditLogParts AFH SecAuditLogParts AFH
SecAuditLogType Serial SecAuditLogType Serial
SecAuditLog /usr/local/lscp/logs/auditmodsec.log SecAuditLog /usr/local/lscp/logs/auditmodsec.log
SecRuleEngine On SecRuleEngine Off
` `
modsecurity_rules_file /usr/local/lscp/modsec/comodo/modsecurity.conf modsecurity_rules_file /usr/local/lscp/modsec/comodo/modsecurity.conf
modsecurity_rules_file /usr/local/lscp/modsec/comodo/00_Init_Initialization.conf modsecurity_rules_file /usr/local/lscp/modsec/comodo/00_Init_Initialization.conf
@@ -2492,6 +2478,41 @@ class preFlightsChecks:
except: except:
return 0 return 0
def setupPythonWSGI(self):
try:
command = "wget http://www.litespeedtech.com/packages/lsapi/wsgi-lsapi-1.4.tgz"
preFlightsChecks.call(command, self.distro, '[setupPythonWSGI]',
'setupPythonWSGI',
1, 0, os.EX_OSERR)
command = "tar xf wsgi-lsapi-1.4.tgz"
preFlightsChecks.call(command, self.distro, '[setupPythonWSGI]',
'setupPythonWSGI',
1, 0, os.EX_OSERR)
os.chdir("wsgi-lsapi-1.4")
command = "python ./configure.py"
preFlightsChecks.call(command, self.distro, '[setupPythonWSGI]',
'setupPythonWSGI',
1, 0, os.EX_OSERR)
command = "make"
preFlightsChecks.call(command, self.distro, '[setupPythonWSGI]',
'setupPythonWSGI',
1, 0, os.EX_OSERR)
command = "cp lswsgi /usr/local/CyberCP/bin/"
preFlightsChecks.call(command, self.distro, '[setupPythonWSGI]',
'setupPythonWSGI',
1, 0, os.EX_OSERR)
os.chdir(self.cwd)
except:
return 0
def setupLSCPDDaemon(self): def setupLSCPDDaemon(self):
try: try:
@@ -2529,6 +2550,27 @@ class preFlightsChecks:
## ##
path = "/usr/local/lscpd/admin/"
command = "mkdir -p " + path
cmd = shlex.split(command)
res = subprocess.call(cmd)
path = "/usr/local/CyberCP/conf/"
command = "mkdir -p " + path
cmd = shlex.split(command)
res = subprocess.call(cmd)
path = "/usr/local/CyberCP/conf/token_env"
writeToFile = open(path, "w")
writeToFile.write("abc\n")
writeToFile.close()
command = "chmod 600 " + path
cmd = shlex.split(command)
res = subprocess.call(cmd)
count = 1 count = 1
while (1): while (1):
@@ -2885,45 +2927,8 @@ class preFlightsChecks:
command = "pip uninstall --yes certbot" command = "pip uninstall --yes certbot"
res = subprocess.call(shlex.split(command)) res = subprocess.call(shlex.split(command))
count = 0 command = 'wget -O - https://get.acme.sh | sh'
while (1): subprocess.call(command, shell=True)
command = "pip install http://" + preFlightsChecks.cyberPanelMirror + "/pyOpenSSL-17.5.0.tar.gz"
res = subprocess.call(shlex.split(command))
if preFlightsChecks.resFailed(self.distro, res):
count = count + 1
preFlightsChecks.stdOut(
"Trying to install pyOpenSSL, trying again, try number: " + str(count))
if count == 3:
logging.InstallLog.writeToFile(
"Failed to install pyOpenSSL, exiting installer! [installCertBot]")
preFlightsChecks.stdOut("Installation failed, consult: /var/log/installLogs.txt")
os._exit(0)
else:
logging.InstallLog.writeToFile("pyOpenSSL successfully installed! [pip]")
preFlightsChecks.stdOut("pyOpenSSL successfully installed! [pip]")
break
count = 0
while (1):
command = "pip install http://" + preFlightsChecks.cyberPanelMirror + "/certbot-0.21.1.tar.gz"
res = subprocess.call(shlex.split(command))
if preFlightsChecks.resFailed(self.distro, res):
count = count + 1
preFlightsChecks.stdOut(
"Trying to install CertBot, trying again, try number: " + str(count))
if count == 3:
logging.InstallLog.writeToFile(
"Failed to install CertBot, exiting installer! [installCertBot]")
preFlightsChecks.stdOut("Installation failed, consult: /var/log/installLogs.txt")
os._exit(0)
else:
logging.InstallLog.writeToFile("CertBot successfully installed! [pip]")
preFlightsChecks.stdOut("CertBot successfully installed! [pip]")
break
except OSError, msg: except OSError, msg:
logging.InstallLog.writeToFile(str(msg) + " [installCertBot]") logging.InstallLog.writeToFile(str(msg) + " [installCertBot]")
@@ -3321,8 +3326,8 @@ milter_default_action = accept
preFlightsChecks.stdOut("Python project dependant modules installed successfully!!") preFlightsChecks.stdOut("Python project dependant modules installed successfully!!")
break break
command = "systemctl restart gunicorn.socket" # command = "systemctl restart gunicorn.socket"
res = subprocess.call(shlex.split(command)) # res = subprocess.call(shlex.split(command))
command = "virtualenv --system-site-packages /usr/local/CyberCP" command = "virtualenv --system-site-packages /usr/local/CyberCP"
res = subprocess.call(shlex.split(command)) res = subprocess.call(shlex.split(command))
@@ -3509,8 +3514,7 @@ def main():
else: else:
installCyberPanel.Main(cwd, mysql, distro, ent, serial, port) installCyberPanel.Main(cwd, mysql, distro, ent, serial, port)
checks.installLSCPD()
checks.setupLSCPDDaemon()
checks.setupPHPAndComposer() checks.setupPHPAndComposer()
checks.fix_selinux_issue() checks.fix_selinux_issue()
checks.install_psmisc() checks.install_psmisc()
@@ -3521,8 +3525,6 @@ def main():
checks.install_unzip() checks.install_unzip()
checks.install_zip() checks.install_zip()
checks.install_rsync() checks.install_rsync()
checks.downoad_and_install_raindloop()
checks.download_install_phpmyadmin()
checks.installFirewalld() checks.installFirewalld()
@@ -3535,6 +3537,8 @@ def main():
checks.installPYDNS() checks.installPYDNS()
checks.installDockerPY() checks.installDockerPY()
checks.download_install_CyberPanel(installCyberPanel.InstallCyberPanel.mysqlPassword, mysql) checks.download_install_CyberPanel(installCyberPanel.InstallCyberPanel.mysqlPassword, mysql)
checks.downoad_and_install_raindloop()
checks.download_install_phpmyadmin()
checks.setupCLI() checks.setupCLI()
checks.setup_cron() checks.setup_cron()
checks.installTLDExtract() checks.installTLDExtract()
@@ -3547,6 +3551,8 @@ def main():
checks.modSecPreReqs() checks.modSecPreReqs()
checks.setupVirtualEnv(distro) checks.setupVirtualEnv(distro)
checks.installLSCPD()
checks.setupLSCPDDaemon()
checks.fixCyberPanelPermissions() checks.fixCyberPanelPermissions()

Binary file not shown.

View File

@@ -81,6 +81,7 @@ class Administrator(models.Model):
type = models.IntegerField() type = models.IntegerField()
owner = models.IntegerField(default=1) owner = models.IntegerField(default=1)
token = models.CharField(max_length=500, default='None') token = models.CharField(max_length=500, default='None')
api = models.IntegerField(default=0)
initWebsitesLimit = models.IntegerField(default=0) initWebsitesLimit = models.IntegerField(default=0)
acl = models.ForeignKey(ACL, default=1) acl = models.ForeignKey(ACL, default=1)

View File

@@ -149,26 +149,9 @@ def loadLoginPage(request):
numberOfAdministrator = Administrator.objects.count() numberOfAdministrator = Administrator.objects.count()
password = hashPassword.hash_password('1234567') password = hashPassword.hash_password('1234567')
noOfRules = FirewallRules.objects.count()
if numberOfAdministrator == 0: if noOfRules == 0:
ACLManager.createDefaultACLs()
acl = ACL.objects.get(name='admin')
token = hashPassword.generateToken('admin', '1234567')
email = 'usman@cyberpersons.com'
admin = Administrator(userName="admin", password=password, type=1,email=email,
firstName="Cyber",lastName="Panel", acl=acl, token=token)
admin.save()
vers = version(currentVersion="1.8", build=1)
vers.save()
package = Package(admin=admin, packageName="Default", diskSpace=1000,
bandwidth=1000, ftpAccounts=1000, dataBases=1000,
emailAccounts=1000,allowedDomains=20)
package.save()
newFWRule = FirewallRules(name="panel", proto="tcp", port="8090") newFWRule = FirewallRules(name="panel", proto="tcp", port="8090")
newFWRule.save() newFWRule.save()
@@ -208,6 +191,24 @@ def loadLoginPage(request):
newFWRule = FirewallRules(name="ftptls", proto="tcp", port="40110-40210") newFWRule = FirewallRules(name="ftptls", proto="tcp", port="40110-40210")
newFWRule.save() newFWRule.save()
if numberOfAdministrator == 0:
ACLManager.createDefaultACLs()
acl = ACL.objects.get(name='admin')
token = hashPassword.generateToken('admin', '1234567')
email = 'usman@cyberpersons.com'
admin = Administrator(userName="admin", password=password, type=1,email=email,
firstName="Cyber",lastName="Panel", acl=acl, token=token)
admin.save()
vers = version(currentVersion="1.8", build=1)
vers.save()
package = Package(admin=admin, packageName="Default", diskSpace=1000,
bandwidth=1000, ftpAccounts=1000, dataBases=1000,
emailAccounts=1000,allowedDomains=20)
package.save()
return render(request, 'loginSystem/login.html', {}) return render(request, 'loginSystem/login.html', {})
else: else:
return render(request, 'loginSystem/login.html', {}) return render(request, 'loginSystem/login.html', {})

View File

@@ -1332,7 +1332,6 @@ def getRequestStatus(request):
ext.status = 0 ext.status = 0
ext.save() ext.save()
installUtilities.reStartLiteSpeed()
final_json = json.dumps({'finished': 1, 'extensionRequestStatus': 1, final_json = json.dumps({'finished': 1, 'extensionRequestStatus': 1,
'error_message': "None", 'error_message': "None",
'requestStatus': requestStatus, 'requestStatus': requestStatus,
@@ -1349,7 +1348,6 @@ def getRequestStatus(request):
ext.status = 0 ext.status = 0
ext.save() ext.save()
installUtilities.reStartLiteSpeed()
final_json = json.dumps({'finished': 1, 'extensionRequestStatus': 1, final_json = json.dumps({'finished': 1, 'extensionRequestStatus': 1,
'error_message': "None", 'error_message': "None",
'requestStatus': requestStatus, 'requestStatus': requestStatus,
@@ -1366,7 +1364,6 @@ def getRequestStatus(request):
ext.status = 0 ext.status = 0
ext.save() ext.save()
installUtilities.reStartLiteSpeed()
final_json = json.dumps({'finished': 1, 'extensionRequestStatus': 1, final_json = json.dumps({'finished': 1, 'extensionRequestStatus': 1,
'error_message': "None", 'error_message': "None",
'requestStatus': requestStatus, 'requestStatus': requestStatus,
@@ -1378,7 +1375,6 @@ def getRequestStatus(request):
ext.status = 0 ext.status = 0
ext.save() ext.save()
installUtilities.reStartLiteSpeed()
final_json = json.dumps({'finished': 1, 'extensionRequestStatus': 1, final_json = json.dumps({'finished': 1, 'extensionRequestStatus': 1,
'error_message': "None", 'error_message': "None",
'requestStatus': requestStatus, 'requestStatus': requestStatus,

View File

@@ -1,29 +1,53 @@
#!/usr/local/CyberCP/bin/python2
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 import argparse
import requests from loginSystem.models import Administrator, ACL
import json from plogical import hashPassword
from random import randint from plogical.acl import ACLManager
from packages.models import Package
from baseTemplate.models import version
def main(): def main():
parser = argparse.ArgumentParser(description='Reset admin user password!') parser = argparse.ArgumentParser(description='Reset admin user password!')
parser.add_argument('--password', help='New Password') parser.add_argument('--password', help='New Password')
pathToFile = "/home/cyberpanel/"+str(randint(1000, 9999))
file = open(pathToFile,"w")
file.close()
args = parser.parse_args() args = parser.parse_args()
finalData = json.dumps({'password': args.password,'randomFile': pathToFile}) adminPass = args.password
r = requests.post("http://localhost:5003/api/changeAdminPassword", data=finalData,
verify=False)
data = json.loads(r.text) numberOfAdministrator = Administrator.objects.count()
if numberOfAdministrator == 0:
ACLManager.createDefaultACLs()
acl = ACL.objects.get(name='admin')
token = hashPassword.generateToken('admin', '1234567')
email = 'usman@cyberpersons.com'
admin = Administrator(userName="admin", password=hashPassword.hash_password(adminPass), type=1, email=email,
firstName="Cyber", lastName="Panel", acl=acl, token=token)
admin.save()
vers = version(currentVersion="1.8", build=1)
vers.save()
package = Package(admin=admin, packageName="Default", diskSpace=1000,
bandwidth=1000, ftpAccounts=1000, dataBases=1000,
emailAccounts=1000, allowedDomains=20)
package.save()
print("Admin password successfully changed!")
return 1
token = hashPassword.generateToken('admin', adminPass)
admin = Administrator.objects.get(userName="admin")
admin.password = hashPassword.hash_password(adminPass)
admin.token = token
admin.save()
if data['changed'] == 1:
print("Admin password successfully changed!") print("Admin password successfully changed!")
else:
print(data['error_message'])
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@@ -142,7 +142,7 @@ class installUtilities:
else: else:
command = "sudo /usr/local/lsws/bin/lswsctrl restart" command = "sudo /usr/local/lsws/bin/lswsctrl restart"
ProcessUtilities.executioner(command) ProcessUtilities.normalExecutioner(command)
except OSError, msg: except OSError, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [reStartLiteSpeed]") logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [reStartLiteSpeed]")

View File

@@ -8,6 +8,7 @@ import tarfile
import shutil import shutil
from mailUtilities import mailUtilities from mailUtilities import mailUtilities
from processUtilities import ProcessUtilities from processUtilities import ProcessUtilities
from plogical.installUtilities import installUtilities
class modSec: class modSec:
@@ -149,6 +150,8 @@ modsecurity_rules_file /usr/local/lsws/conf/modsec/rules.conf
conf.close() conf.close()
installUtilities.reStartLiteSpeed()
print "1,None" print "1,None"
return return
else: else:
@@ -181,6 +184,8 @@ modsecurity_rules_file /usr/local/lsws/conf/modsec/rules.conf
conf.close() conf.close()
installUtilities.reStartLiteSpeed()
print "1,None" print "1,None"
return return
@@ -205,7 +210,7 @@ modsecurity_rules_file /usr/local/lsws/conf/modsec/rules.conf
rulesFile.write(data) rulesFile.write(data)
rulesFile.close() rulesFile.close()
print data installUtilities.reStartLiteSpeed()
print "1,None" print "1,None"
return return
@@ -321,6 +326,7 @@ modsecurity_rules_file /usr/local/lsws/conf/modsec/rules.conf
conf.close() conf.close()
installUtilities.reStartLiteSpeed()
print "1,None" print "1,None"
return return
else: else:
@@ -344,6 +350,7 @@ modsecurity_rules_file /usr/local/lsws/conf/modsec/rules.conf
command = 'sudo chown -R lsadm:lsadm /usr/local/lsws/conf' command = 'sudo chown -R lsadm:lsadm /usr/local/lsws/conf'
subprocess.call(shlex.split(command)) subprocess.call(shlex.split(command))
installUtilities.reStartLiteSpeed()
print "1,None" print "1,None"
return return
@@ -368,6 +375,7 @@ modsecurity_rules_file /usr/local/lsws/conf/modsec/rules.conf
conf.writelines(items) conf.writelines(items)
conf.close() conf.close()
installUtilities.reStartLiteSpeed()
print "1,None" print "1,None"
@@ -376,6 +384,8 @@ modsecurity_rules_file /usr/local/lsws/conf/modsec/rules.conf
shutil.rmtree('/usr/local/lsws/conf/comodo_litespeed') shutil.rmtree('/usr/local/lsws/conf/comodo_litespeed')
except BaseException, msg: except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + ' [disableComodo]') logging.CyberCPLogFileWriter.writeToFile(str(msg) + ' [disableComodo]')
installUtilities.reStartLiteSpeed()
print "1,None" print "1,None"
@@ -520,6 +530,8 @@ modsecurity_rules_file /usr/local/lsws/conf/modsec/owasp/rules/RESPONSE-999-EXCL
command = 'mv ' + completePath + ' ' + completePathBak command = 'mv ' + completePath + ' ' + completePathBak
ProcessUtilities.executioner(command) ProcessUtilities.executioner(command)
installUtilities.reStartLiteSpeed()
print "1,None" print "1,None"
except BaseException, msg: except BaseException, msg:
@@ -551,6 +563,8 @@ modsecurity_rules_file /usr/local/lsws/conf/modsec/owasp/rules/RESPONSE-999-EXCL
command = 'mv ' + completePathBak + ' ' + completePath command = 'mv ' + completePathBak + ' ' + completePath
ProcessUtilities.executioner(command) ProcessUtilities.executioner(command)
installUtilities.reStartLiteSpeed()
print "1,None" print "1,None"
except BaseException, msg: except BaseException, msg:

View File

@@ -33,12 +33,15 @@ class phpUtilities:
writeToFile.writelines("PHP Extension Installed.\n") writeToFile.writelines("PHP Extension Installed.\n")
writeToFile.close() writeToFile.close()
installUtilities.installUtilities.reStartLiteSpeed()
return 1 return 1
except: except:
writeToFile = open(phpUtilities.installLogPath, 'a') writeToFile = open(phpUtilities.installLogPath, 'a')
writeToFile.writelines("Can not be installed.\n") writeToFile.writelines("Can not be installed.\n")
writeToFile.close() writeToFile.close()
logging.CyberCPLogFileWriter.writeToFile("[Could not Install]") logging.CyberCPLogFileWriter.writeToFile("[Could not Install]")
installUtilities.installUtilities.reStartLiteSpeed()
return 0 return 0
except BaseException, msg: except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[installPHPExtension]") logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[installPHPExtension]")
@@ -64,12 +67,14 @@ class phpUtilities:
writeToFile = open(phpUtilities.installLogPath, 'a') writeToFile = open(phpUtilities.installLogPath, 'a')
writeToFile.writelines("PHP Extension Removed.\n") writeToFile.writelines("PHP Extension Removed.\n")
writeToFile.close() writeToFile.close()
installUtilities.installUtilities.reStartLiteSpeed()
return 1 return 1
except: except:
writeToFile = open(phpUtilities.installLogPath, 'a') writeToFile = open(phpUtilities.installLogPath, 'a')
writeToFile.writelines("Can not un-install Extension.\n") writeToFile.writelines("Can not un-install Extension.\n")
writeToFile.close() writeToFile.close()
logging.CyberCPLogFileWriter.writeToFile("[Could not Install]") logging.CyberCPLogFileWriter.writeToFile("[Could not Install]")
installUtilities.installUtilities.reStartLiteSpeed()
return 0 return 0
except BaseException, msg: except BaseException, msg:

View File

@@ -2,13 +2,29 @@ from CyberCPLogFileWriter import CyberCPLogFileWriter as logging
import subprocess import subprocess
import shlex import shlex
import os import os
import socket
import threading as multi
class ProcessUtilities: class ProcessUtilities(multi.Thread):
litespeedProcess = "litespeed" litespeedProcess = "litespeed"
ent = 1 ent = 1
OLS = 0 OLS = 0
centos = 1 centos = 1
ubuntu = 0 ubuntu = 0
server_address = '/usr/local/lscpd/admin/comm.sock'
token = "2dboNyhseD7ro8rRUsJGy9AlLxJtSjHI"
def __init__(self, function, extraArgs):
multi.Thread.__init__(self)
self.function = function
self.extraArgs = extraArgs
def run(self):
try:
if self.function == 'popen':
self.customPoen()
except BaseException, msg:
logging.writeToFile( str(msg) + ' [ApplicationInstaller.run]')
@staticmethod @staticmethod
def getLitespeedProcessNumber(): def getLitespeedProcessNumber():
@@ -126,37 +142,91 @@ class ProcessUtilities:
except BaseException: except BaseException:
return 0 return 0
@staticmethod
def setupUDSConnection():
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(ProcessUtilities.server_address)
return [sock, "None"]
except BaseException, msg:
logging.writeToFile(str(msg) + ". [setupUDSConnection:138]")
return [-1, str(msg)]
@staticmethod
def sendCommand(command):
try:
ret = ProcessUtilities.setupUDSConnection()
if ret[0] == -1:
return ret[0]
token = os.environ.get('TOKEN')
sock = ret[0]
sock.sendall(token + command)
data = ""
while (1):
currentData = sock.recv(32)
if len(currentData) == 0 or currentData == None:
break
data = data + currentData
sock.close()
logging.writeToFile(data)
return data
except BaseException, msg:
logging.writeToFile(str(msg) + " [sendCommand]")
return "0" + str(msg)
@staticmethod @staticmethod
def executioner(command): def executioner(command):
try: try:
logging.writeToFile(command) logging.writeToFile(command)
res = subprocess.call(shlex.split(command)) ProcessUtilities.sendCommand(command)
if res == 0:
return 1 return 1
else:
return 0
except BaseException, msg: except BaseException, msg:
logging.writeToFile(str(msg) + " [executioner]")
return 0 return 0
@staticmethod @staticmethod
def outputExecutioner(command): def outputExecutioner(command):
try:
if type(command) == str or type(command) == unicode: if type(command) == str or type(command) == unicode:
logging.writeToFile(command) logging.writeToFile(command)
return subprocess.check_output(shlex.split(command))
else: else:
command = " ".join(command) command = " ".join(command)
logging.writeToFile(command + " join") logging.writeToFile(command)
return subprocess.check_output(shlex.split(command))
return ProcessUtilities.sendCommand(command)
except BaseException, msg:
logging.writeToFile(str(msg) + "[outputExecutioner:188]")
def customPoen(self):
try:
if type(self.extraArgs['command']) == str or type(self.extraArgs['command']) == unicode:
command = self.extraArgs['command']
logging.writeToFile(self.extraArgs['command'])
else:
command = " ".join(self.extraArgs['command'])
logging.writeToFile(command)
ProcessUtilities.sendCommand(command)
return 1
except BaseException, msg:
logging.writeToFile(str(msg) + " [customPoen]")
@staticmethod @staticmethod
def popenExecutioner(command): def popenExecutioner(command):
if type(command) == str or type(command) == unicode: try:
logging.writeToFile(command) extraArgs = {}
return subprocess.Popen(shlex.split(command)) extraArgs['command'] = command
else: pu = ProcessUtilities("popen", extraArgs)
command = " ".join(command) pu.start()
logging.writeToFile(command) except BaseException, msg:
return subprocess.Popen(shlex.split(command)) logging.writeToFile(str(msg) + " [popenExecutioner]")

View File

@@ -231,12 +231,8 @@ class sslUtilities:
try: try:
acmePath = '/root/.acme.sh/acme.sh' acmePath = '/root/.acme.sh/acme.sh'
if ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu: # if ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu:
acmePath = '/home/cyberpanel/.acme.sh/acme.sh' # acmePath = '/home/cyberpanel/.acme.sh/acme.sh'
if not os.path.exists(acmePath):
command = 'wget -O - https://get.acme.sh | sh'
subprocess.call(command, shell=True)
if aliasDomain == None: if aliasDomain == None:

View File

@@ -1002,7 +1002,7 @@ class virtualHostUtilities:
def getDiskUsage(path, totalAllowed): def getDiskUsage(path, totalAllowed):
try: try:
totalUsageInMB = subprocess.check_output(["sudo", "du", "-hs", path, "--block-size=1M"]).split()[0] totalUsageInMB = ProcessUtilities.outputExecutioner(["sudo", "du", "-hs", path, "--block-size=1M"]).split()[0]
percentage = float(100) / float(totalAllowed) percentage = float(100) / float(totalAllowed)

View File

@@ -564,7 +564,7 @@ class WebsiteManager:
execPath = execPath + " findDomainBW --virtualHostName " + self.domain + " --bandwidth " + str( execPath = execPath + " findDomainBW --virtualHostName " + self.domain + " --bandwidth " + str(
website.package.bandwidth) website.package.bandwidth)
output = subprocess.check_output(shlex.split(execPath)) output = ProcessUtilities.outputExecutioner(execPath)
bwData = output.split(",") bwData = output.split(",")
except BaseException, msg: except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg)) logging.CyberCPLogFileWriter.writeToFile(str(msg))
@@ -629,7 +629,7 @@ class WebsiteManager:
execPath = execPath + " findDomainBW --virtualHostName " + self.domain + " --bandwidth " + str( execPath = execPath + " findDomainBW --virtualHostName " + self.domain + " --bandwidth " + str(
website.package.bandwidth) website.package.bandwidth)
output = subprocess.check_output(shlex.split(execPath)) output = ProcessUtilities.outputExecutioner(execPath)
bwData = output.split(",") bwData = output.split(",")
except BaseException, msg: except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg)) logging.CyberCPLogFileWriter.writeToFile(str(msg))

View File

@@ -310,6 +310,9 @@ def servicesAction(request):
command = 'sudo systemctl %s %s' % (action, service) command = 'sudo systemctl %s %s' % (action, service)
ProcessUtilities.executioner(command) ProcessUtilities.executioner(command)
final_dic = {'serviceAction': 1, "error_message": 0}
final_json = json.dumps(final_dic)
return HttpResponse(final_json)
except BaseException, msg: except BaseException, msg:
@@ -358,10 +361,14 @@ def switchTOLSWSStatus(request):
output = ProcessUtilities.outputExecutioner(command) output = ProcessUtilities.outputExecutioner(command)
if output.find('[404]') > -1: if output.find('[404]') > -1:
command = "sudo rm -f " + serverStatusUtil.ServerStatusUtil.lswsInstallStatusPath
ProcessUtilities.popenExecutioner(command)
data_ret = {'abort': 1, 'requestStatus': output, 'installed': 0} data_ret = {'abort': 1, 'requestStatus': output, 'installed': 0}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
elif output.find('[200]') > -1: elif output.find('[200]') > -1:
command = "sudo rm -f " + serverStatusUtil.ServerStatusUtil.lswsInstallStatusPath
ProcessUtilities.popenExecutioner(command)
data_ret = {'abort': 1, 'requestStatus': output, 'installed': 1} data_ret = {'abort': 1, 'requestStatus': output, 'installed': 1}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@@ -371,6 +378,8 @@ def switchTOLSWSStatus(request):
return HttpResponse(json_data) return HttpResponse(json_data)
except BaseException, msg: except BaseException, msg:
command = "sudo rm -f " + serverStatusUtil.ServerStatusUtil.lswsInstallStatusPath
ProcessUtilities.popenExecutioner(command)
data_ret = {'abort': 1, 'requestStatus': str(msg), 'installed': 0} data_ret = {'abort': 1, 'requestStatus': str(msg), 'installed': 0}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@@ -563,7 +572,7 @@ def topProcessesStatus(request):
## CPU Details ## CPU Details
command = 'sudo cat /proc/cpuinfo' command = 'sudo cat /proc/cpuinfo'
output = subprocess.check_output(shlex.split(command)).splitlines() output = ProcessUtilities.outputExecutioner(command).splitlines()
import psutil import psutil

View File

@@ -1420,3 +1420,78 @@ app.controller('resellerCenterCTRL', function($scope,$http) {
}); });
/* Java script code for reseller center acl */ /* Java script code for reseller center acl */
/* Java script code for api access */
app.controller('apiAccessCTRL', function($scope,$http) {
$scope.apiAccessDropDown = true;
$scope.cyberpanelLoading = true;
$scope.showApiAccessDropDown = function () {
$scope.apiAccessDropDown = false;
};
$scope.saveChanges = function(){
$scope.cyberpanelLoading = false;
var url = "/users/saveChangesAPIAccess";
var data = {
accountUsername:$scope.accountUsername,
access:$scope.access,
};
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.apiAccessDropDown = true;
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) {
$scope.cyberpanelLoading = true;
new PNotify({
title: 'Error!',
text: 'Could not connect to server, please refresh this page.',
type:'error'
});
}
};
});
/* Java script code for api access */

View File

@@ -1420,3 +1420,78 @@ app.controller('resellerCenterCTRL', function($scope,$http) {
}); });
/* Java script code for reseller center acl */ /* Java script code for reseller center acl */
/* Java script code for api access */
app.controller('apiAccessCTRL', function($scope,$http) {
$scope.apiAccessDropDown = true;
$scope.cyberpanelLoading = true;
$scope.showApiAccessDropDown = function () {
$scope.apiAccessDropDown = false;
};
$scope.saveChanges = function(){
$scope.cyberpanelLoading = false;
var url = "/users/saveChangesAPIAccess";
var data = {
accountUsername:$scope.accountUsername,
access:$scope.access,
};
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.apiAccessDropDown = true;
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) {
$scope.cyberpanelLoading = true;
new PNotify({
title: 'Error!',
text: 'Could not connect to server, please refresh this page.',
type:'error'
});
}
};
});
/* Java script code for api access */

View File

@@ -0,0 +1,70 @@
{% extends "baseTemplate/index.html" %}
{% load i18n %}
{% block title %}{% trans "API Access for User - CyberPanel" %}{% endblock %}
{% block content %}
{% load static %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<div ng-controller="apiAccessCTRL" class="container">
<div id="page-title">
<h2>{% trans "API Access" %}</h2>
<p>{% trans "Allow/Remove API access for account, this effects Cloud Platform Connection and Third Party Modules." %}</p>
</div>
<div class="panel">
<div class="panel-body">
<h3 class="content-box-header">
{% trans "API Access" %} <img ng-hide="cyberpanelLoading" src="{% static 'images/loading.gif' %}">
</h3>
<div class="example-box-wrapper">
<form action="/" class="form-horizontal bordered-row panel-body">
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Select User" %}</label>
<div class="col-sm-6">
<select ng-change="showApiAccessDropDown()" ng-model="accountUsername" class="form-control">
{% for items in acctNames %}
<option>{{ items }}</option>
{% endfor %}
</select>
</div>
</div>
<div ng-hide="apiAccessDropDown" class="form-group">
<label class="col-sm-3 control-label">{% trans "Access" %}</label>
<div class="col-sm-6">
<select ng-model="access" class="form-control">
<option>Enable</option>
<option>Disable</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<button type="button" ng-click="saveChanges()"
class="btn btn-primary btn-lg">{% trans "Save Changes" %}</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@@ -28,4 +28,6 @@ urlpatterns = [
url(r'^changeACLFunc$',views.changeACLFunc,name="changeACLFunc"), url(r'^changeACLFunc$',views.changeACLFunc,name="changeACLFunc"),
url(r'^resellerCenter$',views.resellerCenter,name="resellerCenter"), url(r'^resellerCenter$',views.resellerCenter,name="resellerCenter"),
url(r'^saveResellerChanges$',views.saveResellerChanges,name="saveResellerChanges"), url(r'^saveResellerChanges$',views.saveResellerChanges,name="saveResellerChanges"),
url(r'^apiAccess$', views.apiAccess, name="apiAccess"),
url(r'^saveChangesAPIAccess$', views.saveChangesAPIAccess, name="saveChangesAPIAccess"),
] ]

View File

@@ -68,6 +68,54 @@ def createUser(request):
logging.CyberCPLogFileWriter.writeToFile(str(msg)) logging.CyberCPLogFileWriter.writeToFile(str(msg))
return redirect(loadLoginPage) return redirect(loadLoginPage)
def apiAccess(request):
try:
userID = request.session['userID']
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
adminNames = ACLManager.loadDeletionUsers(userID, currentACL)
adminNames.append("admin")
return render(request, 'userManagment/apiAccess.html', {'acctNames': adminNames})
else:
return ACLManager.loadError()
except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg))
return redirect(loadLoginPage)
def saveChangesAPIAccess(request):
try:
userID = request.session['userID']
currentACL = ACLManager.loadedACL(userID)
data = json.loads(request.body)
if currentACL['admin'] != 1:
finalResponse = {'status': 0, "error_message": "Only administrators are allowed to perform this task."}
json_data = json.dumps(finalResponse)
return HttpResponse(json_data)
else:
accountUsername = data['accountUsername']
access = data['access']
userAcct = Administrator.objects.get(userName=accountUsername)
if access == "Enable":
userAcct.api = 1
else:
userAcct.api = 0
userAcct.save()
finalResponse = {'status': 1}
json_data = json.dumps(finalResponse)
return HttpResponse(json_data)
except BaseException, msg:
finalResponse = {'status': 0, 'errorMessage': str(msg), 'error_message': str(msg)}
json_data = json.dumps(finalResponse)
return HttpResponse(json_data)
def submitUserCreation(request): def submitUserCreation(request):
try: try: