This is a php appwrite function code to delete a document. I compared the owner of the document with the user id. If they are the same, the user has permission to delete it, otherwise not. After I execute it, even thought the user id equals with the owner, the document won't be deleted. However, I'm noticing that the user ID fetched on the server is different from my actual user ID and I think this leads to unexcepted behaviour. How can I solve this issue or should I use another logic?
<?php
use Appwrite\Client;
use Appwrite\Services\Databases;
use Appwrite\Services\Functions;
use Appwrite\ID;
require_once 'vendor/autoload.php';
error_reporting(E_ALL);
ini_set('display_errors', '1');
return function ($req, $res) {
$client = new Client();
$database = new Databases($client);
if (
empty($req['variables']['APPWRITE_FUNCTION_ENDPOINT']) ||
empty($req['variables']['APPWRITE_FUNCTION_API_KEY']) ||
empty($req['variables']['APPWRITE_FUNCTION_PROJECT_ID'])
) {
return $res->send('Environment variables are not set. Function cannot use Appwrite SDK.', 500);
}
echo "Configuring the client...\n";
$client
->setEndpoint($req['variables']['APPWRITE_FUNCTION_ENDPOINT'])
->setProject($req['variables']['APPWRITE_FUNCTION_PROJECT_ID'])
->setKey($req['variables']['APPWRITE_FUNCTION_API_KEY'])
->setSelfSigned(false); //false in the test environment
try {
print_r($req);
$payload = json_decode($req['payload'], true);
$databaseId = 'conni';
$collectionId = 'innocaps';
$documentId = $payload['documentId'] ?? '';
if (empty($documentId)) {
return $res->json([
'success' => false,
'message' => 'Missing required data: documentId',
], 400);
}
echo "Checking if the user has permission to delete the innocap document.\n";
$document = $database->getDocument($databaseId, $collectionId, $documentId);
if(isset($document['owner']) && $document['owner'] === $req['variables']['APPWRITE_FUNCTION_USER_ID']){
echo "The user who is trying to delete the document, with id: " . $req['variables']['APPWRITE_FUNCTION_USER_ID'] . " has permission to delete the document.\n";
echo "Deleting document with ID: $documentId from Collection: $collectionId Database: $databaseId\n";
$response = $database->deleteDocument($databaseId, $collectionId, $documentId);
return $res->json([
'success' => true,
'message' => 'Document deleted successfully.',
]);
} else {
echo "The user who was trying to delete the document, with id: " . $req['variables']['APPWRITE_FUNCTION_USER_ID'] . " does not have permission to delete it.\n";
// Return an error response if the requester is not the owner of the document
return $res->json([
'success' => false,
'message' => 'The user failed to delete the document',
], 403);
}
} catch (\Exception $e) {
return $res->json([
'success' => false,
'message' => 'Failed to delete document: ' . $e->getMessage(),
], 500);
}
};