How to delete folder drive api - php

I am unable to delete a folder (created by another person) even if I try to change the rights, I have a console application and the current authenticated user can do the following :
create folders/files
move files
Scopes:
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive.appdata',
'https://spreadsheets.google.com/feeds',
Tries:
1.Set permissions to the current user
public function deleteFolder(\Google_Service_Drive_DriveFile $folder)
{
$permission = new \Google_Service_Drive_Permission();
$permission->setRole( 'owner' );
$permission->setType( 'user' );
$permission->setEmailAddress('someId#developer.gserviceaccount.com');
$permission = $this->googleDriveClient->permissions->create( $folder->getId(),$permission,array('transferOwnership'=>true));
$this->googleDriveClient->files->delete($folder->getId());
}
Result:
[Google_Service_Exception] {
"error": {
"errors": [
{
"domain": "global",
"reason": "internalError",
"message": "Internal Error"
}
],
"code": 500,
"message": "Internal Error" } }
2.Set permission type to anyone
public function deleteFolder(\Google_Service_Drive_DriveFile $folder)
{
$permission = new \Google_Service_Drive_Permission();
$permission->setRole( 'owner' );
$permission->setType( 'anyone' );
$permission = $this->googleDriveClient->permissions->create( $folder->getId(),$permission,array('transferOwnership'=>true));
$this->googleDriveClient->files->delete($folder->getId());
}
Result:
[Google_Service_Exception]
{
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientFilePermissions",
"message": "The user does not have sufficient permissions for this file ."
}
],
"code": 403,
"message": "The user does not have sufficient permissions for this file." }
}
try 3: Impersonate the creator
$this->googleClient->setAccessType('offline');
$this->googleClient->setSubject('x#domain.com');//if removed everything works
[GuzzleHttp\Exception\ClientException]
Client error: POST https://www.googleapis.com/oauth2/v4/token
resulted in a 401 Unauthorized response:
{
"error": "unauthorized_client",
"error_description": "Unauthorized client or scope in request.",
"error_uri": ""
}
Am I missing something?

Only the owner of the folder can delete the folder.
Use a service account Using OAuth 2.0 for Server to Server Applications, take the identity of the owner of the folder Perform Google Apps Domain-Wide Delegation of Authority.
Once authorized as the owner of the folder it should be possible to delete the folder.

Related

Google API - Auth server to server

I need a service to manipulate emails in a gmail account within a project developed in PHP Symfony...
I found this example : https://github.com/googleapis/google-api-php-client/blob/main/docs/oauth-server.md
But more confusing than helping...
I wrote this code :
src/Service/Gmail.php
<?php
namespace App\Service;
use Google\Client;
class Gmail
{
private \Google\Service\Gmail $api;
private function getGoogleClient(): Client
{
$credentialsPath = getenv('GOOGLE_APPLICATION_CREDENTIALS');
if (empty($credentialsPath)) {
throw new \Exception('You need to set env var GOOGLE_APPLICATION_CREDENTIALS');
}
if (!file_exists($credentialsPath)) {
throw new \Exception('Credentials file path ' . getenv('GOOGLE_APPLICATION_CREDENTIALS') . ' set in GOOGLE_APPLICATION_CREDENTIALS does not exist');
}
$client = new Client();
$client->useApplicationDefaultCredentials();
return $client;
}
private function getApi(): \Google\Service\Gmail
{
if (!isset($this->api)) {
$this->api = new \Google\Service\Gmail($this->getGoogleClient());
}
return $this->api;
}
public function getUserMessages($userId): \Google\Service\Gmail\ListMessagesResponse
{
return $this->getApi()->users_messages->listUsersMessages($userId);
}
}
Then I followed the steps described in Google Workspace for developers :
Create a new project : https://developers.google.com/workspace/guides/create-project?hl=en
Enable Gmail API : https://developers.google.com/workspace/guides/enable-apis?hl=en
Create credentials for web application server-side : https://developers.google.com/workspace/guides/create-credentials?hl=en
But at this point I have no idea what type of credentials I need : "OAuth client ID" or a "Service account" ??? If I choose "Oauth client ID" I suppose I have to use the application type "Web application" with server side url ? Or do I choose "Service account" ?
With service account I got this error :
In REST.php line 134:
{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.
google.com/identity/sign-in/web/devconsole-project.",
"errors": [
{
"message": "Login Required.",
"domain": "global",
"reason": "required",
"location": "Authorization",
"locationType": "header"
}
],
"status": "UNAUTHENTICATED",
"details": [
{
"#type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "CREDENTIALS_MISSING",
"domain": "googleapis.com",
"metadata": {
"service": "gmail.googleapis.com",
"method": "caribou.api.proto.MailboxService.ListMessages"
}
}
]
}
}
You have not proeprly authorized your service account to delegate to a user on your domain.
require_once('../../vendor/autoload.php');
// Some user within your workspace domain
$user_to_impersonate = "your#domain.com";
$sender = $user_to_impersonate;
$to = 'another#domain.com';
$subject = 'Hello';
$messageText = 'How are you doing?';
// The path to your service account credentials goes here.
putenv("GOOGLE_APPLICATION_CREDENTIALS=credentials.json");
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setSubject($sender);
$client->setApplicationName("Quickstart");
$client->setScopes(["https://mail.google.com/"]);
$service = new Google_Service_Gmail($client);

