Skip to content

Commit

Permalink
connection: refetch token if invalid.
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenplusplus committed Sep 23, 2014
1 parent 7be2cae commit 6e5a560
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
25 changes: 18 additions & 7 deletions lib/common/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
'use strict';

var events = require('events');
var extend = require('extend');
var fs = require('fs');
var GAPIToken = require('gapitoken');
var nodeutil = require('util');
Expand Down Expand Up @@ -233,7 +234,15 @@ Connection.prototype.req = function(requestOptions, callback) {
callback(err);
return;
}
that.requester(authorizedReq, callback);
that.requester(authorizedReq, function(err) {
if (err && err.code === 401) {
// Token expired. Try to fetch a new one.
that.token = null;
that.req(requestOptions, callback);
return;
}
callback(err);
});
});
};

Expand All @@ -246,10 +255,10 @@ Connection.prototype.req = function(requestOptions, callback) {
* @example
* conn.createAuthorizedReq({}, function(err) {});
*/
Connection.prototype.createAuthorizedReq = function(reqOpts, callback) {
Connection.prototype.createAuthorizedReq = function(requestOptions, callback) {
var that = this;
// Add user agent.
reqOpts.headers = reqOpts.headers || {};

var reqOpts = extend(true, {}, requestOptions, { headers: {} });

if (reqOpts.headers['User-Agent']) {
reqOpts.headers['User-Agent'] += '; ' + USER_AGENT;
Expand Down Expand Up @@ -305,9 +314,11 @@ Connection.prototype.isConnected = function() {
* @return {object} Authorized request options.
*/
Connection.prototype.authorizeReq = function(requestOptions) {
requestOptions.headers = requestOptions.headers || {};
requestOptions.headers.Authorization = 'Bearer ' + this.token.accessToken;
return requestOptions;
return extend(true, {}, requestOptions, {
headers: {
Authorization: 'Bearer ' + this.token.accessToken
}
});
};

/**
Expand Down
17 changes: 17 additions & 0 deletions test/common/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,23 @@ describe('Connection', function() {
conn.req({ uri: 'https://someuri' }, function() {});
});

it('should fetch a new token if API returns a 401', function() {
var fetchTokenCount = 0;
conn.fetchToken = function(callback) {
fetchTokenCount++;
callback(null, tokenNeverExpires);
};
conn.requester = function(req, callback) {
if (fetchTokenCount === 1) {
callback({ code: 401 });
} else {
callback(null);
}
};
conn.req({ uri: 'https://someuri' }, function() {});
assert.equal(fetchTokenCount, 2);
});

it('should pass error to callback', function(done) {
var error = new Error('Something terrible happened.');
conn.fetchToken = function(cb) {
Expand Down

0 comments on commit 6e5a560

Please sign in to comment.