all files / express-stormpath/lib/middleware/ get-user.js

70.48% Statements 74/105
71.15% Branches 37/52
100% Functions 13/13
70.48% Lines 74/105
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 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202                                                    77× 77× 77×   77× 77×       77×     75×   75× 14×   14× 14×     14× 14×                                                         10× 10× 10×         10×                               61×                                                 57× 57× 53× 53×                                          
'use strict';
 
var stormpath = require('stormpath');
 
var createSession = require('../helpers/create-session');
var expandAccount = require('../helpers/expand-account');
 
/**
 * This callback, when called, will simply continue processing the HTTP
 * request.
 *
 * @callback nextCallback
 * @private
 */
 
/**
 * Attempts to retrieve a user object from either the session, a user's API
 * keys, or a user's OAuth tokens, making it available in the current context.
 * If a user cannot be found, nothing will be done and the request will
 * continue processing.
 *
 * @method
 * @private
 *
 * @param {Object} req - The http request.
 * @param {Object} res - The http response.
 * @param {nextCallback} next - The callback which is called to continue
 *   processing the request.
 */
module.exports = function (req, res, next) {
  var application = req.app.get('stormpathApplication');
  var config = req.app.get('stormpathConfig');
  var logger = req.app.get('stormpathLogger');
 
  var accessTokenCookieName = config.web.accessTokenCookie.name;
  var refreshTokenCookieName = config.web.refreshTokenCookie.name;
 
  // In the event this has already been run (this can happen due to Express
  // routing logic) -- don't re-run this function.
  if (req.user) {
    return next();
  }
 
  var cookies = req.cookies;
 
  if (cookies && cookies[accessTokenCookieName]) {
    var authenticator = new stormpath.JwtAuthenticator(application);
 
    Eif (config.web.oauth2.password.validationStrategy === 'local') {
      authenticator.withLocalValidation();
    }
 
    authenticator.authenticate(cookies[accessTokenCookieName], function (err, authenticationResult) {
      if (err) {
        logger.info('Failed to authenticate the request. Invalid access_token found.');
 
        if (!cookies[refreshTokenCookieName]) {
          return next();
        }
 
        return new stormpath.OAuthRefreshTokenGrantRequestAuthenticator(application).authenticate({ refresh_token: cookies[refreshTokenCookieName] }, function (err, refreshGrantResponse) {
          if (err) {
            logger.info('Failed to refresh an access_token given a refresh_token.');
            return next();
          }
 
          refreshGrantResponse.getAccount(function (err, account) {
            Iif (err) {
              logger.info('Failed to get account from refreshGrantResponse.');
              return next();
            }
 
            Iif (account.status !== 'ENABLED') {
              logger.info('Account for refresh_token cookie is not ENALBED.');
              return next();
            }
 
            expandAccount(account, config.expand, logger, function (err, expandedAccount) {
              Iif (err) {
                logger.info('Failed to expand the user\'s account.');
                return next();
              }
 
              res.locals.user = expandedAccount;
              req.user = expandedAccount;
 
              Iif (refreshGrantResponse.grantedScopes) {
                res.locals.permissions = refreshGrantResponse.grantedScopes;
                req.user = expandedAccount;
                req.permissions = refreshGrantResponse.grantedScopes;
              }
 
              createSession(refreshGrantResponse, account, req, res);
              next();
            });
          });
        });
      }
 
      req.accessToken = authenticationResult.accessToken;
      authenticationResult.getAccount(function (err, account) {
        Iif (err) {
          logger.info('Failed to get account ' + authenticationResult.account.href);
          return next();
        }
 
        if (account.status !== 'ENABLED') {
          logger.info('Account for access_token cookie is not ENALBED.');
          return next();
        }
 
        expandAccount(account, config.expand, logger, function (err, expandedAccount) {
          Iif (err) {
            logger.info('Failed to expand the user\'s account.');
            return next();
          }
 
          res.locals.user = expandedAccount;
          req.user = expandedAccount;
 
          Iif (authenticationResult.grantedScopes) {
            res.locals.permissions = authenticationResult.grantedScopes;
            req.user = expandedAccount;
            req.permissions = authenticationResult.grantedScopes;
          }
 
          next();
        });
      });
    });
  } else if (cookies && cookies[refreshTokenCookieName]) {
    new stormpath.OAuthRefreshTokenGrantRequestAuthenticator(application).authenticate({ refresh_token: cookies[refreshTokenCookieName] }, function (err, refreshGrantResponse) {
      if (err) {
        logger.info('Failed to refresh an access_token given a refresh_token.');
        return next();
      }
 
      refreshGrantResponse.getAccount(function (err, account) {
        Iif (err) {
          logger.info('Failed to get account from refreshGrantResponse.');
          return next();
        }
 
        Iif (account.status !== 'ENABLED') {
          logger.info('Account for refresh_token cookie is not ENALBED.');
          return next();
        }
 
        expandAccount(account, config.expand, logger, function (err, expandedAccount) {
          Iif (err) {
            logger.info('Failed to expand the user\'s account.');
            return next();
          }
 
          res.locals.user = expandedAccount;
          req.user = expandedAccount;
 
          Iif (refreshGrantResponse.grantedScopes) {
            res.locals.permissions = refreshGrantResponse.grantedScopes;
            req.user = expandedAccount;
            req.permissions = refreshGrantResponse.grantedScopes;
          }
 
          createSession(refreshGrantResponse, account, req, res);
          next();
        });
      });
    });
  } else {
    application.authenticateApiRequest({ request: req }, function (err, result) {
      if (err) {
        logger.info('Failed to authenticate the incoming request.');
        return next();
      }
 
      result.getAccount(function (err, account) {
        Iif (err) {
          logger.info('Failed to get account.');
          return next();
        }
 
        Iif (account.status !== 'ENABLED') {
          logger.info('Account is not ENALBED.');
          return next();
        }
 
        expandAccount(account, config.expand, logger, function (err, expandedAccount) {
          Iif (err) {
            logger.info('Failed to expand the user\'s account.');
            return next();
          }
 
          res.locals.user = expandedAccount;
          req.user = expandedAccount;
 
          next();
        });
      });
    });
  }
};