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

ⅰ亾dé卋堺 提交于 2020-05-14 10:24:19

问题


I have a apps script web app that writes to a fusion table, as well as a few spreadsheets which it periodically caches. I do not want to provide edit access to the fusion table to colleagues, who could just go and edit entries as they see fit.

Currently the web app executes as the user, for anyone within my organization, which is the intention. However, I'd rather the web app execute any queries as myself, so that I don't need to explicitly provide permissions to each individual user that might be accessing it.

Is there a way to do this?


回答1:


Yes this is possible. Previously you would use the OAuth2 library, save your credentials to the script property store, then use the REST interface to the service you want to access with your own credentials. Now you can use the Execution API to use the built in services.

Setup

1) Add the OAuth2 Library to your project:
https://github.com/googlesamples/apps-script-oauth2

2) Set it up according the the README.md, matching the scopes of your project(look at the project properties). Make sure your point setPropertyStore() to the script properties.

3) Authenticate your OAuth2 service.

4) Publish your script as an Execution API

5) Add a call to your scripts REST interface. Look at the token method, make sure you change it to match your own.

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

5) Execute the function as you: var results = ExecuteAsMe("searchFusionTable",['searchTerm', 50]);

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

OAuth2 Library
https://github.com/googlesamples/apps-script-oauth2



来源:https://stackoverflow.com/questions/35119649/can-i-have-part-of-google-apps-script-code-execute-as-me-while-the-rest-executes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!