From 29af94718a163f16d7dd47990212ac3e89b71f59 Mon Sep 17 00:00:00 2001 From: "Gunar C. Gessner" Date: Tue, 25 Oct 2016 18:44:27 -0200 Subject: [PATCH] Add Auth through Service Account in env variable --- lib/authenticate.js | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/lib/authenticate.js b/lib/authenticate.js index 2ee0aa9..b52a743 100644 --- a/lib/authenticate.js +++ b/lib/authenticate.js @@ -1,5 +1,6 @@ var colors = require('colors'); var OAuth2Client = require('googleapis').auth.OAuth2; +var ServiceToken = require('googleapis').auth.JWT; var Promise = require('bluebird'); var fs = Promise.promisifyAll(require('fs')); @@ -15,6 +16,12 @@ module.exports = function authenticate() { }; function getCredentials() { + if (process.env.GOOGLE_APPS_PRIVATE_KEY) { + const buffer = Buffer.from(process.env.GOOGLE_APPS_PRIVATE_KEY, 'base64').toString(); + const json = JSON.parse(buffer); + json.serviceAccount = true; + return Promise.resolve(json); + } return fs.readFileAsync(defaults.STORAGE_FILE) .then(JSON.parse) .catch(SyntaxError, function(e) { @@ -27,6 +34,34 @@ function getCredentials() { } function createAuthClient(credentials) { + if (credentials.serviceAccount == true) { + var auth = new ServiceToken( + credentials.client_email, + null, // 'path/to/key.pem', + + // Contents of private_key.pem if you want to load the pem file yourself + // (do not use the path parameter above if using this param) + credentials.private_key, + + // Scopes can be specified either as an array or as a single, space-delimited string + // ['https://spreadsheets.google.com/feeds'], // TODO: check if this is correct + [ + 'https://www.googleapis.com/auth/drive', + 'https://www.googleapis.com/auth/drive.file', + 'https://www.googleapis.com/auth/drive.appdata', + 'https://www.googleapis.com/auth/drive.apps.readonly', + ], + + // User to impersonate (leave empty if no impersonation needed) + null + ); + + return Promise.promisify(auth.authorize.bind(auth))() + .then(function(res) { + return auth; + }) + } + var auth = new OAuth2Client( credentials.client_id, credentials.client_secret,