From eb5a3bf4f986942a849466b7a9fd0e2ae06c5324 Mon Sep 17 00:00:00 2001 From: Horilla Date: Wed, 2 Jul 2025 12:27:03 +0530 Subject: [PATCH] [FIX] HORILLA_BACKUP: Google service file authentication issue --- horilla_backup/forms.py | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/horilla_backup/forms.py b/horilla_backup/forms.py index de313f6e2..cd97346da 100644 --- a/horilla_backup/forms.py +++ b/horilla_backup/forms.py @@ -1,4 +1,5 @@ import os +import tempfile from pathlib import Path from django import forms @@ -121,21 +122,26 @@ class GdriveBackupSetupForm(ModelForm): service_account_file = cleaned_data.get("service_account_file") try: - if GoogleDriveBackup.objects.exists(): - authenticate(service_account_file.path) - else: - file_data = service_account_file.read() - # Save the processed file to the desired location - file_name = service_account_file.name - new_file_name = file_name - # Save using Django's default storage system - relative_path = default_storage.save( - new_file_name, ContentFile(file_data) - ) - # Get the full absolute path - full_path = default_storage.path(relative_path) - authenticate(full_path) - os.remove(full_path) + # Read file content from InMemoryUploadedFile or whatever you receive + file_data = service_account_file.read() + file_name = service_account_file.name + + # Save using Django's storage (optional, if you need to persist it later) + if not GoogleDriveBackup.objects.exists(): + # Save to storage if no backup exists + relative_path = default_storage.save(file_name, ContentFile(file_data)) + + # Always write to temp file for authentication (because .path isn't supported) + with tempfile.NamedTemporaryFile(delete=False, suffix=".json") as tmp_file: + tmp_file.write(file_data) + tmp_file.flush() + temp_path = tmp_file.name + + # Authenticate using temp file path + authenticate(temp_path) + + # Clean up temp file + os.remove(temp_path) except Exception as e: raise forms.ValidationError("Please provide a valid service account file.")