# Google Drive Permissions Fix

## Problem

When files are uploaded to Google Drive using a service account, the files are created successfully but the viewing URLs do not work because the service account does not automatically configure the necessary permissions for domain users to access the files.

### Symptoms
- Files are uploaded successfully to Google Drive
- Generated URLs show "You don't have access" or "Access denied"
- Files appear in Google Drive but are not accessible from the application

## Implemented Solution

### 1. Automatic Permission Configuration

The `GoogleWorkspaceProvider` was modified to automatically configure permissions after uploading files:

```php
// In upload(), createDocument(), createSpreadsheet(), createFolder()
$fileId = $file->getId();

// Automatically configure permissions for the domain after upload
$this->setDefaultPermissions($fileId);

return $fileId;
```

### 2. setDefaultPermissions() Method

This method configures two types of permissions:

```php
private function setDefaultPermissions(string $fileId): void
{
    try {
        // 1. Share with entire domain for read access
        $domainPermission = new Permission([
            'type' => 'domain',
            'role' => 'reader',
            'domain' => $this->config->organization_domain
        ]);

        $this->driveService->permissions->create($fileId, $domainPermission, [
            'sendNotificationEmail' => false
        ]);

        // 2. Share with anyone who has the link
        $anyonePermission = new Permission([
            'type' => 'anyone',
            'role' => 'reader'
        ]);

        $this->driveService->permissions->create($fileId, $anyonePermission, [
            'sendNotificationEmail' => false
        ]);

    } catch (\Exception $e) {
        Log::warning('Failed to set default permissions for file: ' . $fileId, [
            'error' => $e->getMessage(),
            'domain' => $this->config->organization_domain
        ]);
    }
}
```

### 3. Improved URLs

The `getUrl()` and `getEditUrl()` methods were updated to use more reliable URLs:

```php
public function getUrl(string $path): string
{
    $fileId = $this->getFileId($path);
    // Use a more reliable URL format that works with proper permissions
    return "https://drive.google.com/file/d/{$fileId}/view?usp=sharing";
}

public function getEditUrl(string $documentId): string
{
    // Use a more reliable URL format that works with proper permissions
    return "https://docs.google.com/document/d/{$documentId}/edit?usp=sharing";
}
```

## Configuration for Existing Files

For files that were uploaded before these changes, tools were created to configure permissions manually:

### 1. Artisan Command

```bash
# Configure permissions for a specific file
php artisan google:configure-permissions --file-id=1ABC123DEF456

# Configure permissions for all existing files
php artisan google:configure-permissions --all
```

### 2. HTTP Endpoint

```bash
POST /setup/cloud-storage/configure-permissions
Content-Type: application/json

{
    "file_id": "1ABC123DEF456",
    "provider": "google"
}
```

### 3. Service Method

```php
$storageService = new CloudStorageService($factory, $config);
$success = $storageService->configureFilePermissions($fileId);
```

## Verification

To verify that permissions are configured correctly:

1. **In Google Drive**: Files should appear with the "shared" icon (person)
2. **In the application**: URLs should open without showing access errors
3. **In the logs**: Look for success or warning messages related to permissions

## Service Account Configuration

Make sure the service account has the necessary permissions in Google Workspace:

1. **Domain-wide delegation** enabled
2. **Scopes** configured correctly:
   - `https://www.googleapis.com/auth/drive`
   - `https://www.googleapis.com/auth/documents`
   - `https://www.googleapis.com/auth/spreadsheets`

3. **Subject** configured correctly:
   ```php
   $this->client->setSubject('admin@' . $this->config->organization_domain);
   ```

## Troubleshooting

### Error: "Insufficient permissions"
- Verify that the service account has domain-wide delegation
- Confirm that the subject is a domain admin

### Error: "File not found"
- Verify that the file_id is correct
- Confirm that the file exists in Google Drive

### URLs still not working
- Run the permissions configuration command
- Verify that the domain is configured correctly
- Review logs for specific errors

## Modified Files

- `src/App/Providers/CloudServices/GoogleWorkspaceProvider.php`
- `src/Domain/CloudService/Contracts/CloudStorageProvider.php`
- `src/App/Services/CloudServices/CloudStorageService.php`
- `src/App/Http/Controllers/CloudStorageController.php`
- `routes/tenant.php`
- `app/Console/Commands/ConfigureGoogleDrivePermissions.php`

## Next Steps

1. Run the command to configure permissions on existing files
2. Test uploading new files
3. Verify that URLs work correctly
4. Monitor logs to ensure there are no errors
