Grape middleware methods


 Before do.
332332
def before
      return if WineBouncer.configuration.disable_block.call

      set_auth_strategy(WineBouncer.configuration.auth_strategy)
      auth_strategy.api_context = context
      #extend the context with auth methods.
      context.extend(WineBouncer::AuthMethods)
      context.protected_endpoint = endpoint_protected?
      return unless context.protected_endpoint?
      self.doorkeeper_request = env # set request for later use.
      doorkeeper_authorize!(*auth_scopes)
      context.doorkeeper_access_token = doorkeeper_token
    end
277656
public void beforeDeploy(@Observes(precedence = CitrusExtensionConstants.INSTANCE_PRECEDENCE) BeforeDeploy event) {
        try {
            if (!event.getDeployment().testable()) {
                log.info("Producing Citrus framework instance");
                citrusInstance.set(Citrus.newInstance(configurationInstance.get().getConfigurationClass()));
            }
        } catch (Exception e) {
            log.error(CitrusExtensionConstants.CITRUS_EXTENSION_ERROR, e);
            throw e;
        }
    }
30172
function compose(middlewares, path) {
    if (!Array.isArray(middlewares)) {
        throw new Error(`middlewares ${JSON.stringify(middlewares)} should be an Array of functions.`);
    }
    if (middlewares.length) {
        for (const fn of middlewares) {
            if (typeof fn !== 'function') {
                throw new Error(`middleware ${path} - ${JSON.stringify(fn)} should be a function, ignored.`);
            }
        }
    }
    return (req, res, next) => {
        (function iterate(i, max) {
            if (i === max) {
                return next();
            }
            middlewares[i](req, res, iterate.bind(this, i + 1, max));
        })(0, middlewares.length);
    }
}
1111531
def pre_execute(self, execution, context):
        """"""
        path = self._fspath
        if path:
            path = path.format(
                benchmark=context.benchmark,
                api=execution['category'],
                **execution.get('metas', {})
            )
            if self.clean_path:
                shutil.rmtree(path, ignore_errors=True)
            if execution['metas']['file_mode'] == 'onefile':
                path = osp.dirname(path)
            if not osp.exists(path):
                os.makedirs(path)
1342282
public function before(... $middlewares)
  {
    foreach ($middlewares as $middleware) {
      $this->currentContext->addMiddleware($middleware, RoutingContext::BEFORE);
    }

    return $this;
  }
773780
protected function beforeAction()
    {
        if (Lb::app()->isRest()) {
            $restConfig = Lb::app()->getRest()[$this->controller_id][$this->action_id];
            list($requestMethod, $authType) = $restConfig;

            $response = $this->response;

            //Set Auth Middleware
            $this->middleware['authMiddleware']['params'] = [
                'rest_config' => $restConfig,
                'request' => $this->request,
            ];
            $this->middleware['authMiddleware']['failureCallback'] = function () use ($response) {
                $response->response_unauthorized(401);
            };

            //Set Request Method Filter
            $this->middleware['requestMethodFilter']['params'] = [
                'request_method' => $requestMethod,
                'request' => $this->request,
            ];
            $this->middleware['requestMethodFilter']['failureCallback'] = function () use ($response) {
                $response->response_invalid_request(403);
            };

            //Set Rate Limit Filter
            if (array_key_exists($this->action_id, $this->rateLimitActions)) {
                $this->middleware['rateLimitFilter']['params'] = $this->rateLimitActions[$this->action_id];
                $this->middleware['rateLimitFilter']['failureCallback'] = function () use ($response) {
                    $response->response_invalid_request(403);
                };
            }
        } else {
            $this->response_invalid_request(403);
        }

        parent::beforeAction();
    }
80991
def pre_fork(self, process_manager):
        '''
        
        '''
        salt.transport.mixins.auth.AESReqServerMixin.pre_fork(self, process_manager)
        if USE_LOAD_BALANCER:
            self.socket_queue = multiprocessing.Queue()
            process_manager.add_process(
                LoadBalancerServer, args=(self.opts, self.socket_queue)
            )
        elif not salt.utils.platform.is_windows():
            self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            _set_tcp_keepalive(self._socket, self.opts)
            self._socket.setblocking(0)
            self._socket.bind((self.opts['interface'], int(self.opts['ret_port'])))
820060
function (method, endpoint, routerMiddelware) {
		var self = this;

		if (typeof routerMiddelware == 'object'){
			this.app[method](endpoint, function (req, res, next) {
				var middlewareFunction = []
				routerMiddelware.forEach(function (m) {
					middlewareFunction.push(function (cb) {
						self.__exec__middlewares(m, req, res, cb);
					});
				});

				async.waterfall(middlewareFunction);
			});
		} else {
			this.app[method](endpoint, function (req, res, next) {
				self.__exec__middleware(routerMiddelware)(req, res, next);
			});
		}
	}
