Middleware to make sure the method is valid.
@param {Request} req
@param {Response} res
@param {function} next
339238
function validMethod(req, res, next) {
    if (httpMethods.indexOf(req.method) === -1) {
        res.sendStatus(405);
    } else {
        next();
    }
}
740171
function callEntityMethod(req, res, next) {
  var payload = req.payload;
  var method = req.serversideMethod;

  if (req.hasCallback) {

    debug('Transforming callback function');
    payload[req.clientCallbackIndex] = function(err) {
      if (err) {
        return next(err);
      }

      var values = Array.prototype.slice.call(arguments).slice(1);

      debug('Callback function called. Values are:', values);

      res.entityResponse = values;

      next();
    };
  }

  debug('Calling ' + req.path + ' with arguments:', payload);

  var context = {
    req: req,
    xhr: true,
    setCookie: res.cookie.bind(res),
    clearCookie: res.clearCookie.bind(res)
  };

  var ret;

  // Calls the requested serverside method.
  // Applies the payload, and provides a context for validation purposes.
  // Caches errors in the method's scope, and sends it to the next error handler.
  try {
    ret = method.apply(context, payload);
  } catch(err) {
    return next(err);
  }

  if (util.isPromise(ret)) {
    ret.then(function(resolved) {
      res.entityResponse = [resolved];
      next();
    })
    .catch(function(err) {
      next(err);
    });
  }

  // If the request is not expecting the response from the entity,
  // send a generic 'Ok' response.
  else if (!req.hasCallback) {
    res.entityResponse = [ret];
    debug('Not asynchronous. Returning value: ', res.entityResponse);
    next();
  }
}
1121448
function callResponseMiddleware(err, res1, res2) {
        i -= 1;
        if (i >= 0) {
            var next = self.middlewares[i].response;
            if (typeof next === 'function') {
                next(req, err, res1, res2, callResponseMiddleware);
            } else {
                // skip this middleware if it doesn't implement response
                callResponseMiddleware(err, res1, res2);
            }
        } else {
            callback(req, err, res1, res2);
        }
    }
261448
function(request, response, next){
		if (!utils.Misc.isNullOrUndefined(request.user)) {
			next();
		}
		else {
			var error = new Error(errors['213']);
			response.end(utils.Misc.createResponse(null, error, 213));
		}
	}
88574
function (req, res, next) {
        var hostId = req.miajs.route.hostId;
        var url = req.miajs.route.url;
        var prefix = req.miajs.route.prefix;
        var method = req.miajs.route.method;
        var group = req.miajs.route.group;
        var version = req.miajs.route.version;
        var registeredServices = Shared.registeredServices();
        var errors = [];
        var routeFound = false;
        req.miajs = req.miajs || {};

        //console.log('checkPreconditions: url: ' + url + ', method: ' + method + ', body: ' + JSON.stringify(req.body));

        for (var index in registeredServices) {

            if (registeredServices[index].group == group
                && registeredServices[index].hostId == hostId
                && registeredServices[index].version == version
                && registeredServices[index].prefix == prefix
                && registeredServices[index].method == method
                && registeredServices[index].url == url
            ) {
                routeFound = true;
                if (registeredServices[index].preconditions) {
                    var service = registeredServices[index];
                    var preconditionsList = service.preconditions;
                    var qfunctions = [];

                    for (var cIndex in preconditionsList) {
                        qfunctions.push(_checkControllerConditions(req, preconditionsList[cIndex]));
                    }

                    Q.all(qfunctions).then(function (results) {

                        req.miajs.commonValidatedParameters = [];

                        results.forEach(function (result) {
                            if (result) {
                                if (result.validatedData) {
                                    req.miajs.commonValidatedParameters.push(result.validatedData);
                                }

                                var controllerErrors = result.errors;
                                controllerErrors.forEach(function (error) {

                                    var inList = false;
                                    // Check for error duplicates
                                    for (var eIndex in errors) {
                                        if (errors[eIndex].code == error.code && errors[eIndex].id == error.id && errors[eIndex].in == error.in) {
                                            inList = true;
                                        }
                                    }

                                    if (inList == false) {
                                        errors.push(error);
                                    }
                                });
                            }
                        });

                    }).then(function () {
                        if (!_.isEmpty(errors)) {
                            next({'status': 400, err: errors})
                            return;
                        }
                        else {
                            next();
                            return;
                        }
                    }).catch(function (err) {
                        next({'status': 400, err: err});
                        return;
                    });
                }
                else {
                    next();
                    return;
                }
            }
        }

        if (routeFound == false) {
            Logger.error('Can not find controller file in preconditionsCheck to perform parameter validation. Request canceled due to security reasons');
            next({status: 500});
            return;
        }
    }
