all files / express-stormpath/lib/controllers/ id-site-verify.js

61.54% Statements 40/65
44.83% Branches 13/29
88.89% Functions 8/9
61.54% Lines 40/65
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                                                                                                                                                                 
'use strict';
 
var url = require('url');
var nJwt = require('njwt');
var stormpath = require('stormpath');
 
var helpers = require('../helpers');
var middleware = require('../middleware');
 
/**
 * This controller handles a Stormpath ID Site authentication.  Once a user is
 * authenticated, they'll be returned to the site.
 *
 * @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 logger = req.app.get('stormpathLogger');
 
  var params = req.query || {};
  var stormpathToken = params.jwtResponse || '';
  var assertionAuthenticator = new stormpath.StormpathAssertionAuthenticator(application);
 
  assertionAuthenticator.authenticate(stormpathToken, function (err) {
    Iif (err) {
      logger.info('During an IdSite login attempt, we were unable to verify the JWT response.');
      return helpers.writeJsonError(res, err);
    }
 
    var parsedToken = nJwt.verify(stormpathToken, config.client.apiKey.secret);
    var tokenStatus = parsedToken.body.status;
 
    function redirectNext() {
      var nextUri = config.web.idSite.nextUri;
      var nextQueryPath = url.parse(params.next || '').path;
      res.redirect(302, nextQueryPath || nextUri);
    }
 
    function authenticateToken(callback) {
      var stormpathTokenAuthenticator = new stormpath.OAuthStormpathTokenAuthenticator(application);
 
      stormpathTokenAuthenticator.authenticate({ stormpath_token: stormpathToken }, function (err, authenticationResult) {
        Iif (err) {
          logger.info('During an IdSite login attempt, we were unable to create a Stormpath session.');
          return helpers.writeJsonError(res, err);
        }
 
        authenticationResult.getAccount(function (err, account) {
          Iif (err) {
            logger.info('During an IdSite login attempt, we were unable to retrieve an account from the authentication result.');
            return helpers.writeJsonError(res, err);
          }
 
          helpers.expandAccount(account, config.expand, logger, function (err, expandedAccount) {
            Iif (err) {
              logger.info('During an IdSite login attempt, we were unable to expand the Stormpath account.');
              return helpers.writeJsonError(res, err);
            }
 
            helpers.createSession(authenticationResult, expandedAccount, req, res);
 
            callback(null, expandedAccount);
          });
        });
      });
    }
 
    function handleAuthRequest(type, callback) {
      var handler;
 
      switch (type) {
        case 'registration':
          handler = config.postRegistrationHandler;
          break;
        case 'login':
          handler = config.postLoginHandler;
          break;
        default:
          return callback(new Error('Invalid authentication request type: ' + type));
      }
 
      Iif (handler) {
        authenticateToken(function (err, expandedAccount) {
          if (err) {
            return callback(err);
          }
          handler(expandedAccount, req, res, callback);
        });
      } else {
        authenticateToken(callback);
      }
    }
 
    switch (tokenStatus) {
      case 'REGISTERED':
        if (!config.web.register.autoLogin) {
          return redirectNext();
        }
        handleAuthRequest('registration', redirectNext);
        break;
 
      case 'AUTHENTICATED':
        handleAuthRequest('login', redirectNext);
        break;
 
      case 'LOGOUT':
        middleware.revokeTokens(req, res);
        middleware.deleteCookies(req, res);
        redirectNext();
        break;
 
      default:
        res.status(500).end('Unknown ID site result status: ' + tokenStatus);
        break;
    }
  });
};