Google Cloud Storage bucket->exists gives 403

I am trying to check if a bucket exists in Laravel PHP.
I am getting a 403 on the exists() method. Why?
See line 160 https://github.com/googleapis/google-cloud-php/blob/master/Storage/src/Bucket.php
$storageClient = new \Google\Cloud\Storage\StorageClient([
'projectId' => env('GCS_PROJECT_ID'),
'keyFilePath' => storage_path(env('GCS_KEY_FILE')),
]);
$bucket = $storageClient->bucket('mybucketname');
if (!$bucket->exists()) {
$bucket = $storageClient->createBucket('mybucketname');
}
{ "error": {
"code": 403,
"message": "myaccount#api-project-xxxxxxxxx.iam.gserviceaccount.com does not have storage.buckets.get access to downloads.",
"errors": [ {
"message": "myaccount#api-project-xxxxxxxx.iam.gserviceaccount.com does not have storage.buckets.get access to mybucketname.",
"domain": "global",
"reason": "forbidden"
} ]
} }
Your service account does not have the storage.buckets.get permission. In order to check whether a bucket exists and then create it, assign roles/storage.admin to your service account.
For reference, see:
Cloud IAM roles for Cloud Storage
Cloud IAM permissions for Cloud Storage

How do i create permission on google sheet on docs in PHP

How do i create permission on google sheet on docs. Here it's show the error
{
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
here my code. i use php library.
function insertPermission($fileId) {
$client = $this->getClient();
$client->setScopes(Google_Service_Drive::DRIVE);
$service = new Google_Service_Drive($client);
$newPermission = new Google_Service_Drive_Permission(
array(
"role"=> "writer",
"type"=> "domain",)
);
try {
return $service->permissions->create($fileId, $newPermission);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
After set permisson it's denied and return this error.
The permissions.create method can be used to insert permissions into a file on google drive.
POST https://www.googleapis.com/drive/v3/files/fileId/permissions
{
"role": "writer",
"type": "user",
"emailAddress": "test#test.com"
}
In order to run the above request the currently authenticated user must have been authenticated using the following scopes and of course have permissions on the file already
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
insufficientPermissions
Means that the user you are authenticated with either hasn't granted your application permissions to make these changes or they themselves do not have the permissions. First thing i would do would be check the scopes your application has requested and add the scopes needed and re-authenticated the user and try again.

Insufficient Permission

befor i ask i want to introduce my first steps.
I used this for example: PHP Quickstart
Install google/apiclient via composer
Create a project in Google Developers Console
Add credentials to my project
Upload client_secret.json to my webserver
Run the script & enter the code
Credentials saved to /files/php-yt-oauth2.json
This channel's ID is UC_x5XG1OV2P6uZZ5FSM9Ttw. Its title is Google Developers, and it has 125874726 views.
Now i want to list all videos of one playlist:
function playlistItemsListByPlaylistId($service, $part, $params) {
$params = array_filter($params);
$response = $service->playlistItems->listPlaylistItems(
$part,
$params
);
print_r($response);
}
playlistItemsListByPlaylistId($service,
'snippet',
array('maxResults' => 1, 'playlistId' => 'ID'));
An get the following error:
[23-Dec-2017 14:29:59 Europe/Berlin] PHP Fatal error: Uncaught Google_Service_Exception: {
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
in /html/sa/vendor/google/apiclient/src/Google/Http/REST.php:118
I dont know whats going wrong and i hope someone can help me with this issue.

Symfony Google Drive Api

I used Symfony and I need create file in google drive and add access to write for another user to this file. I read google api drive
intsall google/apiclient
and run qiuck star, I get name for my share file. But I not find how to create new file and how to share this file for some user, this is possible ?
I find how to create file and add to quick start
crate file
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'Project plan',
'mimeType' => 'application/vnd.google-apps.drive-sdk'));
$file = $service->files->create($fileMetadata, array(
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
but have error
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/drive/v3/files?fields=id: (403) Insufficient Permission' in /home/ivan/host/aog-code/vendor/google/apiclient/src/Google/Http/REST.php:110
{
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
how to correct add file and add to permission for some user to this file ?

Categories