// BasicAuthFunc returns a Handler that authenticates via Basic Auth using the provided function.
// The function should return true for a valid username/password combination.
327925
func BasicAuthFunc(authfn func(string, string, *http.Request) bool) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
			auth := req.Header.Get("Authorization")
			if len(auth) < 6 || auth[:6] != "Basic " {
				unauthorized(res)
				return
			}
			b, err := base64.StdEncoding.DecodeString(auth[6:])
			if err != nil {
				unauthorized(res)
				return
			}
			tokens := strings.SplitN(string(b), ":", 2)
			if len(tokens) != 2 || !authfn(tokens[0], tokens[1], req) {
				unauthorized(res)
				return
			}
			next.ServeHTTP(res, req)
		})
	}
}
346313
func BasicConnect(realm string, f func(user, passwd string) bool) goproxy.HttpsHandler {
	return goproxy.FuncHttpsHandler(func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
		if !auth(ctx.Req, f) {
			ctx.Resp = BasicUnauthorized(ctx.Req, realm)
			return goproxy.RejectConnect, host
		}
		return goproxy.OkConnect, host
	})
}
900673
func (r *Request) BasicAuth(username, password string) *Request {
	r.Header.Set("Authorization", "Basic "+basicAuth(username, password))
	return r
}
330178
func BasicAuthToken(username, password string) (*oauth2.Token, error) {
	basicToken, err := RFC7617UserPass(username, password)
	if err != nil {
		return nil, err
	}

	return &oauth2.Token{
		AccessToken: basicToken,
		TokenType:   BasicPrefix,
		Expiry:      timeutil.TimeRFC3339Zero()}, nil
}
1083176
func (b *basicAuth) requestAuth(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm=%q`, b.opts.Realm))
	b.opts.UnauthorizedHandler.ServeHTTP(w, r)
}
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) }
}
25695
func (r *Router) HandleFunc(path string, h http.HandlerFunc, ms ...Method) {
	r.Route(
		path,
		func(w http.ResponseWriter, req *Request) error {
			h(w, req.Request)
			return nil
		},
		ms...,
	)
}
62704
func NewBasicAuthFromString(creds string) (*BasicAuth, error) {
	ba := NewBasicAuth()
	for _, u := range strings.Split(creds, "|") {
		uparts := strings.SplitN(u, ":", 2)
		if len(uparts) != 2 || len(uparts[0]) == 0 || len(uparts[1]) == 0 {
			return ba, fmt.Errorf("Unable to create credentials from '%s'", u)
		}

		ba.AddPrincipal(uparts[0], uparts[1])
	}
	return ba, nil
}
762551
func (r *Route) HandlerFunc(f func(context.Context, http.ResponseWriter, *http.Request) error) *Route {
	return r.Handler(HandlerFunc(f))
}
1067119
func readBasicAuth() *basicAuth {
	var auth basicAuth
	httpAuth := os.Getenv("HTTP_AUTH")
	switch {
	case *authFileF != "":
		bytes, err := ioutil.ReadFile(*authFileF)
		if err != nil {
			log.Fatalf("cannot read auth file %q: %s", *authFileF, err)
		}
		if err = yaml.Unmarshal(bytes, &auth); err != nil {
			log.Fatalf("cannot parse auth file %q: %s", *authFileF, err)
		}
	case httpAuth != "":
		data := strings.SplitN(httpAuth, ":", 2)
		if len(data) != 2 || data[0] == "" || data[1] == "" {
			log.Fatalf("HTTP_AUTH should be formatted as user:password")
		}
		auth.Username = data[0]
		auth.Password = data[1]
	default:
		// that's fine, return empty one below
	}

	return &auth
}
1076241
func BasicAuthRealmCtx(realm string, authenticate UserPassAuthenticationCtx) runtime.Authenticator {
	if realm == "" {
		realm = DefaultRealmName
	}

	return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
		if usr, pass, ok := r.BasicAuth(); ok {
			ctx, p, err := authenticate(r.Context(), usr, pass)
			if err != nil {
				ctx = context.WithValue(ctx, failedBasicAuth, realm)
			}
			*r = *r.WithContext(ctx)
			return true, p, err
		}
		*r = *r.WithContext(context.WithValue(r.Context(), failedBasicAuth, realm))
		return false, nil, nil
	})
}
1257001
func NewBasicHandlerFunc(h health.IHealth) http.HandlerFunc {
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		status := http.StatusOK
		body := "ok"

		if h.Failed() {
			status = http.StatusInternalServerError
			body = "failed"
		}

		rw.WriteHeader(status)
		rw.Write([]byte(body))
	})
}
284910
func BasicAuthHandler(w http.ResponseWriter, r *http.Request) {
	basicAuthHandler(w, r, http.StatusUnauthorized)
}
472871
func BasicAuthEncode(username, password string) string {
	return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
}
1284190
func (c *Cors) HandlerFunc(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
		c.logf("HandlerFunc: Preflight request")
		c.handlePreflight(w, r)
	} else {
		c.logf("HandlerFunc: Actual request")
		c.handleActualRequest(w, r)
	}
}
1228063
func (b basicAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// Check if we have a user-provided error handler, else set a default
	if b.opts.UnauthorizedHandler == nil {
		b.opts.UnauthorizedHandler = http.HandlerFunc(defaultUnauthorizedHandler)
	}

	// Check that the provided details match
	if b.authenticate(r) == false {
		b.requestAuth(w, r)
		return
	}

	// Call the next handler on success.
	b.h.ServeHTTP(w, r)
}
103118
func CheckBasicAuth(r *http.Request) (*BasicAuth, error) {
	if r.Header.Get("Authorization") == "" {
		return nil, nil
	}

	s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
	if len(s) != 2 || s[0] != "Basic" {
		return nil, errors.New("Invalid authorization header")
	}

	b, err := base64.StdEncoding.DecodeString(s[1])
	if err != nil {
		return nil, err
	}
	pair := strings.SplitN(string(b), ":", 2)
	if len(pair) != 2 {
		return nil, errors.New("Invalid authorization message")
	}

	// Decode the client_id and client_secret pairs as per
	// https://tools.ietf.org/html/rfc6749#section-2.3.1

	username, err := url.QueryUnescape(pair[0])
	if err != nil {
		return nil, err
	}

	password, err := url.QueryUnescape(pair[1])
	if err != nil {
		return nil, err
	}

	return &BasicAuth{Username: username, Password: password}, nil
}