Provide connect/express-style middleware

@param {IncomingMessage} req
@param {ServerResponse} res
@param {Function} next
@return {*}
550901
function xmlbodyparser(req, res, next) {

    var data = '';

    var parser = new xml2js.Parser(parserOptions);

    /**
     * @param {Error} err
     * @param {Object} [xml]
     */

    var responseHandler = function (err, xml) {
        if (err) {
          err.status = 400;
          return next(err);
        }

        req.body = xml || req.body;
        req.rawBody = data;
        next();
    };

    if (req._body) {
      return next();
    }

    req.body = req.body || {};

    if (!hasBody(req) || !module.exports.regexp.test(mime(req))) {
      return next();
    }

    req._body = true;

    // explicitly cast incoming to string
    req.setEncoding('utf-8');
    req.on('data', function (chunk) {
      data += chunk;
    });

    // in case `parseString` callback never was called, ensure response is sent
    parser.saxParser.onend = function() {
      if (req.complete && req.rawBody === undefined) {
        return responseHandler(null);
      }
    };

    req.on('end', function () {

      // invalid xml, length required
      if (data.trim().length === 0) {
        return next(error(411));
      }

      parser.parseString(data, responseHandler);

    });
  }
612222
function handler(req, res, next) {
  var userAgent = req.headers["user-agent"];

  //-- set device
  req.device = new Device(userAgent);

  return next();
}
1226877
function get (req, res, next) {
    var prop = pluralize.singular(req.params.resource)
    req.query[prop + 'Id'] = utils.toNative(req.params.id)
    if (!req.query._filter) {
      req.query._filter = prop + 'Id=' + req.params.id
    } else {
      req.query._filter += ',' + prop + 'Id=' + req.params.id
    }
    req.url = '/' + req.params.nested
    next()
  }
116018
function authorize(req, res, next) {
  const role = findRoleFromRequest(
    req,
    options.roleSearchPath,
    options.defaultRole,
    options.decodedObjectName
  );

  if (req.originalUrl === '/') {
    return next();
  }

  const policy = options.policies.get(role);

  if (!policy) {
    return res.status(403).json({
      status: 'Access denied',
      success: false,
      message: `REQUIRED: Policy for role ${role} is not defined`
    });
  }

  const permission = findPermissionForRoute(
    req.originalUrl,
    req.method,
    options.baseUrl,
    policy
  );

  if (!permission) {
    if (typeof options.denyCallback === 'function') {
      return options.denyCallback(res);
    }
    return res.status(403).json(deny(options.customMessage, options.response));
  }

  return checkIfHasAccess(
    req.method,
    res,
    next,
    permission,
    options.customMessage,
    options.response,
    options.denyCallback
  );
}
245956
function(req, res, next, relationship) {
		if(req.fullModel.hasRelationship(relationship)) {
			return next();
		}

		return responseUtils.respond(res, 400); //Malformed syntax or a bad query
	}
1060447
function authorize (req, res, next) {
  var params = req.connectParams
  var responseTypes = params.response_type.trim().split(' ')
  var responseMode = (params.response_mode && params.response_mode.trim()) ||
    (params.response_type === 'code' ||
      params.response_type === 'none') ? '?' : '#'

  // ACCESS GRANTED
  if (params.authorize === 'true') {
    // compose the response
    async.waterfall([

      function includeAccessToken (callback) {
        if (responseTypes.indexOf('token') !== -1) {
          AccessToken.issue(req, function (err, response) {
            if (err) { return callback(err) }
            callback(null, response)
          })

        // initialize an empty response
        } else {
          callback(null, {})
        }
      },

      function includeAuthorizationCode (response, callback) {
        if (responseTypes.indexOf('code') !== -1) {
          AuthorizationCode.insert({
            client_id: req.client._id,
            redirect_uri: params.redirect_uri,
            nonce: params.nonce,
            max_age: parseInt(params.max_age, 10) || req.client.default_max_age,
            user_id: req.user._id,
            scope: req.scope

          }, function (err, ac) {
            if (err) { return callback(err) }
            response.code = ac.code
            callback(null, response)
          })

        // pass through to next
        } else {
          callback(null, response)
        }
      },

      function includeIDToken (response, callback) {
        if (responseTypes.indexOf('id_token') !== -1) {
          var shasum, hash, atHash

          if (response.access_token) {
            shasum = crypto.createHash('sha256')
            shasum.update(response.access_token)
            hash = shasum.digest('hex')
            atHash = hash.slice(0, hash.length / 2)
          }

          var idToken = new IDToken({
            iss: settings.issuer,
            sub: req.user._id,
            aud: req.client._id,
            exp: nowSeconds(response.expires_in),
            nonce: params.nonce,
            at_hash: atHash,
            amr: req.session.amr
          })

          response.id_token = idToken.encode(settings.keys.sig.prv)
        }

        callback(null, response)
      }

    ], function (err, response) {
      if (err) { return next(err) }

      if (params.state) {
        response.state = params.state
      }

      // Set the OP browser state.
      var opbs = req.session.opbs

      // if responseTypes includes id_token or token
      // calculate session_state and add to response
      if (responseTypes.indexOf('id_token') !== -1 ||
        responseTypes.indexOf('token') !== -1) {
        var session = sessionState(req.client, req.client.client_uri, opbs)
        response.session_state = session
      }

      res.redirect(
        params.redirect_uri + responseMode + qs.stringify(response)
      )
    })

  // ACCESS DENIED
  } else {
    res.redirect(params.redirect_uri + '?error=access_denied')
  }
}
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();
}
647195
function (next) {

      var app = connect();

      // application/json
      app.use(bodyParser.json());

      // application/x-www-form-urlencoded
      app.use(bodyParser.urlencoded({ extended: false }));

      // url parameters
      app.use(function (req, res, next) {
        if (!req.query) {
          req.query = ~req.url.indexOf('?')
            ? qs.parse(parseUrl(req).query)
            : {};
        }

        req.params = _.merge({}, req.query, req.body);

        next();
      });

      next(null, app);
    }
