Middleware Function for the IP
@param {Request} req
@param {Response} res
@param {function} next
968211
function middlewareFunction (req,res,next){

  return ipToLocation(req.ip)
    .then(function (location) {
      req.location = location;
      next();
    })
    .catch(function (error) {
      req.locationError = error;
      next();
    })

}
1020979
function nextMiddleware (factory, mw, info) {
  const {
    resolved,
    index,
    routes,
    middlewares,
    errorMiddleware,
    req,
    res,
    metrics
  } = info

  const local = {
    finished: false,
    timeout: null
  }

  // check if the request has already been resolved
  if (resolved) return

  // get the current middleware
  const current = mw[index]
  const exec = {
    name: current.functionName,
    started: Date.now(),
    ended: null,
    data: null
  }

  metrics.executions.push(exec)

  // create a next method
  const next = data => {
    clearTimeout(local.timeout)
    if (local.finished || info.resolved) return
    local.finished = true

    // add the result
    exec.ended = Date.now()
    exec.data = data

    // allow reroutes to valid named route paths
    if (_.isString(data)) {
      const route = routes[data]
      if (!route) {
        if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
          info.index = 0
          req.error = new Error(`No route found for "${data}"`)
          return nextMiddleware(factory, errorMiddleware, info)
        }
        res.end(data)
      }

      // get the correct route set
      const mwSet = route.type === ERROR_MIDDLEWARE
        ? errorMiddleware
        : middlewares

      // increment the re-route counter, set the index and go
      req.reroutes += 1
      info.index = route.index
      return nextMiddleware(factory, mwSet, info)
    }

    // check for an error passed to the next method and not
    // already in the error middleware chain. if condition met
    // start processing error middleware
    if (data instanceof Error) {
      if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
        info.index = 0
        req.error = data
        return nextMiddleware(factory, errorMiddleware, info)
      }
      res.end(data)
    }

    // check if there is any more middleware in the chain
    // if not, call end to complete the request
   return info.index === mw.length
     ? res.end()
     : nextMiddleware(factory, mw, info)
  }

  // create a timeout for the middleware if timeout > 0
  if (current.timeout > 0) {
    local.timeout = setTimeout(() => {
      local.finished = true
      req.error = new Error(current.functionName
        + ' middleware timed out')

      // add the result
      exec.ended = Date.now()
      exec.data = req.error

      // if already in error middleware and timed out
      // end the entire request, othewise move to error mw
      if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
        info.index = 0
        return nextMiddleware(factory, errorMiddleware, info)
      }
      return res.end()
    }, current.timeout)
  }

  // try to execute the resolver and if unable
  // move to error middleware. if already in error
  // middleware end the request
  try {
    info.index += 1
    current.resolver(req, res, next)
  } catch (err) {
    clearTimeout(local.timeout)
    local.finished = true
    factory.emit(EVENT_ERROR, err)
    req.error = err

    // add the result
    exec.ended = Date.now()
    exec.data = req.error

    if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
      info.index = 0
      return nextMiddleware(factory, errorMiddleware, info)
    }
    return res.end()
  }
}
257932
function router(rpc, handlers, req, res) {
  var $       = rpc.$;
  var api     = rpc.api;
  var request = api.handle(req.method, req.url);
  var dom     = domain.create();

  // the request handler doesn't exit
  // TODO: hoist response logic
  if (!request) {
    res.statusCode = 404;
    res.end();
    return;
  }

  var context = new Context(); // TODO: hoist to own module
  var handle  = request.handle;
  var params  = {};

  // TODO: hoist logic to 'union' module
  var key;
  for(key in request.params) params[key] = request.params[key];
  for(key in request.query)  params[key] = request.query[key];

  var future = $.future();

  future.setWritable(res);
  future.setReadable(req);

  // TODO: extract request making logic
  res.setHeader('Transfer-Encoding' , 'chunked');
  res.setHeader('Content-Type'      , 'application/json');

  dom.on('error', function (err) {
    var statusCode = err.statusCode;

    // only catch known errors, re-throw unexpected errors
    if (!statusCode) throw err;

    // TODO: hoist response logic
    res.statusCode = statusCode;
    res.write(JSON.stringify(err));
    res.end();
  });

  // domain should handle all route errors
  dom.run(function () {
    handlers[handle](future, params, context);
  });
}
269684
function (req, res, next) {
      if (req.query.return) {
        req.session.oauth2return = req.query.return;
      }
      next();
    }
