// BasicAuth parses the Authorization header on req
// If absent or invalid, an error is returned.
187211
func BasicAuth(req *http.Request) (username, password string, err error) {
	auth := req.Header.Get("Authorization")
	if auth == "" {
		err = fmt.Errorf("Missing \"Authorization\" in header")
		return
	}
	matches := kBasicAuthPattern.FindStringSubmatch(auth)
	if len(matches) != 2 {
		err = fmt.Errorf("Bogus Authorization header")
		return
	}
	encoded := matches[1]
	enc := base64.StdEncoding
	decBuf := make([]byte, enc.DecodedLen(len(encoded)))
	n, err := enc.Decode(decBuf, []byte(encoded))
	if err != nil {
		return
	}
	pieces := strings.SplitN(string(decBuf[0:n]), ":", 2)
	if len(pieces) != 2 {
		err = fmt.Errorf("didn't get two pieces")
		return
	}
	return pieces[0], pieces[1], nil
}
1086102
func (s *CreateAppInput) SetBasicAuthCredentials(v string) *CreateAppInput {
	s.BasicAuthCredentials = &v
	return s
}
1252382
func BasicAuthFromContext(ctx context.Context) (*BasicAuth, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return nil, nil
	}
	authorization, ok := md["Authorization"]
	if !ok {
		authorization, ok = md["authorization"]
		if !ok {
			return nil, nil
		}
	}
	if len(authorization) != 1 {
		return nil, ErrInvalidAuthorization
	}
	if !strings.HasPrefix(authorization[0], "Basic ") {
		return nil, ErrInvalidAuthorization
	}
	decoded, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authorization[0], "Basic "))
	if err != nil {
		return nil, err
	}
	split := strings.SplitN(string(decoded), ":", 2)
	if len(split) != 2 {
		return nil, ErrInvalidAuthorization
	}
	return &BasicAuth{
		Username: split[0],
		Password: split[1],
	}, nil
}
1183057
func (h *BasicAuthHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	authInfo, err := h.Authenticator.Authenticate(req)
	if err != nil {
		w.Header().Set("WWW-Authenticate", `Basic realm="juju"`)
		if common.IsDischargeRequiredError(err) {
			sendErr := sendError(w, err)
			if sendErr != nil {
				logger.Errorf("%v", sendErr)
			}
			return
		}
		http.Error(w,
			fmt.Sprintf("authentication failed: %s", err),
			http.StatusUnauthorized,
		)
		return
	}
	if h.Authorizer != nil {
		if err := h.Authorizer.Authorize(authInfo); err != nil {
			http.Error(w,
				fmt.Sprintf("authorization failed: %s", err),
				http.StatusForbidden,
			)
			return
		}
	}
	ctx := context.WithValue(req.Context(), authInfoKey{}, authInfo)
	req = req.WithContext(ctx)
	h.Handler.ServeHTTP(w, req)
}
709363
func (c *Context) RequireBasicAuth(username, password string) {
	fields := strings.Fields(c.Req.Header.Get("Authorization"))
	if len(fields) != 2 || fields[0] != "Basic" {
		c.Status(http.StatusUnauthorized)
		return
	}

	uname, passwd, _ := tool.BasicAuthDecode(fields[1])
	if uname != username || passwd != password {
		c.Status(http.StatusForbidden)
		return
	}
}
1064653
func (s *SuperAgent) SetBasicAuth(username string, password string) *SuperAgent {
	s.BasicAuth = struct{ Username, Password string }{username, password}
	return s
}
1145925
func BasicAuth(username, password string) runtime.ClientAuthInfoWriter {
	return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
		encoded := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
		return r.SetHeaderParam("Authorization", "Basic "+encoded)
	})
}
629249
func newBasicAuthentication(userName, password string) httpAuthentication {
	auth := fmt.Sprintf("%s:%s", userName, password)
	encoded := base64.StdEncoding.EncodeToString([]byte(auth))
	return &basicAuthentication{
		authorizationValue: "Basic " + encoded,
	}
}
451662
func (uri URI) PlainAuth() *PlainAuth {
	return &PlainAuth{
		Username: uri.Username,
		Password: uri.Password,
	}
}
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)
		})
	}
}
77996
func APIKeyAuth(key string, h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if key == "" {
			log.Error().Msg("API key is empty")
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
		authorization := r.Header.Get("Authorization")
		parts := strings.Fields(authorization)
		if len(parts) != 2 {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
		authMethod := strings.ToLower(parts[0])
		if authMethod != "apikey" || parts[1] != key {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
		h.ServeHTTP(w, r)
	})
}
1063250
func (s *UpdateAppInput) SetBasicAuthCredentials(v string) *UpdateAppInput {
	s.BasicAuthCredentials = &v
	return s
}
384018
func (a BasicAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	var protected, isAuthenticated bool
	var realm string
	var username string
	var password string
	var ok bool

	// do not check for basic auth on OPTIONS call
	if r.Method == http.MethodOptions {
		// Pass-through when no paths match
		return a.Next.ServeHTTP(w, r)
	}

	for _, rule := range a.Rules {
		for _, res := range rule.Resources {
			if !httpserver.Path(r.URL.Path).Matches(res) {
				continue
			}

			// path matches; this endpoint is protected
			protected = true
			realm = rule.Realm

			// parse auth header
			username, password, ok = r.BasicAuth()

			// check credentials
			if !ok ||
				username != rule.Username ||
				!rule.Password(password) {
				continue
			}

			// by this point, authentication was successful
			isAuthenticated = true

			// let upstream middleware (e.g. fastcgi and cgi) know about authenticated
			// user; this replaces the request with a wrapped instance
			r = r.WithContext(context.WithValue(r.Context(),
				httpserver.RemoteUserCtxKey, username))

			// Provide username to be used in log by replacer
			repl := httpserver.NewReplacer(r, nil, "-")
			repl.Set("user", username)
		}
	}

	if protected && !isAuthenticated {
		// browsers show a message that says something like:
		// "The website says: <realm>"
		// which is kinda dumb, but whatever.
		if realm == "" {
			realm = "Restricted"
		}
		w.Header().Set("WWW-Authenticate", "Basic realm=\""+realm+"\"")

		// Get a replacer so we can provide basic info for the authentication error.
		repl := httpserver.NewReplacer(r, nil, "-")
		repl.Set("user", username)
		errstr := repl.Replace("BasicAuth: user \"{user}\" was not found or password was incorrect. {remote} {host} {uri} {proto}")
		err := fmt.Errorf("%s", errstr)
		return http.StatusUnauthorized, err
	}

	// Pass-through when no paths match
	return a.Next.ServeHTTP(w, r)
}
365299
func (s *CreateBranchInput) SetBasicAuthCredentials(v string) *CreateBranchInput {
	s.BasicAuthCredentials = &v
	return s
}
1364916
func AuthorizationHeader(creds *common.Credentials) (key, value string) {
	return "Authorization", "Bearer " + creds.Get(OAuth2KeyAccessToken).Str("Invalid")
}
264702
func (b *basicAuth) simpleBasicAuthFunc(user, pass string, r *http.Request) bool {
	// Equalize lengths of supplied and required credentials
	// by hashing them
	givenUser := sha256.Sum256([]byte(user))
	givenPass := sha256.Sum256([]byte(pass))
	requiredUser := sha256.Sum256([]byte(b.opts.User))
	requiredPass := sha256.Sum256([]byte(b.opts.Password))

	// Compare the supplied credentials to those set in our options
	if subtle.ConstantTimeCompare(givenUser[:], requiredUser[:]) == 1 &&
		subtle.ConstantTimeCompare(givenPass[:], requiredPass[:]) == 1 {
		return true
	}

	return false
}
142861
func GetBasicAuthHeader(user string, password string) string {
	var userAndPass = user + ":" + password
	return "Basic " + base64.StdEncoding.EncodeToString([]byte(userAndPass))
}