// Middleware returns a CasbinAuth middleware.
//
// For valid credentials it calls the next handler.
// For missing or invalid credentials, it sends "401 - Unauthorized" response.
352367
func Middleware(ce *casbin.Enforcer) echo.MiddlewareFunc {
	c := DefaultConfig
	c.Enforcer = ce
	return MiddlewareWithConfig(c)
}
880227
func WrapMiddleware(m interface{}) Middleware {
	if h, ok := m.(MiddlewareFunc); ok {
		return h
	}
	if h, ok := m.(MiddlewareFuncd); ok {
		return h
	}
	if h, ok := m.(Middleware); ok {
		return h
	}
	if h, ok := m.(HandlerFunc); ok {
		return WrapMiddlewareFromHandler(h)
	}
	if h, ok := m.(func(Context) error); ok {
		return WrapMiddlewareFromHandler(HandlerFunc(h))
	}
	if h, ok := m.(func(Handler) func(Context) error); ok {
		return MiddlewareFunc(func(next Handler) Handler {
			return HandlerFunc(h(next))
		})
	}
	if h, ok := m.(func(Handler) HandlerFunc); ok {
		return MiddlewareFunc(func(next Handler) Handler {
			return h(next)
		})
	}
	if h, ok := m.(func(HandlerFunc) HandlerFunc); ok {
		return MiddlewareFunc(func(next Handler) Handler {
			return h(next.Handle)
		})
	}
	if h, ok := m.(func(Handler) Handler); ok {
		return MiddlewareFunc(h)
	}
	if h, ok := m.(func(func(Context) error) func(Context) error); ok {
		return MiddlewareFunc(func(next Handler) Handler {
			return HandlerFunc(h(next.Handle))
		})
	}
	if v, ok := m.(http.Handler); ok {
		return WrapMiddlewareFromStdHandler(v)
	}
	if v, ok := m.(func(http.ResponseWriter, *http.Request)); ok {
		return WrapMiddlewareFromStdHandleFunc(v)
	}
	if v, ok := m.(func(http.ResponseWriter, *http.Request) error); ok {
		return WrapMiddlewareFromStdHandleFuncd(v)
	}
	panic(`unknown middleware`)
}
32705
func (s *State) Middleware(c *router.Context, next router.Handler) {
	state, settings := s.checkSettings(c.Context)
	if settings.Enabled {
		started := clock.Now(c.Context)
		req := c.Request
		userAgent, ok := req.Header["User-Agent"]
		if !ok || len(userAgent) == 0 {
			userAgent = []string{"Unknown"}
		}
		ctx := c.Context
		contentLength := c.Request.ContentLength
		nrw := newResponseWriter(c.Writer)
		c.Writer = nrw
		defer func() {
			dur := clock.Now(ctx).Sub(started)
			metric.UpdateServerMetrics(ctx, c.HandlerPath, nrw.Status(), dur,
				contentLength, nrw.Size(), userAgent[0])
		}()
		next(c)
		s.flushIfNeeded(ctx, req, state, settings)
	} else {
		next(c)
	}
}
176537
func (m *middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ctx, err := m.authenticate(r)
	if err == nil {
		if ctx != nil && ctx != r.Context() {
			r = r.WithContext(ctx)
		}
		m.next.ServeHTTP(w, r)
	} else {
		SendError(w, err)
	}
}
796468
func MiddlewareFunc(tr opentracing.Tracer, h http.HandlerFunc, options ...MWOption) http.HandlerFunc {
	opts := mwOptions{
		opNameFunc: func(r *http.Request) string {
			return "HTTP " + r.Method
		},
		spanFilter:   func(r *http.Request) bool { return true },
		spanObserver: func(span opentracing.Span, r *http.Request) {},
		urlTagFunc: func(u *url.URL) string {
			return u.String()
		},
	}
	for _, opt := range options {
		opt(&opts)
	}
	fn := func(w http.ResponseWriter, r *http.Request) {
		if !opts.spanFilter(r) {
			h(w, r)
			return
		}
		ctx, _ := tr.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(r.Header))
		sp := tr.StartSpan(opts.opNameFunc(r), ext.RPCServerOption(ctx))
		ext.HTTPMethod.Set(sp, r.Method)
		ext.HTTPUrl.Set(sp, opts.urlTagFunc(r.URL))
		opts.spanObserver(sp, r)

		// set component name, use "net/http" if caller does not specify
		componentName := opts.componentName
		if componentName == "" {
			componentName = defaultComponentName
		}
		ext.Component.Set(sp, componentName)

		sct := &statusCodeTracker{w, 200}
		r = r.WithContext(opentracing.ContextWithSpan(r.Context(), sp))

		h(sct.wrappedResponseWriter(), r)

		ext.HTTPStatusCode.Set(sp, uint16(sct.status))
		if sct.status >= http.StatusInternalServerError {
			ext.Error.Set(sp, true)
		}
		sp.Finish()
	}
	return http.HandlerFunc(fn)
}
598587
func HandleCredentialError(err error, ctx context.ProviderCallContext) {
	common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
}
2675
func chainMiddleware(el *list.Element) http.HandlerFunc {
	// The last element of the middlewares chain is nil.
	if el == nil {
		return func(rw http.ResponseWriter, r *http.Request) {}
	}
	return func(rw http.ResponseWriter, r *http.Request) {
		el.Value.(Middleware).ServeHTTP(rw, r, chainMiddleware(el.Next()))
	}
}
867444
func LoggingMiddleware(out io.Writer) MiddlewareHandlerFunc {
	return func(next HandlerFunc) HandlerFunc {
		fn := func(ctx *Context) {
			start := time.Now()
			path := ctx.Request.URL.Path

			next(ctx)

			end := time.Now()
			latency := end.Sub(start)

			clientIP := ctx.ClientIP()
			method := ctx.Request.Method
			statusCode := ctx.statusCode
			statusColor := colorForStatus(statusCode)
			methodColor := colorForMethod(method)

			fmt.Fprintf(out, "%v |%s %3d %s| %13v | %s |%s  %s %-7s %s\n",
				end.Format("2006/01/02 - 15:04:05"),
				statusColor, statusCode, reset,
				latency,
				clientIP,
				methodColor, reset, method,
				path,
			)
		}
		return fn
	}
}
382071
func MiddlewareTimeout(timeout time.Duration) Middleware {
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
			handleTimeout(timeout, rw, func() { h.ServeHTTP(rw, r) })
		})
	}
}
782131
func CORS(config CORSConfig) Middleware {
	if config.Skipper == nil {
		config.Skipper = DefaultSkipper
	}

	allowMethods := strings.Join(config.AllowMethods, ",")
	allowHeaders := strings.Join(config.AllowHeaders, ",")
	exposeHeaders := strings.Join(config.ExposeHeaders, ",")

	maxAge := ""
	if config.MaxAge > time.Duration(0) {
		maxAge = strconv.FormatInt(int64(config.MaxAge/time.Second), 10)
	}

	allowOrigins := make(map[string]struct{})
	for _, v := range config.AllowOrigins {
		allowOrigins[v] = struct{}{}
	}

	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if config.Skipper(r) {
				h.ServeHTTP(w, r)
				return
			}

			if origin := r.Header.Get("Origin"); origin != "" {
				h := w.Header()

				if config.AllowAllOrigins {
					h.Set("Access-Control-Allow-Origin", "*")
				} else if _, ok := allowOrigins[origin]; ok {
					h.Set("Access-Control-Allow-Origin", origin)
				} else {
					w.WriteHeader(http.StatusForbidden)
					return
				}

				if config.AllowCredentials {
					h.Set("Access-Control-Allow-Credentials", "true")
				}

				if r.Method == http.MethodOptions {
					if allowMethods != "" {
						h.Set("Access-Control-Allow-Methods", allowMethods)
					}
					if allowHeaders != "" {
						h.Set("Access-Control-Allow-Headers", allowHeaders)
					}
					if maxAge != "" {
						h.Set("Access-Control-Max-Age", maxAge)
					}

					if !config.AllowAllOrigins {
						h.Add("Vary", "Origin")
					}

					h.Add("Vary", "Access-Control-Request-Method")
					h.Add("Vary", "Access-Control-Request-Headers")

					w.WriteHeader(http.StatusNoContent)
					return
				}

				if exposeHeaders != "" {
					h.Set("Access-Control-Expose-Headers", exposeHeaders)
				}

				if !config.AllowAllOrigins {
					h.Set("Vary", "Origin")
				}
			}
			h.ServeHTTP(w, r)
		})
	}
}
1322341
func WrapMiddleware(m func(http.Handler) http.Handler) MiddlewareFunc {
	return func(next HandlerFunc) HandlerFunc {
		return func(c Context) (err error) {
			m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				c.SetRequest(r)
				err = next(c)
			})).ServeHTTP(c.Response(), c.Request())
			return
		}
	}
}
114945
func (m *Manager) Middleware() func(http.Handler) http.Handler {
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			rm := &scopedManager{
				Manager:        m,
				ResponseWriter: w,
				r:              r,
				storage:        make(map[string]*Session),
			}

			ctx := context.WithValue(r.Context(), scopedManagerKey{}, rm)
			h.ServeHTTP(rm, r.WithContext(ctx))

			rm.MustSaveAll()
		})
	}
}
18685
func (app *App) CORSMiddleware(domains ...string) func(*Context) {
	return func(ctx *Context) {
		ctx.CORS(domains...)
	}
}
710208
func middleware(event *bugsnag.Event, config *bugsnag.Configuration) error {
	for _, datum := range event.RawData {
		if controller, ok := datum.(*revel.Controller); ok {
			// make the request visible to the builtin HttpMiddleware
			event.Context = controller.Action
			event.MetaData.AddStruct("Session", controller.Session)
		}
	}

	return nil
}
6983
func (api *API) middlewareChain(c APIContexter, w http.ResponseWriter, r *http.Request) {
	for _, middleware := range api.middlewares {
		middleware(c, w, r)
	}
}
633646
func Middleware(config Config) func(http.Handler) http.Handler {
	return New(config).Middleware()
}
1040018
func (r *route) Middlewares(
	middlewares ...types.Middleware) types.Route {
	r.middlewares = append(r.middlewares, middlewares...)
	return r
}