Google Datastore service for Goa using service account examples

This describes how to authenticate with Google Datastore using Goa along with a service account, as described in Oauth2 for Apps Script in a few lines of code (which you should read first for background) and Goa services and customization

The library, cGoa, is available under this project key.

MZx5DzNPsYjVyZaR67xXJQai_d-phDA33

Setting up


You'll need to create an App. The dashboard/developers console can be found here. This time, its a service account that's required. 

Your one time setup would look something like this. In this case - a service account, the credentials come from the JSON file downloaded from the Google developer console and identified by the given file id.
  cGoa.GoaApp.setPackage (propertyStore , cGoa.GoaApp.createServiceAccount (DriveApp , {
    packageName: 'DriverDatastore_serviceaccount',
    fileId:'0xxxxxxxxs',
    scopes : cGoa.GoaApp.scopesGoogleExpand (['datastore','userinfo.email']),
    service:'google_service'
  }));;
 

The example

The example includes 3 functions.
  • A doGet example for a web app.
  • An example where the token has already been setup by a one off doGet example
  • An example of consuming the token
The doGet should be published 

function doGet(e) {
  return doGetDataStoreSA (e);
}

There is no consent screen required or created for a service account.

The patterns



// Data store using service account

/**
 * this is how  to do a webapp which needs authentication
 * @param {*} e - parameters passed to doGet
 * @return {HtmlOurput} for rendering
 */
function doGetDataStoreSA (e) {
  
  // this is pattern for a WebApp.
  // passing the doGet parameters (or anything else)
  // will ensure they are preservered during the multiple oauth2 processes
  
  // change this to whatever store & credentials name are being used
  var goa = cGoa.GoaApp.createGoa('DriverDatastore_serviceaccount',PropertiesService.getScriptProperties()).execute(e);
  
  if (goa.needsConsent()) {
    // this should never happen with a service account
    throw 'you should never need consent with a service account';
  }
  
  // if we get here its time for your webapp to run and we should have a token, or thrown an error somewhere
  if (!goa.hasToken()) throw 'something went wrong with goa - did you check if consent was needed?';
  
  // This is a webapp doing whaever its supposed to do
  // getParams is used to retrieve the original parameters passed to this function
  var result = testDataStore (goa.getToken(), goa.getParams() );   
  
  // now return it as normal
  return HtmlService.createHtmlOutput (result.getContentText())
    .setSandboxMode(HtmlService.SandboxMode.IFRAME);

}

function dataStoreSA (params) {
       
  // pick up the token refreshing if necessary
  var goa = cGoa.GoaApp.createGoa('DriverDatastore_serviceaccount', PropertiesService.getScriptProperties()).execute(params);
  
  if (!goa.hasToken()) {
    throw 'no token retrieved';
  }
  
  // do a test - passing the token and any parameters that arrived to this function
  Logger.log (testDataStore (goa.getToken(), goa.getParams(params) ));
  

/**
 * this is your main processing - will be called with your access token
 * @param {string} accessToken - the accessToken
 * @param {*} params any params
 */
function testDataStore (accessToken,params) {
 
   var options = {
     method: "POST",
     contentType : "application/json" ,
     muteHttpExceptions : true,
     headers: {
       "authorization": "Bearer " + accessToken,
     },
     payload:JSON.stringify({
       "query": {
        "kinds": [{"name":"polymerdbab"}]
       }
      })
   };
   

  return UrlFetchApp.fetch( 
    "https://www.googleapis.com/datastore/v1beta2/datasets/xliberationdatastore/runQuery", options);

}


An example of using cGoa for copying to a DataStore using Driver DbAbstraction is shown in the slides below. 

do something in 5 with gas-9-copy between databases with oauth2


For more like this, see OAuth2 for Apps Script in a few lines of code Why not join our forumfollow the blog or follow me on twitter to ensure you get updates when they are available. 

You want to learn Google Apps Script?

Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, All formats are available from O'ReillyAmazon and all good bookshops. You can also read a preview on O'Reilly

If you prefer Video style learning I also have two courses available. also published by O'Reilly.
Google Apps Script for Developers and Google Apps Script for Beginners.


Comments