使用 google api 更改 google 电子表格的访问权限

change access permissions of google spreadsheet using google apis

我正在尝试使用 google API 更改我的 google 电子表格的辅助功能权限,我已经使用我的 google 服务帐户创建了它 google API.

我也可以将它的所有权授予其他电子邮件地址并保留我自己的编辑权限吗?

生成代码(我用的是node js):-

const client = new google.auth.JWT(
  keys.client_email,
  null,
  keys.private_key,
  ['https://www.googleapis.com/auth/spreadsheets']
);

client.authorize((err, tokens) => {
  if (err) {
    console.log('sheet auth err', err);
    return;
  }
  console.log('success auth');
});

app.post('/generateSheet', async (req, res, next) => {
  const { userId, sheetName } = req.body;
  console.log(userId, sheetName);
  // return res.redirect('/');
  const integrationName = 'Google_Sheets';

    const data = req.body;
  try {
    // const integrationInfoSnapshot = await db
        //  .doc(`integrationParameters/${integrationName}`)
    //   .get();
    try {
      const gsapi = google.sheets({
        version: 'v4',
        auth: client,
      });
      request_ = {
        resource: {
          properties: {
            title: sheetName
          }
        }
      }
      const response = await gsapi.spreadsheets.create(request_);

      // GIVE SPREADSHEET OWNERSHIP TO SOME OTHER EMAIL ADDRESS AND KEEP EDITING ACCESS TO MY SELF
 
      console.log(response);
    } catch (e) {
      console.log(`Error while creating google sheet for user: ${userId}: `, e);
    }
  } catch (e) {
        console.log(`Error while activating integration for user: "${userId}": `, e);
        res.status(500).send({ message: e.message });
    }
});

如果有人能回答,那就太好了。请帮忙!!!

为了给使用电子邮件的作者权限,您可以使用权限的方法来实现:在驱动器中创建API。很遗憾,在当前阶段,Sheets API 无法执行此操作。

以你的脚本为例,当给创建的Spreadsheet赋予权限时,脚本如下。

修改后的脚本:

从:
const client = new google.auth.JWT(
  keys.client_email,
  null,
  keys.private_key,
  ['https://www.googleapis.com/auth/spreadsheets']
);
到:
const client = new google.auth.JWT(
  keys.client_email,
  null,
  keys.private_key,
  ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive']
);

并且,还请修改如下。

从:
const response = await gsapi.spreadsheets.create(request_);
到:
const response = await gsapi.spreadsheets.create(request_);

// I added below script.
const fileId = response.data.spreadsheetId;
drive = google.drive({ version: "v3", auth: client });
const res = await drive.permissions.create({
  resource: {
    type: "user",
    role: "writer",
    emailAddress: "###",  // Please set the email address you want to give the permission.
  },
  fileId: fileId,
  fields: "id",
});

参考