// AuthMiddleware returns a Basic Authentication middleware for a particular user and password.
501387
func AuthMiddleware(requiredUser, requiredPassword, realm string) endpoint.Middleware {
	requiredUserBytes := toHashSlice([]byte(requiredUser))
	requiredPasswordBytes := toHashSlice([]byte(requiredPassword))

	return func(next endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (interface{}, error) {
			auth, ok := ctx.Value(httptransport.ContextKeyRequestAuthorization).(string)
			if !ok {
				return nil, AuthError{realm}
			}

			givenUser, givenPassword, ok := parseBasicAuth(auth)
			if !ok {
				return nil, AuthError{realm}
			}

			givenUserBytes := toHashSlice(givenUser)
			givenPasswordBytes := toHashSlice(givenPassword)

			if subtle.ConstantTimeCompare(givenUserBytes, requiredUserBytes) == 0 ||
				subtle.ConstantTimeCompare(givenPasswordBytes, requiredPasswordBytes) == 0 {
				return nil, AuthError{realm}
			}

			return next(ctx, request)
		}
	}
}
798812
func (c *Client) Middleware(middleware ...neptulon.Middleware) {
	c.conn.Middleware(middleware...)
}
290481
func (s *Server) authMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	reqOrigin := r.Header.Get("Origin")
	s.setAllowedOrigins(rw, reqOrigin)

	defer r.Body.Close()
	if s.auth {
		_, password, ok := r.BasicAuth()
		// If we have valid password or going to tribe/agreements endpoint
		// go to next. tribe/agreements endpoint used for populating
		// snaptel help page when tribe mode is turned on.
		if ok && password == s.authpwd {
			next(rw, r)
		} else {
			v2.Write(401, v2.UnauthError{Code: 401, Message: "Not authorized. Please specify the same password that used to start snapteld. E.g: [snaptel -p plugin list] or [curl http://localhost:8181/v2/plugins -u snap]"}, rw)
		}
	} else {
		next(rw, r)
	}
}
48262
func (api *API) UseMiddleware(middleware ...HandlerFunc) {
	api.middlewares = append(api.middlewares, middleware...)
}
477520
func (mw *JWTMiddleware) MiddlewareFunc(handler rest.HandlerFunc) rest.HandlerFunc {

	if mw.Realm == "" {
		log.Fatal("Realm is required")
	}
	if mw.SigningAlgorithm == "" {
		mw.SigningAlgorithm = "HS256"
	}
	if mw.Key == nil {
		log.Fatal("Key required")
	}
	if mw.Timeout == 0 {
		mw.Timeout = time.Hour
	}
	if mw.Authenticator == nil {
		log.Fatal("Authenticator is required")
	}
	if mw.Authorizator == nil {
		mw.Authorizator = func(userId string, request *rest.Request) bool {
			return true
		}
	}

	return func(writer rest.ResponseWriter, request *rest.Request) { mw.middlewareImpl(writer, request, handler) }
}
1168726
func Middleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	var authToken string = strings.Replace(r.Header.Get("Authorization"), "Bearer ", "", 1)
	claims, err := getClaims(authToken)
	if err == nil || failRequest == false {
		if err == nil {
			context.Set(r, context_key, claims)
		}
		next(rw, r)
	} else {
		rw.WriteHeader(401)
	}
}
847292
func NewMiddleware(limiter *limiter.Limiter, options ...Option) gin.HandlerFunc {
	middleware := &Middleware{
		Limiter:        limiter,
		OnError:        DefaultErrorHandler,
		OnLimitReached: DefaultLimitReachedHandler,
		KeyGetter:      DefaultKeyGetter,
	}

	for _, option := range options {
		option.apply(middleware)
	}

	return func(ctx *gin.Context) {
		middleware.Handle(ctx)
	}
}
1346606
func (r *Router) Middleware(fn interface{}) *Router {
	vfn := reflect.ValueOf(fn)
	validateMiddleware(vfn, r.contextType)
	if vfn.Type().NumIn() == 3 {
		r.middleware = append(r.middleware, &middlewareHandler{Generic: true, GenericMiddleware: fn.(func(ResponseWriter, *Request, NextMiddlewareFunc))})
	} else {
		r.middleware = append(r.middleware, &middlewareHandler{Generic: false, DynamicMiddleware: vfn})
	}

	return r
}
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)
	}
}
522806
func (q *Queue) Middleware(ctx *neptulon.ReqCtx) error {
	q.middlewareChan <- middlewareChan{userID: ctx.Conn.Session.Get("userid").(string), connID: ctx.Conn.ID}
	return ctx.Next()
}
1222729
func (s *Server) AddMiddleware(m Middleware) {
	s.middlewares = append(s.middlewares, m)
}
150652
func (s *SiteConfig) AddMiddleware(m Middleware) {
	s.middleware = append(s.middleware, m)
}
1322735
func (context *Context) Authentication(request *restful.Request) (interface{}, error) {
	return nil, errors.New("Auth is not implemented")
}
692703
func (n NextHTTP) CreateMiddleware(next ContextHandler) ContextHandler {
	return HandlerFunc(func(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
		n(rw, r, http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
			next.ServeHTTPC(ctx, rw, r)
		}))
	})
}
301700
func WrapMiddlewareFromHandler(h HandlerFunc) Middleware {
	return MiddlewareFunc(func(next Handler) Handler {
		return HandlerFunc(func(c Context) error {
			if err := h.Handle(c); err != nil {
				return err
			}
			return next.Handle(c)
		})
	})
}
1274810
func HandleMiddlewares(h http.Handler, adapters ...Middleware) http.Handler {
	// To make the middleware run in the order in which they are specified,
	// we reverse through them in the Middleware function, rather than just
	// ranging over them
	for i := len(adapters) - 1; i >= 0; i-- {
		h = adapters[i](h)
	}
	return h
}
67062
func (b *basicAuthMiddleware) Serve(ctx context.Context) {

	auth, found := b.findAuth(ctx.GetHeader("Authorization"))
	if !found {
		b.askForCredentials(ctx)
		ctx.StopExecution()
		return
		// don't continue to the next handler
	}
	// all ok
	if b.expireEnabled {
		if auth.logged == false {
			auth.expires = time.Now().Add(b.config.Expires)
			auth.logged = true
		}

		if time.Now().After(auth.expires) {
			b.askForCredentials(ctx) // ask for authentication again
			ctx.StopExecution()
			return
		}
	}
	ctx.Next() // continue
}