all files / express-stormpath/lib/controllers/ logout.js

26.67% Statements 8/30
0% Branches 0/8
0% Functions 0/10
26.67% Lines 8/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 81                                                                                                                                                 
'use strict';
 
var url = require('url');
 
var helpers = require('../helpers');
var middleware = require('../middleware');
var idSiteRedirect = require('./id-site-redirect');
 
/**
 * This controller logs out an existing user, then redirects them to the
 * homepage.
 *
 * @method
 *
 * @param {Object} req - The http request.
 * @param {Object} res - The http response.
 * @param {function} next - The next function.
 */
module.exports = function (req, res, next) {
  var config = req.app.get('stormpathConfig');
 
  function cleanupSession(callback) {
    // Retrieve the user and remove it from the request.
    delete req['user'];
 
    // Remove tokens.
    middleware.revokeTokens(req, res);
    middleware.deleteCookies(req, res);
 
    // If we have have an account, then invalidate the cache for it.
    // This needs to be brought back once account caching has been implemented
 
    // if (account) {
    //   return account.invalidate(function () {
    //     callback();
    //   });
    // }
 
    callback();
  }
 
  function handlePostLogout(account, callback) {
    var postLogoutHandler = config.postLogoutHandler;
 
    if (postLogoutHandler) {
      return postLogoutHandler(account, req, res, callback);
    }
 
    callback();
  }
 
  function handleLogout(callback) {
    middleware.getUser(req, res, function () {
      var account = req.user;
      cleanupSession(function () {
        handlePostLogout(account, callback);
      });
    });
  }
 
  helpers.handleAcceptRequest(req, res, {
    'application/json': function () {
      handleLogout(function () {
        res.status(200).end();
      });
    },
    'text/html': function () {
      handleLogout(function () {
        if (config.web.idSite.enabled) {
          return idSiteRedirect({ logout: true })(req, res);
        }
 
        var queryNextPath = url.parse(req.query.next || '').path;
        var nextUri = queryNextPath || config.web.logout.nextUri;
 
        res.redirect(nextUri);
      });
    }
  }, next);
};