I am trying to create an email parser that responds to a pubsub gmail message. Currently, I can get and parse the pubsub message and extract historyId, but I am having problems authenticating my request in gmail api. Here is what I have so far:
function getAuthClient(event, callback) {
var GoogleAuth = require('google-auth-library');
var authFactory = new GoogleAuth();
authFactory.getApplicationDefault(function (err, authClient) {
if (err) {
console.log('Unable to get application default credentials.');
callback(err);
return;
}
if (authClient.createScopedRequired && authClient.createScopedRequired()) {
console.log('creating scoped client');
authClient = authClient.createScoped([
'https://mail.google.com/'
]);
}
callback(null, authClient);
});
}
exports.gmailParser = function gmailParser (event, callback) {
var path = require('path');
var base64 = require('base-64');
to pick up
process.env['GOOGLE_APPLICATION_CREDENTIALS'] = path.resolve(__dirname,
'auth_credentials.json');
console.log(process.env['GOOGLE_APPLICATION_CREDENTIALS']);
console.log(__dirname);
var pubsubMessage = event.data;
var baseMessage = pubsubMessage.data;
var decodedMessage = base64.decode(baseMessage);
var messageJSON = JSON.parse(decodedMessage);
var historyId = messageJSON.historyId;
var email = messageJSON.emailAddress;
getAuthClient(null, function(err, authClient) {
var google = require('googleapis');
var gmail = google.gmail('v1');
if(err) {
callback(err);
}
var params = {
userId: email,
startHistoryId: historyId
};
gmail.users.history.list(params, function(error, response) {
if (error) {
console.log('Encountered error', error);
callback(error);
} else {
console.log('Response', response);
callback(response);
}
});
});
};
The code works successfully, but I get the following error:
"Error: Login Required
at Request._callback (/user_code/node_modules/googleapis/node_modules/google-auth-library/lib/transporters.js:85:15)
at Request.self.callback (/user_code/node_modules/googleapis/node_modules/request/request.js:188:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (/user_code/node_modules/googleapis/node_modules/request/request.js:1171:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at IncomingMessage.<anonymous> (/user_code/node_modules/googleapis/node_modules/request/request.js:1091:12)
at IncomingMessage.g (events.js:291:16)
at emitNone (events.js:91:20)"
I tried adding authClient to the param object, but it returns a "Bad request" error. I tried to change the import order, created new credentials, but I couldn’t get anywhere. If anyone has pointers, we will be very grateful.