// ParseAuthHeader creates a new BasicAuth from header values
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
}
824310
func noAuthHeaders(c context.Context, uri string, opts *rpcOptions) (*oauth2.Token, map[string]string, error) {
	return nil, nil, nil
}
1106977
func (auth *Auth) ParseHeader(header string, t AuthType) error {
	if len(header) < 4 || strings.ToLower(header[:4]) != "hawk" {
		return AuthFormatError{"scheme", "must be Hawk"}
	}

	fields, err := lexHeader(header[4:])
	if err != nil {
		return err
	}

	if hash, ok := fields["hash"]; ok {
		auth.Hash, err = base64.StdEncoding.DecodeString(hash)
		if err != nil {
			return AuthFormatError{"hash", "malformed base64 encoding"}
		}
	}
	auth.Ext = fields["ext"]

	mac := fields["mac"]
	if mac == "" {
		return AuthFormatError{"mac", "missing or empty"}
	}
	auth.MAC, err = base64.StdEncoding.DecodeString(mac)
	if err != nil {
		return AuthFormatError{"mac", "malformed base64 encoding"}
	}
	if t == AuthHeader {
		auth.Credentials.App = fields["app"]
		auth.Credentials.Delegate = fields["dlg"]
		auth.Credentials.ID = fields["id"]

		if ts, ok := fields["ts"]; ok {
			tsint, err := strconv.ParseInt(ts, 10, 64)
			if err != nil {
				return AuthFormatError{"ts", "not an integer"}
			}
			auth.Timestamp = time.Unix(tsint, 0)
		}
		auth.Nonce = fields["nonce"]
	}
	return nil
}
350950
func ParseHeader(h http.Header) Group {
	if headers, found := h["Link"]; found {
		return Parse(strings.Join(headers, ", "))
	}

	return nil
}
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
}
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)
		})
	})
}
53314
func (s *S3Uploader) buildAuthHeader(md5, headerTime, fileName string) (string, error) {
	access, err := getAuthCredentials()
	if err != nil {
		return "", err
	}

	// Docs: http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html
	verStr := fmt.Sprintf("PUT\n%s\napplication/x-gzip\n%s\nx-amz-acl:%s\n/%s", md5, headerTime, s.permission,
		path.Join(s.bucketName, fileName))
	encodedStr := hmac.ComputeHmacSha1(verStr, access.SecretKey)
	return fmt.Sprintf("AWS %s:%s", access.AccessKey, encodedStr), nil
}
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
}
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)
}
339547
func (a *BasicAuth) RequireAuth(w http.ResponseWriter, r *http.Request) {
	w.Header().Set(contentType, a.Headers.V().UnauthContentType)
	w.Header().Set(a.Headers.V().Authenticate, `Basic realm="`+a.Realm+`"`)
	w.WriteHeader(a.Headers.V().UnauthCode)
	w.Write([]byte(a.Headers.V().UnauthResponse))
}
40182
func AuthBasic(username string, password string) ProxyAuthorization {
	return &basicAuth{username: username, password: password}
}
669555
func (c *AccountClient) SetHeader(header *http.Header) {
	c.Client.RequestHeader = header
}
142861
func GetBasicAuthHeader(user string, password string) string {
	var userAndPass = user + ":" + password
	return "Basic " + base64.StdEncoding.EncodeToString([]byte(userAndPass))
}
1255020
func (c *UserConfig) ParseAuthorize(request *http.Request, service *Service) (string, string, error) {
	request.ParseForm()
	urlParts := request.URL.Query()
	token := urlParts.Get("oauth_token")
	verifier := urlParts.Get("oauth_verifier")
	if token == "" {
		token = request.Form.Get("oauth_token")
	}
	if verifier == "" {
		verifier = request.Form.Get("oauth_verifier")
	}
	if token == "" || verifier == "" {
		return "", "", fmt.Errorf("Token or verifier were missing from response")
	}
	return token, verifier, nil
}
814649
func BasicAuthHandlerFunc(h http.HandlerFunc,
	authFn func(string, string) (interface{}, bool), realm string) http.HandlerFunc {
	return BasicAuthHandler(h, authFn, realm)
}
492680
func AddAuthHeaders(ctx context.Context, r *http.Request, serviceToken string) {
	if IsUserPresent(ctx) {
		AddUserHeader(r, User(ctx))
	}
	AddServiceTokenHeader(r, serviceToken)
}
546640
func NewAPIKeyAuthorizer(headers map[string]interface{}, queryParameters map[string]interface{}) *APIKeyAuthorizer {
	return &APIKeyAuthorizer{headers: headers, queryParameters: queryParameters}
}