diff --git a/IncBackups/static/IncBackups/IncBackups.js b/IncBackups/static/IncBackups/IncBackups.js index d67e6e597..5e659fba7 100644 --- a/IncBackups/static/IncBackups/IncBackups.js +++ b/IncBackups/static/IncBackups/IncBackups.js @@ -1806,6 +1806,7 @@ app.controller('ConfigureV2Backup', function ($scope, $http, $timeout) { sfptpasswd: $scope.sfptpasswd, hostName: $scope.hostName, UserName: $scope.UserName, + Repo_Name: $scope.reponame, }; var config = { diff --git a/IncBackups/templates/IncBackups/ConfigureV2Backup.html b/IncBackups/templates/IncBackups/ConfigureV2Backup.html index 389944cbb..7e5315df7 100644 --- a/IncBackups/templates/IncBackups/ConfigureV2Backup.html +++ b/IncBackups/templates/IncBackups/ConfigureV2Backup.html @@ -100,6 +100,14 @@
+
+ +
+ +
+
+
diff --git a/IncBackups/tests.py b/IncBackups/tests.py index e69de29bb..2bc228ac9 100644 --- a/IncBackups/tests.py +++ b/IncBackups/tests.py @@ -0,0 +1,35 @@ +import json +import configparser + +CurrentContent = """[usman] +type = sftp +host = staging.cyberpanel.net +user = abcds2751 +pass = s0RBbJU8EhfQ-wvFgbOVEmy3HK6y19A +shell_type = unix +md5sum_command = md5sum +sha1sum_command = sha1sum + +[habbitest2gdrive] +type = drive +client_id = "" +client_secret = "" +scope = drive +root_folder_id = "" +service_account_file = "" +token = {"access_token":"ya29.a0Ael9sCPUpwAZpHChyBkAYrDGo5BRjkj2OV1r9KNBXdXZZrjTrjPOHxTkayEr-hfKNhsqYrvChowxQw-EgTO7JobBE7IrZpLDpdpEOTY49JOg-PagtPLU_TuqFPab356TdeC0-f2RHQ_2arU1pN92aKcgfp7CaCgYKASESARESFQF4udJhaS1_8FVFFkG-ds0yPY0APA0163","token_type":"Bearer","refresh_token":"1//09Sgboc4b9-kYCgYIARAAGAkSNgF-L9IrgxJ3jKcd0UDraNAncWDKRUNu0L5ORiaS8H_QaXv2y85p0cL3ZArEaShSxy2P_Kb0CQ"} +""" + +# Read the configuration string +config = configparser.ConfigParser() +config.read_string(CurrentContent) + +# Get the refresh token +refresh_token = json.loads(config.get('habbitest2gdrive', 'token'))['refresh_token'] +old_access_token = json.loads(config.get('habbitest2gdrive', 'token'))['access_token'] +print(refresh_token) + +new_token ="jdskjkvnckjdfvnjknvkvdjc" +new_string = CurrentContent.replace(str(old_access_token), new_token) + +print(new_string) \ No newline at end of file diff --git a/IncBackups/views.py b/IncBackups/views.py index fc4baf769..941606162 100644 --- a/IncBackups/views.py +++ b/IncBackups/views.py @@ -928,6 +928,7 @@ def ConfigureSftpV2Backup(request): sfptpasswd = data['sfptpasswd'] hostName = data['hostName'] UserName = data['UserName'] + Repo_Name = data['Repo_Name'] currentACL = ACLManager.loadedACL(userID) admin = Administrator.objects.get(pk=userID) @@ -941,6 +942,7 @@ def ConfigureSftpV2Backup(request): req_data['host'] = hostName req_data['user'] = UserName req_data['password'] = sfptpasswd + req_data['Repo_Name'] = Repo_Name cpbuv2 = CPBackupsV2( @@ -949,10 +951,10 @@ def ConfigureSftpV2Backup(request): cpbuv2.SetupRcloneBackend(CPBackupsV2.SFTP, req_data) - return ConfigureV2Backup(request) + # return ConfigureV2Backup(request) - # final_json = json.dumps({'status': 1, 'fetchStatus': 1, 'error_message': "None", "data": None}) - # return HttpResponse(final_json) + final_json = json.dumps({'status': 1, 'fetchStatus': 1, 'error_message': "None", "data": None}) + return HttpResponse(final_json) except BaseException as msg: diff --git a/plogical/Backupsv2.py b/plogical/Backupsv2.py index 7a50d7155..36eae5847 100644 --- a/plogical/Backupsv2.py +++ b/plogical/Backupsv2.py @@ -4,6 +4,8 @@ import os import sys import time import requests +import json +import configparser from django.http import HttpResponse sys.path.append('/usr/local/CyberCP') @@ -19,6 +21,8 @@ except: pass from plogical.processUtilities import ProcessUtilities +from plogical.processUtilities import ProcessUtilities as pu + import threading as multi @@ -50,6 +54,51 @@ class CPBackupsV2(multi.Thread): from websiteFunctions.models import Websites self.website = Websites.objects.get(domain=self.data['domain']) + + + # Resresh gdive access_token code + try: + self.LocalRclonePath = f'/home/{self.website.domain}/.config/rclone' + self.ConfigFilePath = f'{self.LocalRclonePath}/rclone.conf' + + reponame = self.data['BackendName'] + + path = '/home/%s/.config/rclone/rclone.conf' % (self.data['domain']) + + command = 'cat %s' % (path) + CurrentContent = pu.outputExecutioner(command) + + + if CurrentContent.find(reponame) > -1: + config = configparser.ConfigParser() + config.read_string(CurrentContent) + + token_str = config.get(reponame, 'token') + token_dict = json.loads(token_str) + refresh_token = token_dict['refresh_token'] + + + new_Acess_token = self.refresh_V2Gdive_token(refresh_token) + + old_access_token = token_dict['access_token'] + + new_content = CurrentContent.replace(str(old_access_token), new_Acess_token) + + command = f"cat /dev/null > {self.ConfigFilePath}" + pu.executioner(command, self.website.externalApp, True) + + command = f"echo '{new_content}' >> {self.ConfigFilePath}" + ProcessUtilities.executioner(command, self.website.externalApp, True) + + command = f"chmod 600 {self.ConfigFilePath}" + ProcessUtilities.executioner(command, self.website.externalApp) + else: + logging.CyberCPLogFileWriter.writeToFile("Token Not upadate..........") + except BaseException as msg: + logging.CyberCPLogFileWriter.writeToFile("Error update token............%s"%msg) + + + ## Set up the repo name to be used if self.data['BackendName'] != 'local': @@ -94,7 +143,6 @@ class CPBackupsV2(multi.Thread): def SetupRcloneBackend(self, type, config): try: - logging.CyberCPLogFileWriter.writeToFile(' [Configure.1]') self.LocalRclonePath = f'/home/{self.website.domain}/.config/rclone' self.ConfigFilePath = f'{self.LocalRclonePath}/rclone.conf' @@ -103,60 +151,52 @@ class CPBackupsV2(multi.Thread): command = f'cat {self.ConfigFilePath}' CurrentContent = ProcessUtilities.outputExecutioner(command, self.website.externalApp) - logging.CyberCPLogFileWriter.writeToFile(' [Configure.2]') try: if CurrentContent.find('No such file or directory'): CurrentContent = '' except: CurrentContent = '' - logging.CyberCPLogFileWriter.writeToFile(' [Configure.3]') if type == CPBackupsV2.SFTP: ## config = {"name":, "host":, "user":, "port":, "path":, "password":,} command = f'rclone obscure {config["password"]}' ObsecurePassword = ProcessUtilities.outputExecutioner(command).rstrip('\n') content = f'''{CurrentContent} - [{config["name"]}] - type = sftp - host = {config["host"]} - user = {config["user"]} - pass = {ObsecurePassword} - ''' +[{config["Repo_Name"]}] +type = sftp +host = {config["host"]} +user = {config["user"]} +pass = {ObsecurePassword} +''' command = f"echo '{content}' >> {self.ConfigFilePath}" ProcessUtilities.executioner(command, self.website.externalApp, True) command = f"chmod 600 {self.ConfigFilePath}" ProcessUtilities.executioner(command, self.website.externalApp) - - final_json = json.dumps({'status': 1, 'fetchStatus': 1, 'error_message': "None", "data": None}) - return HttpResponse(final_json) + return 1 elif type == CPBackupsV2.GDrive: - logging.CyberCPLogFileWriter.writeToFile(' [Configure.4]') - token = """{"access_token":"%s","token_type":"Bearer","refresh_token":"%s"}""" % ( + token = """{"access_token":"%s","token_type":"Bearer","refresh_token":"%s", "expiry":"2024-04-08T21:53:00.123456789Z"}""" % ( config["token"], config["refresh_token"]) content = f'''{CurrentContent} -[{config["name"]}] -type = Gdrive -[Gdrive_Mount] -client_id = "" -client_secret = "" +[{config["accountname"]}] +type = drive scope = drive -root_folder_id = "" -service_account_file = "" token = {token} +team_drive = ''' command = f"echo '{content}' >> {self.ConfigFilePath}" ProcessUtilities.executioner(command, self.website.externalApp, True) command = f"chmod 600 {self.ConfigFilePath}" ProcessUtilities.executioner(command, self.website.externalApp) - logging.CyberCPLogFileWriter.writeToFile(' [Configure.5]') except BaseException as msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + ' [Configure.run]') + + @staticmethod def FetchCurrentTimeStamp(): import time @@ -242,7 +282,7 @@ token = {token} logging.CyberCPLogFileWriter.writeToFile(result) def InitiateBackup(self): - + logging.CyberCPLogFileWriter.writeToFile("[Create Backup start]") from websiteFunctions.models import Websites, Backupsv2 from django.forms.models import model_to_dict from plogical.mysqlUtilities import mysqlUtilities @@ -787,6 +827,19 @@ token = {token} except BaseException as msg: return 0, str(msg) + @staticmethod + def refresh_V2Gdive_token(refresh_token): + try: + # refresh_token = "1//09pPJHjUgyp09CgYIARAAGAkSNgF-L9IrZ0FLMhuKVfPEwmv_6neFto3JJ-B9uXBYu1kPPdsPhSk1OJXDBA3ZvC3v_AH9S1rTIQ" + finalData = json.dumps({'refresh_token': refresh_token}) + r = requests.post("https://platform.cyberpersons.com/refreshToken", data=finalData + ) + newtoken = json.loads(r.text)['access_token'] + return newtoken + except BaseException as msg: + print("Error Update token:%s" % msg) + return None + @staticmethod def DeleteSchedule(website, repo, frequency, websiteData, websiteDatabases, websiteEmails): try: diff --git a/plogical/IncScheduler.py b/plogical/IncScheduler.py index c15cee75c..f3ccd9f95 100644 --- a/plogical/IncScheduler.py +++ b/plogical/IncScheduler.py @@ -15,6 +15,7 @@ from websiteFunctions.website import WebsiteManager import time import datetime import google.oauth2.credentials +from google.oauth2.credentials import Credentials from googleapiclient.discovery import build from googleapiclient.http import MediaFileUpload from plogical.backupSchedule import backupSchedule @@ -1476,6 +1477,7 @@ def main(): return 0 if args.function == '30 Minutes' or args.function == 'Daily' or args.function == '1 Hour' or args.function == '6 Hours' or args.function == '12 Hours' or args.function == '1 Day' or args.function == '3 Days' or args.function == '1 Week': + # IncScheduler.refresh_access_token() IncScheduler.RemoteBackup(args.function) IncScheduler.v2Backups(args.function) return 0