Home > Software design >  Is there anyway to remove access of google sheet to already shared users by using google sheet api o
Is there anyway to remove access of google sheet to already shared users by using google sheet api o

Time:05-26

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 "[email protected]" with role of 'reader'. but now after 5 minutes, I want to remove the access from "[email protected]", so that it must not be accessible to '[email protected]".
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': '[email protected]',
};

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))) ;
  }
});

CodePudding user response:

I believe your goal is as follows.

  • You want to delete the permission of [email protected] 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 = "[email protected]"; // 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:

  • Related