Is there anyway to remove access of google sheet to already shared users by using google sheet api or google drive api , etc in node js?

Issue

I am using google sheets api as well as google drive api (node js) and I have created google sheet by using service account and shared with one email "xyz@gmail.com" with role of ‘reader’. but now after 5 minutes, I want to remove the access from "xyz@gmail.com", so that it must not be accessible to ‘xyz@gmail.com".
Note: the owner of google sheet is service account.
Below is the snippet of code.

const auth = new google.auth.GoogleAuth({
    keyFile: "private_keys.json", //the key file
    //url to spreadsheets API
    scopes: ["https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/drive"], 
});

var body = {
  'type': 'user',
  'role': 'reader',
  'emailAddress': 'xyz@gmail.com',
};

var drive=google.drive({version: 'v3',auth});

drive.permissions.create({
  'fileId': spId,  //sheetID returned from create sheet response
  'resource': body,
}, function(err, response) {if (err) {
  console.error('error-------', err);
  return;
  } else{
    console.log(JSON.parse(JSON.stringify(response))) ;
  }
});

Solution

I believe your goal is as follows.

  • You want to delete the permission of xyz@gmail.com from a file using googleapis for Node.js.

In this case, how about the following sample script?

Sample script:

const spId = "###"; // Please set the file ID.
const email = "xyz@gmail.com"; // Please set the email address you want to delete the permission.

drive.permissions.list(
  { fileId: spId, fields: "permissions(emailAddress,id)" },
  function (err, response) {
    if (err) {
      console.error("error-------", err);
      return;
    } else {
      var permission = response.data.permissions.find(({ emailAddress }) => emailAddress == email);
      if (permission) {
        drive.permissions.delete({ fileId: spId, permissionId: permission.id },
          function (err, response) {
            if (err) {
              console.error("error-------", err);
              return;
            } else {
              console.log(JSON.parse(JSON.stringify(response)));
            }
          });
      }
    }
  });
  • When this script is run, the permission ID is searched using the email address. And, when the permission is found, the permission is deleted.

References:

Answered By – Tanaike

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.