1103202
function catchClientError(req, res, next) {
  const { end } = res;

  res.end = function() {
    // console.log(`Catch client response : ${req.url} ${res.statusCode}`);
    const errorRoute = Route
      .routes('err')
      .filter((obj) => {
        return obj.extra.status === res.statusCode && obj.route !== req.url;
      });

    if(errorRoute.length > 0 && !isRedirect) {
      return redirect(errorRoute[0], req, res, next);
    }

    isRedirect = false;
    end.apply(res, arguments);
  };

  next();
}
1041759
function requestHandler(req, res, next) {
  const params = req && req.params;
  const start = Date.now();
  let source;
  let opts;

  return Promise.try(() => {
    source = core.getPublicSource(params.src);

    if (!_.contains(source.formats, params.format)) {
      throw new Err('Format %s is not known', params.format).metrics('err.req.format');
    }

    params.z = core.validateZoom(params.z, source);
    params.scale = core.validateScale(params.scale, source);

    params.x = checkType.strToInt(params.x);
    params.y = checkType.strToInt(params.y);
    if (
      !qidx.isValidCoordinate(params.x, params.z) || !qidx.isValidCoordinate(params.y, params.z)
    ) {
      throw new Err('x,y coordinates are not valid, or not allowed for this zoom').metrics('err.req.coords');
    }

    opts = {
      z: params.z,
      x: params.x,
      y: params.y,
    };
    if (params.format !== 'pbf') {
      // Ensure that PNGs are not 32bit
      // TODO: this should be source-configurable
      opts.format = params.format === 'png' ? 'png8:m=h' : params.format;
      if (params.scale) {
        opts.scale = params.scale;
      }
    }
    if (req.query && req.query.lang) {
      if (!langCodeRe.test(req.query.lang)) {
        throw new Err('lang param is not valid').metrics('err.req.lang');
      }
      opts.lang = req.query.lang;
    }

    // fixme: Force all tiles to be treated as vector
    opts.treatAsVector = true;

    return source.getHandler().getAsync(opts);
  }).then((result) => {
    let mx;

    core.setResponseHeaders(res, source, result.headers);

    if (params.format === 'json') {
      // Allow JSON to be shortened to simplify debugging
      res.json(filterJson(req.query, result.data));
    } else {
      res.send(result.data);
    }

    mx = util.format('req.%s.%s.%s', params.src, params.z, params.format);
    if (params.scale) {
      // replace '.' with ',' -- otherwise grafana treats it as a divider
      mx += `.${params.scale.toString().replace('.', ',')}`;
    }
    core.metrics.endTiming(mx, start);
  }).catch(err => core.reportRequestError(err, res)).catch(next);
}
326560
function validateAuthorizationParams (req, res, next) {
  var params = req.connectParams

  // missing response type
  if (!params.response_type || !params.response_type.trim()) {
    return next(new AuthorizationError({
      error: 'invalid_request',
      error_description: 'Missing response type',
      redirect_uri: params.redirect_uri,
      statusCode: 302
    }))
  }

  var responseTypes = params.response_type.trim().split(' ')

  // Check that
  // - All response_types are valid
  // - If `none` response_type is given, that it is the only response_type
  var isValidResponseType = responseTypes.indexOf('none') !== -1
    ? responseTypes.length === 1
    : responseTypes.every(
      function (responseType) {
        return validResponseTypes.indexOf(responseType) !== -1
      }
    )

  // invalid response type
  if (!isValidResponseType) {
    return next(new AuthorizationError({
      error: 'unsupported_response_type',
      error_description: 'Unsupported response type',
      redirect_uri: params.redirect_uri,
      statusCode: 302
    }))
  }

  // Check that there is at least one defined set of response_types that are
  // supported together in both the settings and on the client.
  //
  // For example, if the settings allow 'code', 'id_token token', and
  // 'code id_token token', then:
  //
  // - 'code' will pass
  // - 'id_token token' will pass
  // - 'code token id_token' will pass
  // - 'token' will NOT pass
  // - 'id_token code' will NOT pass

  // Get the registered response_type sets off the client
  var registeredResponseTypeSets =

    // If the client exists and has response_types defined
    (req.client && Array.isArray(req.client.response_types))

      // Return an array of response_type sets
      ? req.client.response_types.map(function (responseTypeString) {
        return responseTypeString.trim().split(' ')
      })
      // Otherwise, return an array with the default set, [ 'code' ]
      : [ [ 'code' ] ]

  // In the array of response_types in the settings...
  var isSupportedResponseType = settings.response_types_supported

    // check each set until we find one that satisfies the following:
    .some(function (responseTypeString) {
      var responseTypeSet = responseTypeString.split(' ')

      // if there is at least one response_type set registered on the client...
      if (registeredResponseTypeSets.some(function (regResTypeSet) {
        var indices = []

        // that has the same number of response_types in it...
        return regResTypeSet.length === responseTypeSet.length &&
          regResTypeSet.every(function (responseType) {
            var index = responseTypeSet.indexOf(responseType)

            // of which there are no duplicates...
            if (indices.indexOf(index) !== -1) {
              return false
            }
            indices.push(index)

            // and where every response_type value exists in the response_type
            // set from the settings...
            return responseTypeSet.indexOf(responseType) !== -1
          })

      // then we have found a response_type set that is both permitted by the
      // server settings and registered for the current client
      })) {
        var indices = []

        // then we check to see that the response_type set received in the auth
        // request also has the same number of response_types...
        return responseTypes.length === responseTypeSet.length &&
          responseTypes.every(function (responseType) {
            var index = responseTypeSet.indexOf(responseType)

            // that there are no duplicates...
            if (indices.indexOf(index) !== -1) {
              return false
            }
            indices.push(index)

            // and that every response_type value exists in the response_type
            // set that we verified is both registered by the client and
            // permitted by the settings

            // if this is true, then we found a match, and the response_type
            // requested is valid, permitted, and registered
            return responseTypeSet.indexOf(responseType) !== -1
          })
      } else {
        // otherwise, continue on to the next response_type in the settings
        return false
      }
    })

  // unsupported response type
  if (!isSupportedResponseType) {
    return next(new AuthorizationError({
      error: 'unsupported_response_type',
      error_description: 'Unsupported response type',
      redirect_uri: params.redirect_uri,
      statusCode: 302
    }))
  }

  // unsupported response mode
  if (params.response_mode && params.response_mode.trim() &&
    validResponseModes.indexOf(params.response_mode.trim()) === -1) {
    return next(new AuthorizationError({
      error: 'unsupported_response_mode',
      error_description: 'Unsupported response mode',
      redirect_uri: params.redirect_uri,
      statusCode: 302
    }))
  }

  // missing scope
  if (!params.scope) {
    return next(new AuthorizationError({
      error: 'invalid_scope',
      error_description: 'Missing scope',
      redirect_uri: params.redirect_uri,
      statusCode: 302
    }))
  }

  // missing openid scope
  if (params.scope.indexOf('openid') === -1) {
    return next(new AuthorizationError({
      error: 'invalid_scope',
      error_description: 'Missing openid scope',
      redirect_uri: params.redirect_uri,
      statusCode: 302
    }))
  }

  // missing nonce
  if (!params.nonce && requiresNonce(responseTypes)) {
    return next(new AuthorizationError({
      error: 'invalid_request',
      error_description: 'Missing nonce',
      redirect_uri: params.redirect_uri,
      statusCode: 302
    }))
  }

  next()
}
517273
function validate(res, result) {
  if (!result) return true;

  var err = new Error('Validation failed');
  try {
    err.errors = result.errors();
  } catch (err) {
    err.errors = [result.validation];
  }
  err.expose = true;
  err.statusCode = 400;
  err.toJSON = function() {
    return {
      message: this.message,
      errors: this.errors,
    };
  };

  res.sf.reply(err);
}
1358273
function(req, res, next) {
                if (req.headers.accept && req.headers.accept.startsWith('text/html')) {
                  req.url = '/index.html'; // eslint-disable-line no-param-reassign
                }
                next();
              }
