Skip to content

Commit

Permalink
Implement support for parsing error responses.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaredhanson committed Aug 14, 2013
1 parent 16b199d commit 5fa7ed1
Showing 1 changed file with 43 additions and 1 deletion.
44 changes: 43 additions & 1 deletion lib/strategy.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ var passport = require('passport-strategy')
, utils = require('./utils')
, OAuth2 = require('oauth').OAuth2
, AuthorizationError = require('./errors/authorizationerror')
, AccessTokenError = require('./errors/accesstokenerror')
, InternalOAuthError = require('./errors/internaloautherror');


Expand Down Expand Up @@ -144,7 +145,7 @@ OAuth2Strategy.prototype.authenticate = function(req, options) {
// presence does not appear to cause any issues.
this._oauth2.getOAuthAccessToken(code, { grant_type: 'authorization_code', redirect_uri: callbackURL },
function(err, accessToken, refreshToken, params) {
if (err) { return self.error(new InternalOAuthError('Failed to obtain access token', err)); }
if (err) { return self.error(self._createOAuthError('Failed to obtain access token', err)); }

self._loadUserProfile(accessToken, function(err, profile) {
if (err) { return self.error(err); }
Expand Down Expand Up @@ -229,6 +230,29 @@ OAuth2Strategy.prototype.authorizationParams = function(options) {
return {};
};

/**
* Parse error response from OAuth 2.0 endpoint.
*
* OAuth 2.0-based authentication strategies can overrride this function in
* order to parse error responses received from the token endpoint, allowing the
* most informative message to be displayed.
*
* If this function is not overridden, the body will be parsed in accordance
* with RFC 6749, section 5.2.
*
* @param {String} body
* @param {Number} status
* @return {Error}
* @api protected
*/
OAuth2Strategy.prototype.parseErrorResponse = function(body, status) {
var json = JSON.parse(body);
if (json.error) {
return new AccessTokenError(json.error_description, json.error, json.error_uri)
}
return null;
};

/**
* Load user profile, contingent upon options.
*
Expand Down Expand Up @@ -260,6 +284,24 @@ OAuth2Strategy.prototype._loadUserProfile = function(accessToken, done) {
}
};

/**
* Create an OAuth error.
*
* @param {String} message
* @param {Object|Error} err
* @api private
*/
OAuth2Strategy.prototype._createOAuthError = function(message, err) {
var e;
if (err.statusCode && err.data) {
try {
e = this.parseErrorResponse(err.data, err.statusCode);
} catch (_) {}
}
if (!e) { e = new InternalOAuthError(message, err); }
return e;
};


/**
* Expose `OAuth2Strategy`.
Expand Down

0 comments on commit 5fa7ed1

Please sign in to comment.