1182001
function (req, res, next) {
        var ip = IPAddressHelper.getClientIP(req)
            , route = req.miajs.route
            , key = ip + route.path + route.method;

        if (_.isEmpty(route.rateLimits)) {
            next();
            return;
        }

        RateLimiter.checkRateLimitsByKey(key, route.rateLimits).then(function (rateLimiterResult) {
            if (rateLimiterResult.remaining == -1) {
                _logInfo("Rate limit of " + rateLimiterResult.limit + "req/" + rateLimiterResult.timeInterval + "min requests exceeded " + route.requestmethod.toUpperCase() + " " + route.url + " for " + ip);
                res.header("X-Rate-Limit-Limit", rateLimiterResult.limit);
                res.header("X-Rate-Limit-Remaining", 0);
                res.header("X-Rate-Limit-Reset", rateLimiterResult.timeTillReset);
                next(new MiaError({
                    status: 429,
                    err: {
                        'code': 'RateLimitExceeded',
                        'msg': Translator('system', 'RateLimitExceeded')
                    }
                }));
            }
            else {
                res.header("X-Rate-Limit-Limit", rateLimiterResult.limit);
                res.header("X-Rate-Limit-Remaining", rateLimiterResult.remaining);
                res.header("X-Rate-Limit-Reset", rateLimiterResult.timeTillReset);
                next();
            }
        }).catch(function () {
            next();
        });
    }
513455
function (req,res,cfg) {
		if(!ipr.checkip(req,process.rapidcfg.ipallow)){return res.status(401).send({message:"error",error:"access allowed by IP"})}
		var ck = utils.checkadmpwd(req,process.rapidcfg.suser,process.rapidcfg.spwd);
		if (ck.message != "OK"){return res.send({error:ck.error})};
		if (!process.rapidcfg.mdb && req.params["0"] !== 'reload'){
			return res.status(404).send({error:"system not configured"})
		};
		/*console.log(req.params["0"]);
		console.log(req.body);
		console.log(req.query);
		console.log(req.method); */
		var fastr = req.params["0"];	
		if (typeof intc[fastr]=='function'){intc[fastr](req,res,cfg)} else {
			res.status(404).send({error:"service not implemented",service:fastr})}
	}
907701
function runMiddlewareStack(stack, req, res, callback) {
  let index = 0;
  // the middleware layer handover callback
  function next(err) {
    // get next middleware callback from stack
    const handle = stack[index++];
    // if no more layers in stack, invoke done callback and exit recursion
    if (!handle) {
      callback(err);
      return;
    }
    let error = err;
    // call the middleware handler
    try {
      if (err && handle.length === 4) {
        // there is an error and it's an error-handling middleware
        handle(err, req, res, next);
        return;
      } else if (!err && handle.length < 4) {
        // no error and it's a request-handling middleware
        handle(req, res, next);
        return;
      }
    } catch (e) {
      // if new error thrown, replace the error
      error = e;
    }
    // otherwise skip layer
    next(error);
  }
  // start going through middleware stack
  next();
}
1359147
function middleware(req, res, next) {
		//Check to see if req.url matches a fingerprinted URL
		var info = fingerprints[req.originalUrl];
		//If this request matches a fingerprint
		if(info)
		{
			//Set headers
			if(info.lastModified)
				res.setHeader("Last-Modified", info.lastModified.toUTCString() );
			if(info.etag)
				res.setHeader("ETag", info.etag);
			if(info.expires)
			{
				res.setHeader("Expires", info.expires.toUTCString() );
				res.setHeader("Cache-Control", "public; max-age=" +
					Math.floor((info.expires.getTime() - new Date().getTime() ) / 1000) );
			}
			//Check If-Modified-Since and If-None-Match headers and return 304, if appropriate
			if((req.headers["if-none-match"] && info.etag == req.headers["if-none-match"]) ||
				(req.headers["if-modified-since"] && info.lastModified.toUTCString() ==
					req.headers["if-modified-since"]) )
				return (res.sendStatus || res.send).call(res, 304);
		}
		//If req.assetFingerprint is already there, do nothing.
		if(!req.assetFingerprint)
		{
			//Create req.assetFingerprint
			req.assetFingerprint = assetFingerprint;
			//Expose req.assetFingerprint in Express helper
			res.locals.assetFingerprint = function() {
				return assetFingerprint.apply(req, arguments);
			};
		}
		//Run next middleware
		next();
	}
