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

10.91% Statements 6/55
0% Branches 0/35
0% Functions 0/12
10.91% Lines 6/55
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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134                                                                                                                                                                                                                                                               
'use strict';
 
var stormpath = require('stormpath');
var expandAccount = require('../helpers/expand-account');
 
/**
 * 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);
  }
 
  function writeSuccessResponse(authResult) {
    res.json(authResult.accessTokenResponse);
  }
 
  function continueWithHandlers(authResult, preHandler, postHandler, onCompleted) {
    var options = req.body || {};
 
    if (!preHandler) {
      preHandler = function (options, req, res, next) {
        next();
      };
    }
 
    preHandler(options, req, res, function (err) {
      if (err) {
        return writeErrorResponse(err);
      }
 
      if (postHandler) {
        return authResult.getAccount(function (err, account) {
          if (err) {
            return writeErrorResponse(err);
          }
 
          expandAccount(account, config.expand, logger, function (err, expandedAccount) {
            if (err) {
              return writeErrorResponse(err);
            }
 
            return config.postLoginHandler(expandedAccount, req, res, function (err) {
              if (err) {
                return writeErrorResponse(err);
              }
 
              onCompleted();
            });
          });
        });
      }
 
      onCompleted();
    });
  }
 
  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);
        }
 
        if (grantType === 'password' && (config.preLoginHandler || config.postLoginHandler)) {
          return continueWithHandlers(
            authResult,
            config.preLoginHandler,
            config.postLoginHandler,
            writeSuccessResponse.bind(null, authResult)
          );
        }
 
        writeSuccessResponse(authResult);
      });
      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;
  }
};