158480
function handleLogin(req, res, next) {
		var p = new Promise(function (resolve, reject) {
			const loginHandler = function (err, user, info) {
				if (err) {
					debug(`Error during user login`, err);
					return reject(err);
				}
				if (!user) {
					debug(`Login user not found or invalid credentials`, info);
					reject(new restifyErrors.InvalidCredentialsError("Incorrect username or password"));
				} else {
					const data = {
						'success': true,
						'token': req.locals.basic_login_token
					};
					resolve(data);
				}
			};

			debug(`Handling user login`);
			passport.authenticate('basic', {
				session: false
			}, loginHandler)(req, res);
		}).then(function (data) {
			res.json(data);
			next();
		}).catch(function (err) {
			debug(`Error during login request.`, err);
			next(err);
		});
	}
884006
function Router(req, res, next) {
        const server = this;
        const state = {
            method: req.method.toUpperCase(),
            params: {},
            routes: routes.concat(),
            routeUnhandled: true,
            server: server,
        };
        run(state, req, res, err => {
            req.params = {};
            if (state.routeUnhandled) req.log('unhandled', 'Router had no matching paths');
            next(err);
        });
    }
720338
function handleVerify(req, res, next) {
		var p = new Promise(function (resolve, reject) {
			const currentToken = req.params.token || false;
			if (!currentToken || currentToken == 'missing') {
				debug(`Verify request, token is missing.`);
				return reject(new restifyErrors.BadRequestError("Verify token is missing"));
			}

			const postVerifyHandler = function (err, user, info) {
				if (err) {
					debug(`Error handling verify request.`, err);
					return reject(new restifyErrors.InternalError(err));
				}
				// The API doesn't store any state in a session!
				req.login(user, {
					'session': false
				}, function (err) {
					if (err) {
						debug(`Login failed during verify request.`, err);
						return reject(new restifyErrors.InternalError("Failed logging in verified user"));
					}
					debug(`User is verified and logged in.`);
					var data = {
						'success': true,
						'token': req.locals.basic_login_token
					};
					resolve(data);
				});
			};

			passport.authenticate('local-verify', postVerifyHandler)(req, res);
		}).then(function (data) {
			res.json(data);
			next();
		}).catch(function (err) {
			debug(`Error during verify request.`, err);
			next(err);
		});
	}
1090994
function verifyProjectIdDoesNotExist(req, res, next) {
  var projectId = req.body.id;
  var dataStore = req.app.dataStore;

  // Check for an existing project REST resource - /projects/{projectId}
  var resource = new swagger.Resource('/projects', projectId, null);
  dataStore.get(resource, function(err, resource) {
    if (resource) {
      // The ID already exists, so send an HTTP 409 (Conflict)
      res.sendStatus(409);
    }
    else {
      next();
    }
  });
}
969021
function middleware(doIt, req, res) {
  const originalEnd = res.end;

  return new Promise(resolve => {
    res.end = function end(...args) {
      originalEnd.apply(this, args);
      resolve(0);
    };
    doIt(req, res, () => {
      resolve(1);
    });
  });
}
245956
function(req, res, next, relationship) {
		if(req.fullModel.hasRelationship(relationship)) {
			return next();
		}

		return responseUtils.respond(res, 400); //Malformed syntax or a bad query
	}
1122899
function ( req, res, next ) {

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

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

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

    next();

}