简体   繁体   中英

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

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?

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

  6. 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/gsuitedevs/apps-script-oauth2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM