Friday, April 23, 2021

demo of displaying content from google drive using a service account

Following
https://www.labnol.org/code/20375-service-accounts-google-apps-script

creating a service account and delegating authority domain-wide via the method at
https://developers.google.com/admin-sdk/directory/v1/guides/delegation

The google apps script's Code.gs has the following, and will work even when the doc is not shared with anyone except theuser@ourdomain.tld:

var JSON = {
    "private_key": "-----BEGIN PRIVATE KEY-----\nMI -- snip -- pJKdnI=\n-----END PRIVATE KEY-----\n",
    "client_email": "what-name-we-give@proj-name.iam.gserviceaccount.com",
    "client_id": "1020123456872",
    "user_email": "theuser@ourdomain.tld"
};

function getOAuthService() {
    return OAuth2.createService("Service Account")
        .setTokenUrl('https://accounts.google.com/o/oauth2/token')
        .setPrivateKey(JSON.private_key)
        .setIssuer(JSON.client_email)
        .setSubject(JSON.user_email)
        .setPropertyStore(PropertiesService.getScriptProperties())
        .setParam('access_type', 'offline')
        .setScope('https://www.googleapis.com/auth/drive');
}


function getUserFiles() {
    var service = getOAuthService();
    service.reset();
    //Logger.log("Getting the Access Token:");
    var atoken = service.getAccessToken()
    //Logger.log(atoken);
    if (service.hasAccess()) {      
        var url = 'https://drive.google.com/open?id=1qM_DOC_ID_5QiIJ0Ls';
        var response = UrlFetchApp.fetch(url, {
            headers: {
                Authorization: 'Bearer ' + atoken
            }
        });
        return response.getContentText()        
    }
}

function reset() {
    var service = getOAuthService();
    service.reset();
}


function doGet(e) {    
  var htmlout = HtmlService.createHtmlOutput(getUserFiles());
  return htmlout
      .setTitle('Our Team')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

No comments:

Post a Comment