我可以让部分 Google Apps 脚本代码以我的身份执行,而其余部分以访问用户的身份执行吗?

Can I have part of Google Apps Script code execute as me while the rest executes as the accessing user?

我有一个写入融合 table 的应用程序脚本 Web 应用程序,以及它定期缓存的一些电子表格。我不想向同事提供对 fusion table 的编辑权限,他们可以根据需要编辑条目。

目前,网络应用程序作为用户执行,对于我组织内的任何人,这是意图。但是,我宁愿网络应用程序像我一样执行任何查询,这样我就不需要为可能访问它的每个用户明确提供权限。

有办法吗?

是的,这是可能的。以前您会使用 OAuth2 库,将您的凭据保存到脚本 属性 存储,然后使用 REST 接口访问您想要使用自己的凭据访问的服务。现在您可以使用执行 API 来使用内置服务。

设置

  1. 将 OAuth2 库添加到您的项目中:
    https://github.com/gsuitedevs/apps-script-oauth2

  2. 根据 README.md 设置它,匹配您的项目范围(查看项目属性)。确保将 setPropertyStore() 指向脚本属性。

  3. 验证您的 OAuth2 服务。

  4. 将脚本发布为执行 API

  5. 添加对脚本 REST 接口的调用。查看令牌方法,确保更改它以匹配您自己的方法。

    function ExecuteAsMe(functionName,paramsArray){
      var url = 'https://script.googleapis.com/v1/scripts/'+ScriptApp.getProjectKey()+':run';
    
      var payload = JSON.stringify({"function": functionName ,"parameters":paramsArray, "devMode": true});
    
      var params={method:"POST",
                  headers:{Authorization: "Bearer "+ getFusionService().getAccessToken()},
                  payload:payload,
                  contentType:"application/json",
                  muteHttpExceptions:true};
      var results = UrlFetchApp.fetch(url, params);
     return JSON.parse(results).response.result;
    }
  1. 执行你的函数:var results = ExecuteAsMe("searchFusionTable",['searchTerm', 50]);

参考:

执行API
https://developers.google.com/apps-script/guides/rest/api?hl=en

OAuth2 库

https://github.com/gsuitedevs/apps-script-oauth2