all files / express-stormpath/lib/controllers/ get-token.js

100% Statements 30/30
100% Branches 16/16
100% Functions 5/5
100% Lines 30/30
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80                            12× 12× 12× 12× 12×                 12×     11×                                                    
'use strict';
 
var stormpath = require('stormpath');
 
/**
 * Allow a developer to exchange their API keys for an OAuth token.
 *
 * The URL this controller is bound to can be controlled via express-stormpath
 * settings.
 *
 * @method
 *
 * @param {Object} req - The http request.
 * @param {Object} res - The http response.
 */
module.exports = function (req, res) {
  var application = req.app.get('stormpathApplication');
  var config = req.app.get('stormpathConfig');
  var grantType = req.body.grant_type;
  var isPostRequest = req.method === 'POST';
  var logger = req.app.get('stormpathLogger');
 
  function writeErrorResponse(err) {
    var error = {
      error: err.error,
      message: err.userMessage || err.message
    };
 
    logger.info('An OAuth token exchange failed due to an improperly formed request.');
 
    return res.status(err.status || err.statusCode || 400).json(error);
  }
 
  if (!isPostRequest) {
    return res.status(405).end();
  }
 
  switch (grantType) {
    case undefined:
      writeErrorResponse({
        error: 'invalid_request'
      });
      break;
    case 'password':
    case 'refresh_token':
      var authenticator = new stormpath.OAuthAuthenticator(application);
 
      authenticator.authenticate(req, function (err, authResult) {
        if (err) {
          return writeErrorResponse(err);
        }
 
        res.json(authResult.accessTokenResponse);
      });
      break;
 
    case 'client_credentials':
      application.authenticateApiRequest({
        request: req,
        ttl: config.web.oauth2.client_credentials.accessToken.ttl,
        scopeFactory: function (account, requestedScopes) {
          return requestedScopes;
        }
      }, function (err, authResult) {
        if (err) {
          return writeErrorResponse(err);
        }
 
        res.json(authResult.tokenResponse);
      });
      break;
 
    default:
      writeErrorResponse({
        error: 'unsupported_grant_type'
      });
      break;
  }
};