all files / express-stormpath/lib/helpers/ redirect-to-organization.js

100% Statements 9/9
100% Branches 2/2
100% Functions 2/2
100% Lines 9/9
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                                                         
'use strict';
 
var url = require('url');
 
var getHost = require('./get-host');
 
/**
* Performs a redirect to a subdomain of the current domain, using the name of
* the given organization as the name of the subdomain. Preserves port, path,
* and query parameters.
*
* @private
* @method
*
* @param {Object} req - HTTP request
* @param {Object} res - HTTP response
* @param {Object} organization - Organization resource
*/
module.exports = function redirectToOrganization(req, res, organization) {
  var uri = req.protocol
    + '://' + organization.nameKey
    + '.'
    + getHost(req)
    + url.parse(req.url).pathname;
 
  var queryParams = Object.keys(req.query);
 
  if (queryParams.length > 0) {
    uri += '?' + queryParams.map(function (param) {
      return encodeURIComponent(param)
        + '='
        + encodeURIComponent(req.query[param]);
    }).join('&');
  }
 
  res.redirect(uri);
};