// BasicAuth creates a authorization strategy that uses
// uses username and password in HTTP Basic Auth
198849
func BasicAuth(username, password string) Strategy {
	return &basicAuth{
		username: username,
		password: password,
	}
}
514165
func (b *basicAuth) authenticate(r *http.Request) bool {
	const basicScheme string = "Basic "

	if r == nil {
		return false
	}

	// In simple mode, prevent authentication with empty credentials if User is
	// not set. Allow empty passwords to support non-password use-cases.
	if b.opts.AuthFunc == nil && b.opts.User == "" {
		return false
	}

	// Confirm the request is sending Basic Authentication credentials.
	auth := r.Header.Get("Authorization")
	if !strings.HasPrefix(auth, basicScheme) {
		return false
	}

	// Get the plain-text username and password from the request.
	// The first six characters are skipped - e.g. "Basic ".
	str, err := base64.StdEncoding.DecodeString(auth[len(basicScheme):])
	if err != nil {
		return false
	}

	// Split on the first ":" character only, with any subsequent colons assumed to be part
	// of the password. Note that the RFC2617 standard does not place any limitations on
	// allowable characters in the password.
	creds := bytes.SplitN(str, []byte(":"), 2)

	if len(creds) != 2 {
		return false
	}

	givenUser := string(creds[0])
	givenPass := string(creds[1])

	// Default to Simple mode if no AuthFunc is defined.
	if b.opts.AuthFunc == nil {
		b.opts.AuthFunc = b.simpleBasicAuthFunc
	}

	return b.opts.AuthFunc(givenUser, givenPass, r)
}
1297322
func (h *basicAuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	username, password, _ := r.BasicAuth()
	usernameOk := subtle.ConstantTimeCompare([]byte(h.Username), []byte(username)) == 1
	passwordOk := subtle.ConstantTimeCompare([]byte(h.Password), []byte(password)) == 1
	if !usernameOk || !passwordOk {
		w.Header().Set("WWW-Authenticate", `Basic realm="metrics"`)
		http.Error(w, "Invalid username or password", http.StatusUnauthorized)
		return
	}

	h.nextHandler.ServeHTTP(w, r)
}
543835
func ParseAuthHeader(header string) (*BasicAuth, error) {
	values := strings.Fields(header)
	if len(values) != 2 {
		return nil, fmt.Errorf(fmt.Sprintf("Failed to parse header '%s'", header))
	}

	authType := strings.ToLower(values[0])
	if authType != "basic" {
		return nil, fmt.Errorf("Expected basic auth type, got '%s'", authType)
	}

	encodedString := values[1]
	decodedString, err := base64.StdEncoding.DecodeString(encodedString)
	if err != nil {
		return nil, fmt.Errorf("Failed to parse header '%s', base64 failed: %s", header, err)
	}

	values = strings.SplitN(string(decodedString), ":", 2)
	if len(values) != 2 {
		return nil, fmt.Errorf("Failed to parse header '%s', expected separator ':'", header)
	}
	return &BasicAuth{Username: values[0], Password: values[1]}, nil
}
860386
func (s *Sling) SetBasicAuth(username, password string) *Sling {
	return s.Set("Authorization", "Basic "+basicAuth(username, password))
}
808677
func Basic(username string, password string) macaron.Handler {
	var siteAuth = base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
	return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
		auth := req.Header.Get("Authorization")
		if !SecureCompare(auth, basicPrefix+siteAuth) {
			basicUnauthorized(res)
			return
		}
		c.Map(User(username))
	}
}
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
}
379396
func BasicAuth(username, passwd string) ConfigOpt {
	// TODO(jdef) this could be more efficient. according to the stdlib we're not supposed to
	// mutate the original Request, so we copy here (including headers). another approach would
	// be to generate a functional RequestOpt that adds the right header.
	return WrapRoundTripper(func(rt http.RoundTripper) http.RoundTripper {
		return roundTripperFunc(func(req *http.Request) (*http.Response, error) {
			var h http.Header
			if req.Header != nil {
				h = make(http.Header, len(req.Header))
				for k, v := range req.Header {
					h[k] = append(make([]string, 0, len(v)), v...)
				}
			}
			clonedReq := *req
			clonedReq.Header = h
			clonedReq.SetBasicAuth(username, passwd)
			return rt.RoundTrip(&clonedReq)
		})
	})
}
49628
func RouterMiddlewareBasicAuth(username, password string) RouterMiddleware {
	return func(h httprouter.Handle) httprouter.Handle {
		return func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
			// Basic auth
			if handleBasicAuth(username, password, rw, r) {
				return
			}

			// Next handler
			h(rw, r, p)
		}
	}
}
637761
func getBasicAuthInfo(r *http.Request) (string, string, bool, error) {
	// Retrieve the Authorization header and check whether it contains basic auth information
	const basicScheme string = "Basic "
	auth := r.Header.Get("Authorization")

	if !strings.HasPrefix(auth, basicScheme) {
		return "", "", false, nil
	}

	str, err := base64.StdEncoding.DecodeString(auth[len(basicScheme):])
	if err != nil {
		return "", "", false, errors.New("no valid base64 data in basic auth scheme found")
	}

	cred := strings.SplitN(string(str), ":", 2)
	if len(cred) < 2 {
		return "", "", false, errors.New("invalid Authorization header")
	}

	username, password := cred[0], cred[1]

	// empty user or pass is not an error but we do not want to try to authenticate in this case
	if len(username) == 0 || len(password) == 0 {
		return "", "", false, nil
	}

	return username, password, true, nil
}
373189
func (s *UpdateBranchInput) SetBasicAuthCredentials(v string) *UpdateBranchInput {
	s.BasicAuthCredentials = &v
	return s
}
33981
func BasicAuthHandler(h http.Handler,
	authFn func(string, string) (interface{}, bool), realm string) http.HandlerFunc {

	if realm == "" {
		realm = "Authorization Required"
	}
	return func(w http.ResponseWriter, r *http.Request) {
		// Self-awareness
		if _, ok := GetUser(w); ok {
			h.ServeHTTP(w, r)
			return
		}
		authInfo := r.Header.Get("Authorization")
		if authInfo == "" {
			// No authorization info, return 401
			Unauthorized(w, realm)
			return
		}
		parts := strings.Split(authInfo, " ")
		if len(parts) != 2 {
			BadRequest(w, "Bad authorization header")
			return
		}
		scheme := parts[0]
		creds, err := base64.StdEncoding.DecodeString(parts[1])
		if err != nil {
			BadRequest(w, "Bad credentials encoding")
			return
		}
		index := bytes.Index(creds, []byte(":"))
		if scheme != "Basic" || index < 0 {
			BadRequest(w, "Bad authorization header")
			return
		}
		user, pwd := string(creds[:index]), string(creds[index+1:])
		udata, ok := authFn(user, pwd)
		if ok {
			// Save user data and continue
			uw := &userResponseWriter{w, udata, user}
			h.ServeHTTP(uw, r)
		} else {
			Unauthorized(w, realm)
		}
	}
}
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
}
425546
func (ctx *Context) GetBasicAuth() (string, string, error) {
	if len(ctx.Request.Header["Authorization"]) == 0 {
		return "", "", errors.New("No Authorization header provided")
	}
	authHeader := ctx.Request.Header["Authorization"][0]
	authString := strings.Split(string(authHeader), " ")
	if authString[0] != "Basic" {
		return "", "", errors.New("Not Basic Authentication")
	}
	decodedAuth, err := base64.StdEncoding.DecodeString(authString[1])
	if err != nil {
		return "", "", err
	}
	authSlice := strings.Split(string(decodedAuth), ":")
	if len(authSlice) != 2 {
		return "", "", errors.New("Error delimiting authString into username/password. Malformed input: " + authString[1])
	}
	return authSlice[0], authSlice[1], nil
}
301851
func (b BasicAuth) String() string {
	return fmt.Sprintf("Basic %s", hashAuth(b.Login, b.Password))
}
403320
func MiddlewareBasicAuth(username, password string) Middleware {
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
			// Basic auth
			if handleBasicAuth(username, password, rw, r) {
				return
			}

			// Next handler
			h.ServeHTTP(rw, r)
		})
	}
}
329384
func (a BasicAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	var protected, isAuthenticated bool

	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

			// 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

			// remove credentials from request to avoid leaking upstream
			r.Header.Del("Authorization")
		}
	}

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

	// Pass-through when no paths match
	return a.Next.ServeHTTP(w, r)
}