479540
function corsPreflight (req, res, next) {
  if (req.method === "OPTIONS") {
    util.debug("OPTIONS %s is a CORS preflight request. Sending HTTP 200 response.", req.path);
    res.send();
  }
  else {
    next();
  }
}
219788
function nextRequest() {
		// If there are no more middleware,
		// then resolve the middleware resolution
		if ( middleware.index == middleware.names.length ) {
			middleware.resolution.resolve();
		}

		// Attempt to invoke the next middleware
		middleware.next();
	}
609838
function (routerMiddelware, req, res, next) {
		var middlewareFilename = routerMiddelware.split('.')[0];
		var middlewareFunction = routerMiddelware.split('.')[1];

		if (!req.pipa) req.pipa = {};

		this.middlewares[middlewareFilename][middlewareFunction](req, res, function (data) {
			_.extend(req.pipa, data); next();
		});
	}
1136549
function(req, res, next){

			res.bootstrap('redirect_url', req.body.redirect || req.query.redirect || route.redirect_url);

			return next();
		}
75424
function (app, next) {
      app.use(function (req, res, next) {
        router.handle(req, res, next);
      });

      next(null, app);
    }
173594
function router(req, resp, next) {
    const routerPath = req.routePath || '';

    const beforeRunMiddleware = (route) => {
      const match = matchRoute(routerPath, req, route);
      if (!match) return false;

      const { params, path: matchPath } = match;

      if (options.params) req.params = { ...options.params, ...params };
      else req.params = params;

      // dynamically set req.routePath for the route
      req.routePath = routerPath + matchPath;
      return true;
    };
    const routeStack = compose(router.routes, { beforeRunMiddleware });

    return routeStack.call(this, req, resp, () => {
      req.routePath = routerPath;// restore routePath
      return next && next();
    });
  }
1327841
function submissions(req, res, next) {
  var params = {
    formId: req.params.id
  };

  logger.debug("Middleware: form submissions: ", {params: params});

  forms.getSubmissions(req.connectionOptions, params, function(err, getSubmissionResponse) {
    if (err) {
      logger.error("Middleware: form submissions ", {error: err});
    }
    getSubmissionResponse = getSubmissionResponse || {};
    req.appformsResultPayload = {
      data: getSubmissionResponse.submissions,
      type: constants.resultTypes.submissions
    };

    next(err);
  });
}
12501
function respond (next) {
  return function sendResult (error, proxyObj) {
    if (error) { return next(error); }

    // TESTING HELPER ONLY
    if (proxyObj.options.shortCircuit) {
      return proxyObj.res.send({
        result: 'proxy-express set to short circuit. If this is not expected, please check your config'
      });
    }

    let proxyError = proxyObjErrors(proxyObj);
    if (proxyError) {
      return next(new Error(proxyError));
    } else if (!(proxyObj.result && proxyObj.result.response)) {
      return next(new Error('Proxy to ' + proxyObj.reqOpts.url + ' failed for an unkown reason'));
    } else {
      proxyObj.res.status(proxyObj.result.response.statusCode || 400).send(proxyObj.result.body);
    }
  };
}
920773
function update(req, res, next) {
  var params = {
    appId: req.params.id || req.body._id,
    forms: req.body.forms || []
  };
  forms.updateAppForms(req.connectionOptions, params, formsResultHandlers(constants.resultTypes.formProjects, req, next));
}