In various posts and articles I’ve been exploring uses of the Google Apps scriptDB datastore. One of the things I’ve been mulling over is how to simplify the whole oAuth experience when dealing with REST queries that need authentication.
When you read up on examples of using oAuth, they are usually server orientated – in PHP, java, python etc. One of the reasons for this is the difficulty in obscuring the various credentials such as your consumer key, consumer secret and so on, when in javaScript (and of course VBA)
For those of us that do not have server based development environments, Google Apps Script comes to the rescue.
- Google Apps ScriptDB gives the opportunity to securely store data that can be shared amongst scripts, yet kept private to those without access.
- Urlfetch.oauthConfig() deals with the “mess with your head” business of oAuth
- The ContentService is able to generate REST like responses.
/** * myStuffDb return the shared DB for myStuff * @return {ScriptDbInstance} the db */ function myStuffDb() { return ScriptDb.getMyDb(); }
function createlockBoxTest(){ return mcpher.createStuff ("lockboxtest", myStuff.myStuffDb(), { site: 'ramblings.mcpher.com', name: 'excel liberation', myNumber: 1234 } ); }
And when we access that,
function testGetMyStuff() { Logger.log(JSON.stringify(mcpher.getMyStuff("lockboxtest",myStuff.myStuffDb()))); }
we get, with the lockbox data in .result.myStuff
{ "status": { "code": "good", "reason": "lockboxtest found in your stuff" }, "result": { "siloId": "lockboxtest", "help": "for details see ramblings.mcpher.com", "timeStamp": 1347535115084, "myStuff": { "site": "ramblings.mcpher.com", "name": "excel liberation", "myNumber": 1234 }, "userStamp": "bruce@mcpher.com" } }
- Only scripts that are authorized to use your library can have access to your scriptDB as the only way they can find out the db() is through myStuff.myStuffDb()
- mcpher.getMyStuff() has an additional security check that only allows the creator of the entry to access it.
if (result.userStamp != Session.getUser().getEmail()) { response.status.code = "bad"; response.status.reason = siloName + "does not belong to you"; }
function doGet(e) { return ContentService .createTextOutput(JSON.stringify(mcpher.getMyStuff(e.parameter ? e.parameter.entry : null, myStuffDb()))) .setMimeType(ContentService.MimeType.JSON); }
{ "status": { "code": "good", "reason": "lockboxtest found in your stuff" }, "result": { "siloId": "lockboxtest", "help": "for details see ramblings.mcpher.com", "timeStamp": 1347535115084, "myStuff": { "site": "ramblings.mcpher.com", "name": "excel liberation", "myNumber": 1234 }, "userStamp": "bruce@mcpher.com" } }
function testOauth() { return oAuthProxy("twitterauth", "http://api.twitter.com/1/statuses/user_timeline.json" ).getContentText() }