231018
function callMiddleware(entry, middleware, callback) {
  var index = 0;

  function next(entry, acc) {
    var layer = middleware[index++];
    if (!layer) {
      return callback(entry, acc);
    }

    var accumulator = acc || {};
    layer(entry, accumulator, next);
  }

  next(entry);
}
474320
function middleware(req, res, next) {
  req.security.csrf.exclude = true;
  next();
}
1360965
def _call_one_middleware(self, middleware):
        '''  '''
        args = {}
        for arg in middleware['args']:
            if hasattr(self, arg):
                # same as eval() but safer for arbitrary code execution
                args[arg] = reduce(getattr, arg.split('.'), self)
        self.logger.debug('calling middleware event {}'
                          .format(middleware['name']))
        middleware['call'](**args)
441238
def log_middleware(store):
    """"""
    def wrapper(next_):
        def log_dispatch(action):
            print('Dispatch Action:', action)
            return next_(action)
        return log_dispatch
    return wrapper
345357
function compose () {
  // the function required by the server
  function middlewareF (req, res, end) {
    var index = 0

    // inject stats middleware
    if (middlewareF.options && middlewareF.options.stats) {
      middlewareF.stack = middlewareF.stack.map(function (mw) {
        var fn
        if (typeof mw === 'object') {
          var key = Object.keys(mw)[0]
          if (!mw[key].stats) {
            fn = {}
            fn[key] = middlewareF.options.stats(mw[key])
          }
        } else {
          if (!mw.stats) {
            fn = middlewareF.options.stats(mw)
          }
        }
        return fn
      })
    }

    // looping over all middleware functions defined by stack
    ;(function next (err) {
      var arity
      var middleware = middlewareF.stack[index++] // obtain the current middleware from the stack

      if (!middleware) {
        // we are at the end of the stack
        end && end(err)
        return
      } else {
        // extract middleware from object
        if (typeof (middleware) === 'object') {
          var name = Object.keys(middleware)[0]
          if (typeof (middleware[name]) === 'function') {
            middleware = middleware[name]
          } else {
            middleware = function (req, res, next) {
              next(new Error('missing middleware'))
            }
          }
        }

        try {
          arity = middleware.length // number of arguments function middleware requires
          // handle errors
          if (err) {
            // If the middleware function contains 4 arguments than this will act as an "error trap"
            if (arity === 4) {
              middleware(err, req, res, function (err) {
                nextTick(next, err)
              })
            } else {
              // otherwise check the next middleware
              next(err)
            }
          } else if (arity < 4) {
            // process non "error trap" stack
            middleware(req, res, function (err) {
              nextTick(next, err)
            })
          } else {
            // loop over "error traps" if no error `err` is set.
            next()
          }
        } catch (e) {
          next(e)
        }
      }
    })()
  }

  middlewareF.stack = []
  middlewareF.options = compose.options || {}

  ;[].slice.call(arguments).forEach(function (a) {
    middlewareF.stack = middlewareF.stack.concat(compose.decompose(a))
  })

  // extends
  ;[ 'before', 'after', 'replace', 'remove', 'push', 'unshift', 'clone' ].forEach(function (p) {
    middlewareF[p] = compose[p]
  })

  // inject stats middleware
  if (compose.options.stats) {
    middlewareF.options = {}
    middlewareF.options.stats = compose.options.stats
  }

  return middlewareF
}
771241
def and_before_calling_original
      self.and_wrap_original do |m, *args, &block|
        yield *args
        m.call(*args, &block)
      end
    end
850240
def pre_request(self):
        
        middleware = sort_by_priority(self)
        return tuple(m.pre_request for m in middleware if hasattr(m, 'pre_request'))
1007089
def before_processing(eng, objects):
        """"""
        super(InvenioProcessingFactory, InvenioProcessingFactory)\
            .before_processing(eng, objects)
        eng.save(WorkflowStatus.RUNNING)
        db.session.commit()
1334851
function createDefaultMiddleware(connect, options) {
    var middlewares = [];
    if (!Array.isArray(options.base)) {
      options.base = [options.base];
    }
    var directory = options.directory || options.base[options.base.length - 1];
    options.base.forEach(function(base) {
      // Serve static files.
      middlewares.push(connect.static(base));
    });
    // Make directory browse-able.
    middlewares.push(connect.directory(directory));
    return middlewares;
  }