I want to update my user permissions using google drive api with PHP. I am doing like this-
$Service = new Google_Service_Drive($Client);
$OptParams = array(
'fields' => '*'
);
$Reponse = $Service->files->get($FileId,$OptParams);
foreach ($Reponse->getPermissions() as $PermissionValue) {
$PermissionId = $PermissionValue->getId();
$PermissionValue->setRole('reader');
$result = $Service->permissions->update($FileId,$PermissionId,$PermissionValue);
}
return $result;
From the above code I can get my file id and permission id both but its throwing me error on update method. What am I doing while updating the user permissions for a file.
I am getting this error-
Fatal error: Uncaught Google\Service\Exception: { "error": { "errors": [ { "domain": "global", "reason": "fieldNotWritable", "message": "The resource body includes fields which are not directly writable." } ], "code": 403, "message": "The resource body includes fields which are not directly writable." } }
Can anybody tell me What am I doing wrong or what am I missing? What is the correct way of updating the permissions for user?
CodePudding user response:
Issue:
You are providing all properties in Permissions returned by Files: get. Some of these properties, like id
itself, are not writable.
Solution:
Permissions: update uses patch semantics to update the permission, which means only the fields you directly provide will get updated; there's no need to provide fields like id
, since not providing them doesn't cause these to get removed from the updated permission.
Therefore, you should only provide the fields you want to update. In this case, that's role
. Create a new permission object (see Google_Service_Drive_Permission) and set its role:
foreach ($Response->getPermissions() as $PermissionValue) {
$PermissionId = $PermissionValue->getId();
$updatedPerm = new Google_Service_Drive_Permission();
$updatedPerm->setRole("reader");
$result = $Service->permissions->update($FileId,$PermissionId,$updatedPerm);
}
Note:
This will fail for the permission related to the file owner, since you cannot remove the owner of a file without transfering ownership (see parameter transferOwnership
in the method documentation).
CodePudding user response:
The permissions get method returns a Permissions response object. This object contains a number of fields which are not writeable.
The permissions update method uses HTTP Patch methodology. This means that it is going to try and update every property that you send even the ones that are not writeable.
So by loading $PermissionValue object from the get permissions method you are populating to many propertyes.
You should create a new permissions object and only set what you need to update. in this case the role.
$newPermission = new Google_Service_Drive_Permission();
$newPermission ->setRole('reader');
$result = $Service->permissions->update($FileId,$PermissionId,$newPermission );