1009284
function (next) {
                request(url, function (err, res, body) {
                    if (err) {
                        return next(err);
                    }
                    next(null, body);
                });
            }
987599
function(host, next) {
    var tokens = tldtools.extract(host),
      resolvingHost;

    if (ipaddr.IPv4.isValid(host) || ipaddr.IPv6.isValid(host) ) {
      next(false, [ host ], host);
    } else {
      resolvingHost = tokens.inspect.getDomain() || tokens.domain;
      dns.resolve(resolvingHost, function(err, aRecords) {
        next(err, aRecords, resolvingHost );
      });
    }
  }
1301289
function send(req, res, next){
  /**
   * [type description]
   * @param  {[type]} type    [description]
   * @param  {[type]} options [description]
   * @return {[type]}         [description]
   */
  res.type = function(type, options){
    type = CONTENT_TYPES[ type ] || type;
    options = Object.keys(options || {}).map(function(name){
      return [ name, options[ name ] ].join('=');
    }).join('; ');
    res.setHeader('Content-Type', type + (options ? ('; ' + options) : ''));
    return res;
  };
  /**
   * [header description]
   * @param  {[type]} name  [description]
   * @param  {[type]} value [description]
   * @return {[type]}       [description]
   */
  res.header = function(name, value){
    res.setHeader(name, value);
    return res;
  };
  
  /**
   * [status description]
   * @param  {[type]} code [description]
   * @return {[type]}      [description]
   */
  res.status = function(code){
    this.statusCode = code;
    return res;
  };

  /**
   * [redirect description]
   * @param  {[type]} url     [description]
   * @param  {[type]} code    [description]
   * @param  {[type]} headers [description]
   * @return {[type]}         [description]
   */
  res.redirect = function(url, code){
    this.status(code || 302);
    this.header('Location', url);
    return res.end();
  };
  
  /**
   * [send description]
   * @param  {[type]} body [description]
   * @return {[type]}      [description]
   */
  res.send = body => {
    var type = ({})
      .toString
      .call(body)
      .match(/^\[object (\w+)\]$/)[1]
      .toLowerCase();

    if(type === 'object' && body.then)
      type = 'promise';
      
    if(type === 'object' && (body instanceof Stream))
      type = 'stream';
    
    if(type === 'object' && (body instanceof Buffer))
      type = 'buffer';

    if(type === 'object' && (body instanceof Response))
      type = 'response';
      
    switch(type){
      case 'number':
        res.status(body);
        res.send(STATUS_CODES[body]);
        break;
      case 'function':
        body = body(req, res);
        body && res.send(body);
        break;
      case 'error':
        res.send(body.stack);
        break;
      case 'promise':
        body.then(res.send, next);
        break;
      case 'stream':
        body.pipe(res);
        break;
      case 'array':
      case 'object':
        res.type('json');
        res.send(JSON.stringify(body));
        break;
      case 'string':
      case 'buffer':
      case 'uint8array':
        res.end(body);
        break;
      case 'response':
        body.respond(req, res);
        break;
      default:
        res.end();
        break;
    }
    return res;
  };
  return next();
}
1122899
function ( req, res, next ) {

    if ( req.body ) {
        trimStringProperties(req.body);
    }

    if ( req.params ) {
        trimStringProperties(req.params);
    }

    if ( req.query ) {
        trimStringProperties(req.query);
    }

    next();

}
204286
function(req, res) {
    var params = URL.parse(req.url, true).query;
    var oauth2_server_id = params.provider || this.config.default_server;
    var next_url = this.nexturl_query(req, params);
    this.redirects_for_login(oauth2_server_id, res, next_url);
  }
