// makeTokenRequest makes a request for a bootstrap token
426251
func makeTokenRequest(ctx context.Context, client *http.Client, verifier server.Verifier, config *Config) (*server.NodeRegistration, error) {
	registration := &server.NodeRegistration{}

	// @step: create the request payload
	req, err := verifier.VerifyIdentity(ctx)
	if err != nil {
		return nil, err
	}

	hostname, err := getHostname()
	if err != nil {
		return nil, err
	}

	// @step: make the request to the node-authozier
	url := fmt.Sprintf("%s/authorize/%s", strings.TrimSuffix(config.NodeURL, "/authorize"), hostname)
	resp, err := client.Post(url, "application/json", bytes.NewReader(req))
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("invalid response code: %d", resp.StatusCode)
	}

	// @step: read in the response and decode
	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	if err := json.Unmarshal(content, registration); err != nil {
		return nil, err
	}

	return registration, nil
}
1213419
func (t *UAAAuthentication) Make(request *cloudcontroller.Request, passedResponse *cloudcontroller.Response) error {
	if t.client == nil {
		return t.connection.Make(request, passedResponse)
	}

	if t.cache.AccessToken() != "" || t.cache.RefreshToken() != "" {
		// assert a valid access token for authenticated requests
		err := t.refreshToken()
		if nil != err {
			return err
		}
		request.Header.Set("Authorization", t.cache.AccessToken())
	}

	err := t.connection.Make(request, passedResponse)
	return err
}
815628
func (c *Client) DoRequest(r *request) (*http.Response, error) {
	req, err := r.toHTTP()
	if err != nil {
		return nil, err
	}
	for key, value := range r.header {
		req.Header.Add(key, value)
	}
	req.SetBasicAuth(c.config.Username, c.config.Password)
	req.Header.Add("User-Agent", "gogo-bosh")
	resp, err := c.config.HttpClient.Do(req)
	if err != nil {
		if strings.Contains(err.Error(), "oauth2: cannot fetch token") {
			c.refreshClient()
			resp, err = c.config.HttpClient.Do(req)
		}
	}
	return resp, err
}
532268
func (o *RevokeOAuth2TokenParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {

	if err := r.SetTimeout(o.timeout); err != nil {
		return err
	}
	var res []error

	// form param token
	frToken := o.Token
	fToken := frToken
	if fToken != "" {
		if err := r.SetFormParam("token", fToken); err != nil {
			return err
		}
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}
493358
func CreateNewTokens(client clientset.Interface, tokens []kubeadmapi.BootstrapToken) error {
	return UpdateOrCreateTokens(client, true, tokens)
}
791787
func MakeRequest(request rest.Request) (*rest.Response, error) {
	return DefaultClient.Send(request)
}
266189
func makeMetricsRequest(client *http.Client, url string) (producers.MetricsMessage, error) {
	l := logrus.WithFields(logrus.Fields{"plugin": "http-helper"})

	l.Infof("Making request to %s", url)
	mm := producers.MetricsMessage{}

	resp, err := client.Get(url)
	if err != nil {
		l.Errorf("Encountered error requesting data, %s", err.Error())
		return mm, err
	}

	// 204 No Content is not an error code; we handle it explicitly
	if resp.StatusCode == http.StatusNoContent {
		l.Warnf("Empty response received from endpoint: %s", url)
		return mm, nil
	}

	defer resp.Body.Close()
	err = json.NewDecoder(resp.Body).Decode(&mm)
	return mm, errors.Wrapf(err, "could not decode metrics response: %s", url)
}
147745
func (c *Client) MakeRequest(req *http.Request) (*http.Response, error) {
	return c.HTTPClient.Do(req)
}
916020
func MakeMapper(t TokenMapperFn, a AmountMapperFn) MapperFn {
	return func(r request.Request) (string, int64, error) {
		token, err := t(r)
		if err != nil {
			return "", -1, err
		}
		amount, err := a(r)
		if err != nil {
			return "", -1, err
		}
		return token, amount, nil
	}
}
1108855
func TokensCreate(w http.ResponseWriter, r *http.Request) {
	// Decode the request
	var input TokensCreateRequest
	err := utils.ParseRequest(r, &input)
	if err != nil {
		env.Log.WithFields(logrus.Fields{
			"error": err.Error(),
		}).Warn("Unable to decode a request")

		utils.JSONResponse(w, 409, &TokensCreateResponse{
			Success: false,
			Message: "Invalid input format",
		})
		return
	}

	// We can only create "auth" tokens now
	if input.Type != "auth" {
		utils.JSONResponse(w, 409, &TokensCreateResponse{
			Success: false,
			Message: "Only auth tokens are implemented",
		})
		return
	}

	input.Username = utils.RemoveDots(
		utils.NormalizeUsername(input.Username),
	)

	// Check if account exists
	user, err := env.Accounts.FindAccountByName(input.Username)
	if err != nil {
		utils.JSONResponse(w, 403, &TokensCreateResponse{
			Success: false,
			Message: "Wrong username or password",
		})
		return
	}

	// "registered" accounts can't log in
	if user.Status == "registered" {
		utils.JSONResponse(w, 403, &TokensCreateResponse{
			Success: false,
			Message: "Your account is not confirmed",
		})
		return
	}

	// Verify the password
	valid, updated, err := user.VerifyPassword(input.Password)
	if err != nil || !valid {
		utils.JSONResponse(w, 403, &TokensCreateResponse{
			Success: false,
			Message: "Wrong username or password",
		})
		return
	}

	// Update the user if password was updated
	if updated {
		user.DateModified = time.Now()
		err := env.Accounts.UpdateID(user.ID, user)
		if err != nil {
			env.Log.WithFields(logrus.Fields{
				"user":  user.Name,
				"error": err.Error(),
			}).Error("Could not update user")

			// DO NOT RETURN!
		}
	}

	// Check for 2nd factor
	if user.FactorType != "" {
		factor, ok := env.Factors[user.FactorType]
		if ok {
			// Verify the 2FA
			verified, challenge, err := user.Verify2FA(factor, input.Token)
			if err != nil {
				utils.JSONResponse(w, 500, &TokensCreateResponse{
					Success: false,
					Message: "Internal 2FA error",
				})

				env.Log.WithFields(logrus.Fields{
					"err":    err.Error(),
					"factor": user.FactorType,
				}).Warn("2FA authentication error")
				return
			}

			// Token was probably empty. Return the challenge.
			if !verified && challenge != "" {
				utils.JSONResponse(w, 403, &TokensCreateResponse{
					Success:         false,
					Message:         "2FA token was not passed",
					FactorType:      user.FactorType,
					FactorChallenge: challenge,
				})
				return
			}

			// Token was incorrect
			if !verified {
				utils.JSONResponse(w, 403, &TokensCreateResponse{
					Success:    false,
					Message:    "Invalid token passed",
					FactorType: user.FactorType,
				})
				return
			}
		}
	}

	// Calculate the expiry date
	expDate := time.Now().Add(time.Hour * time.Duration(env.Config.SessionDuration))

	// Create a new token
	token := &models.Token{
		Expiring: models.Expiring{ExpiryDate: expDate},
		Resource: models.MakeResource(user.ID, "Auth token expiring on "+expDate.Format(time.RFC3339)),
		Type:     input.Type,
	}

	// Insert int into the database
	env.Tokens.Insert(token)

	// Respond with the freshly created token
	utils.JSONResponse(w, 201, &TokensCreateResponse{
		Success: true,
		Message: "Authentication successful",
		Token:   token,
	})
}
141454
func (c *client) createRequest(rawurl, method string, in interface{}) (*http.Request, error) {
	uri, err := url.Parse(rawurl)
	if err != nil {
		return nil, err
	}

	// if we are posting or putting data, we need to
	// write it to the body of the request.
	var buf io.ReadWriter
	if in != nil {
		buf = new(bytes.Buffer)
		err := json.NewEncoder(buf).Encode(in)
		if err != nil {
			return nil, err
		}
	}

	// creates a new http request to bitbucket.
	req, err := http.NewRequest(method, uri.String(), buf)
	if err != nil {
		return nil, err
	}
	if in != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	return req, nil
}
572754
func ValidateTokenRequest(tr *authentication.TokenRequest) field.ErrorList {
	allErrs := field.ErrorList{}
	specPath := field.NewPath("spec")

	const min = 10 * time.Minute
	if tr.Spec.ExpirationSeconds < int64(min.Seconds()) {
		allErrs = append(allErrs, field.Invalid(specPath.Child("expirationSeconds"), tr.Spec.ExpirationSeconds, "may not specify a duration less than 10 minutes"))
	}
	if tr.Spec.ExpirationSeconds > 1<<32 {
		allErrs = append(allErrs, field.Invalid(specPath.Child("expirationSeconds"), tr.Spec.ExpirationSeconds, "may not specify a duration larger than 2^32 seconds"))
	}
	return allErrs
}
125699
func (client *Client) makeRequest(area string, id string, params map[string]string, v interface{}) (statusCode int, err error) {

	// get the base url
	queryURI, err := url.Parse(rootURI)
	if err != nil {
		return 0, err
	}

	// add the type of request we're making (search|business)
	queryURI.Path = area

	if id != "" {
		queryURI.Path += "/" + id
	}

	// set up OAUTH
	c := oauth.NewCustomHttpClientConsumer(
		client.Options.ConsumerKey,
		client.Options.ConsumerSecret,
		oauth.ServiceProvider{
			RequestTokenUrl:   "",
			AuthorizeTokenUrl: "",
			AccessTokenUrl:    "",
		},
		client.Client)
	token := &oauth.AccessToken{
		client.Options.AccessToken,
		client.Options.AccessTokenSecret,
		make(map[string]string),
	}

	// make the request using the oauth lib
	response, err := c.Get(queryURI.String(), params, token)

	if err != nil {
		if response != nil {
			return response.StatusCode, err
		} else {
			return 500, err
		}
	}

	// close the request when done
	defer response.Body.Close()

	// ensure the request returned a 200
	if response.StatusCode != 200 {
		return response.StatusCode, errors.New(response.Status)
	}

	err = json.NewDecoder(response.Body).Decode(v)
	return response.StatusCode, err
}
630603
func (p Protos) makeRequest(req *http.Request) ([]byte, error) {
	req.Header.Set("Appid", p.AppID)

	resp, err := p.HTTPclient.Do(req)
	if err != nil {
		return []byte{}, err
	}
	defer resp.Body.Close()

	payload, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return []byte{}, err
	}

	if resp.StatusCode != 200 {
		httperr := httpErr{}
		err := json.Unmarshal(payload, &httperr)
		if err != nil {
			return []byte{}, fmt.Errorf("Failed to decode error message from Protos: %s", err.Error())
		}
		return []byte{}, errors.New(httperr.Error)
	}

	return payload, nil
}
725404
func (c *Client) newRequest(method, path string) *request {
	r := &request{
		config: &c.config,
		method: method,
		url: &url.URL{
			Scheme: c.config.Scheme,
			Host:   c.config.Address,
			Path:   path,
		},
		params: make(map[string][]string),
	}
	if c.config.Datacenter != "" {
		r.params.Set("dc", c.config.Datacenter)
	}
	if c.config.WaitTime != 0 {
		r.params.Set("wait", durToMsec(r.config.WaitTime))
	}
	if c.config.Token != "" {
		r.params.Set("token", r.config.Token)
	}
	return r
}
167427
func (client Client) MakeRequest(method, path string, requestBody io.Reader) (int, []byte, error) {
	url := client.Host + path
	request, err := http.NewRequest(method, url, requestBody)
	if err != nil {
		return 0, nil, err
	}
	if client.BasicAuthUsername != "" {
		request.SetBasicAuth(client.BasicAuthUsername, client.BasicAuthPassword)
	} else {
		request.Header.Set("Authorization", "Bearer "+client.AccessToken)
	}
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	httpClient := GetClient(client)
	response, err := httpClient.Do(request)
	if err != nil {
		return 0, nil, err
	}

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return response.StatusCode, body, err
	}

	return response.StatusCode, body, nil
}
43603
func ValidateRequest(r *http.Request, usertoken string) bool {
	var token string
	if strings.Contains(r.Header.Get("content-type"), "/json") {
		decoder := json.NewDecoder(r.Body)
		var i bson.M
		err := decoder.Decode(i)
		if err != nil {
			return false
		}

		token = Decrypt([]byte(FormKey), i["formtoken"].(string))

	} else {
		token = Decrypt([]byte(FormKey), r.FormValue("formtoken"))
	}
	return strings.Contains(token, usertoken) && strings.Contains(token, r.URL.Path)
}