all files / express-stormpath/lib/middleware/ authentication-required.js

21.43% Statements 3/14
0% Branches 0/7
0% Functions 0/1
21.43% Lines 3/14
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                                                                         
'use strict';
 
var helpers = require('../helpers');
var deleteCookies = require('./delete-cookies');
 
/**
 * Assert that a user is logged into an account before allowing the user to
 * continue.  If the user is not logged in, they will be redirected to the login
 * page.  This method allows the user to authenticate ANY WAY THEY WISH, and
 * responds appropriately given the Accept type of the client.  This is useful
 * for SPA type applications.
 *
 * @method
 *
 * @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 if the user is authenticated.
 */
module.exports = function (req, res, next) {
  var config = req.app.get('stormpathConfig');
  var logger = req.app.get('stormpathLogger');
 
  if (req.user) {
    return next();
  }
 
  logger.info('User attempted to access a protected endpoint with invalid credentials.');
  deleteCookies(req, res);
 
  if (req.accepts(['html', 'json']) === 'html') {
    var url = config.web.login.uri + '?next=' + encodeURIComponent(req.originalUrl);
    return res.redirect(302, url);
  }
 
  var message = req.authenticationError && req.authenticationError.userMessage || 'Unauthorized';
 
  helpers.writeJsonError(res, { status: 401, message: message });
};