817746
function (request, response, next) {
                if (!next) {
                    next = makeDefaultNext(request, response);
                }
                try {
                    var url = request.url;
                    var questionIndex = url.indexOf("?");
                    var querystring = "";
                    if (questionIndex !== -1) {
                        // if there is a querystring, we'll just chop that part off
                        // it's still preserved in request.url, and should be handled
                        // by other middleware.
                        querystring = url.substring(questionIndex);
                        url = url.substring(0, questionIndex);
                    }
                    
                    var now = +new Date();
                    if (cacheExpirationTime < now) {
                        // time to reset the dynamic cache cache
                        
                        // Object.create(null) is used instead of {} so it doesn't have a prototype of Object.prototype
                        dynamicRouteCache = Object.create(null);
                        redirectCache = Object.create(null);
                        cacheExpirationTime = now + CACHE_CLEAR_TIME;
                    }
                    
                    var actualUrl = url;
                    var cachedResult = redirectCache[actualUrl];
                    if (cachedResult) {
                        movedPermanently(response, cachedResult + querystring);
                        return;
                    }
                    
                    var lowerMethod = request.method.toLowerCase();
                    if (url.length > 1 && url[url.length - 1] === "/") {
                        url = trimEndingSlashes(url);
                    }
                    var lowerUrl = url.toLowerCase();
                    var staticRoute = staticRoutes[lowerUrl];
                    var params;
                    var callback;
                    var descriptor;
                    var properUrl;
                    
                    if (staticRoute) {
                        properUrl = staticRoute.route;
                        if (properUrl !== actualUrl) {
                            redirectCache[actualUrl] = properUrl;
                            movedPermanently(response, properUrl + querystring);
                            return;
                        }
                        
                        descriptor = staticRoute.descriptor;
                        
                        // we found a static route
                        callback = descriptor[lowerMethod];
                        
                        if (!callback) {
                            // the URL exists, but does not have the provided method defined for it
                            methodNotAllowedHandler(request, response, next);
                            return;
                        }

                        params = emptyParams;
                    } else {
                        cachedResult = dynamicRouteCache[actualUrl];
                        if (cachedResult) {
                            descriptor = cachedResult.descriptor;
                            callback = descriptor[lowerMethod];
                            if (!callback) {
                                // the URL exists, but does not have the provided method defined for it
                                methodNotAllowedHandler(request, response, next);
                                return;
                            }
                            params = cachedResult.params;
                        } else {
                            searchDynamicRoutes:
                            for (var i = 0, len = dynamicRoutes.length; i < len; i += 1) {
                                var dynamicRoute = dynamicRoutes[i];
                                var prefix = dynamicRoute.prefix;
                            
                                if (prefix !== "/" && !startsWith(lowerUrl, prefix)) {
                                    continue;
                                }
                            
                                var routes = dynamicRoute.routes;
                                searchWithinPrefix:
                                for (var j = 0, lenJ = routes.length; j < lenJ; j += 1) {
                                    var route = routes[j];
                                    var match = route.regex.exec(url);
                                    if (!match) {
                                        continue;
                                    }
                                
                                    descriptor = route.descriptor;
                                    callback = descriptor[lowerMethod];
                                    if (!callback) {
                                        // the URL exists, but does not have the provided method defined for it
                                        methodNotAllowedHandler(request, response, next);
                                        return;
                                    }
                                
                                    var literals = route.literals;
                                    properUrl = literals[0];
                                    var argumentNames = route.argumentNames;
                                    var converters = route.converters;
                                    params = {};
                                    for (var k = 0, lenK = argumentNames.length; k < lenK; k += 1) {
                                        var unconvertedValue = match[k * 2 + 2];
                                        var convertedValue;
                                        try {
                                            convertedValue = converters[k](unconvertedValue);
                                        } catch (ex) {
                                            if (ex instanceof escort.ValidationError) {
                                                // if the converter explicitly throws a ValidationError, the route doesn't match.
                                                // thus, we need to keep searching for the correct route.
                                                callback = undefined;
                                                continue searchWithinPrefix;
                                            } else if (ex instanceof escort.CasingError) {
                                                unconvertedValue = ex.expectedCasing;
                                                convertedValue = converters[k](unconvertedValue); // guaranteed not to error
                                            } else {
                                                throw ex;
                                            }
                                        }
                                        properUrl += unconvertedValue;
                                        properUrl += literals[k + 1] || "";
                                        params[argumentNames[k]] = convertedValue;
                                    }
                                    if (route.hasEndingSlash) {
                                        properUrl += "/";
                                    }
                            
                                    if (actualUrl !== properUrl) {
                                        redirectCache[actualUrl] = properUrl;
                                        movedPermanently(response, properUrl + querystring);
                                        return;
                                    }
                                    
                                    // params needs to be frozen since it will be potentially used in later requests through the dynamic route caching system
                                    freeze(params);
                                    dynamicRouteCache[actualUrl] = {
                                        descriptor: descriptor,
                                        params: params
                                    };
                                    
                                    // we're done, so we need to break out of the outer for loop
                                    break searchDynamicRoutes;
                                }
                            }
                        }
                    }
                    
                    if (!callback) {
                        // route was unable to be located
                        if (notFoundHandler) {
                            notFoundHandler(request, response, next);
                        } else {
                            next();
                        }
                        return;
                    }
                    
                    // set params on request as well as pass it into the callback.
                    request.params = params;
                    // the descriptor is passed in as "this" so that the user can do this.post(request, response) from their get callback.
                    callback.call(descriptor, request, response, params, !notFoundHandler ? next : function (err) {
                        if (err) {
                            next(err);
                        } else {
                            notFoundHandler(request, response, next);
                        }
                    });
                } catch (err) {
                    next(err);
                }
            }
