text: 'use strict';
  
  var util = require('util');
  var loginProvider = require('./login-provider');
  var checkRequest = require('../utils/check-request');
  var pathUtil = require('../utils/path-util');
  var vcapUtils = require('../utils/vcap-utils');
  
  module.exports = function loginCheck(req, res, next) {
    if (!loginProvider.isLoginRequired(req) && !loginProvider.isExchangeTokenRequired(req)) {
      return next();
    } else if (loginProvider.isExchangeTokenRequired(req)){
      return loginProvider.exchangeToken(req,next);
    }
    if ((req.method !== 'GET' && pathUtil.pathAuthenticationType(req) === 'xsuaa') || checkRequest.isAjaxRequest(req)) {
      return sendUnauthorizedRequest(next);
    }
  
    loginProvider.getAuthenticator(req, res, function(err, authenticator) {
      if (err) {
        if (err === 401) {
          return sendUnauthorizedRequest(next, { 'WWW-Authenticate': 'Basic realm="' + getRealm() + '"' });
        }
        return next(err);
      }
      if (process.env.PRESERVE_FRAGMENT !== 'false') {
        req.res = res;
      }
      authenticator(req, res, next);
    });
  };
  
  function sendUnauthorizedRequest(next, headers) {
    var error = new Error('Authentication required');
    error.status = 401;
    error.headers = headers;
    next(error);
  }
  
  function getRealm() {
    var appEnv = vcapUtils.getAppEnv();
    var uris = appEnv.uris;
    var uri = (uris && uris.length > 0) ? uris[0] : '';
  
    var name = appEnv.application_name || appEnv.name;
  
    return util.format('%s at %s', name, uri);
  }