1213190
function (req, res, next) {
                    req.mounted = true
                    req.url     = req.url.replace(remove, '')

                    // clear cached req.path
                    delete req._path
                    delete req._pathLength

                    next()
                }
229093
function serviceCall(req, res, next) {
        connector.runCall(req.params.connection, req.params.call, req.body).then(res.json.bind(res), next).done();
    }
350372
function throttleMiddleware (request, response, next) {
    var ip = null

    if (config.useCustomHeader && request.headers[config.useCustomHeader]) {
      ip = request.headers[config.useCustomHeader]
    } else {
      ip = request.headers['x-forwarded-for'] ||
        request.connection.remoteAddress ||
        request.socket.remoteAddress ||
        request.connection.socket.remoteAddress || ''

      ip = ip.split(',')[0]
      if (!ipRegex().test(ip) || ip.substr(0, 7) === '::ffff:' || ip === '::1') {
        ip = '127.0.0.1'
      } else {
        ip = ip.match(ipRegex())[0]
      }
    }

    Throttle
      .findOneAndUpdate({ip: ip}, { $inc: { hits: 1 } }, { upsert: false })
      .exec(function (error, throttle) {
        if (errHandler(response, next, error)) { return }
        if (!throttle) {
          throttle = new Throttle({
            createdAt: new Date(),
            ip: ip
          })
          throttle.save(function (error, throttle) {
            // THERE'S NO ERROR, BUT THROTTLE WAS NOT SAVE
            if (!throttle && !error) {
              error = new Error('Error checking rate limit.')
            }

            if (errHandler(response, next, error)) { return }

            respondWithThrottle(request, response, next, throttle)
          })
        } else {
          respondWithThrottle(request, response, next, throttle)
        }
      })
  }