github.com/liamawhite/cli-with-i18n@v6.32.1-0.20171122084555-dede0a5c3448+incompatible/api/uaa/auth.go (about)

     1  package uaa
     2  
     3  import (
     4  	"net/http"
     5  	"net/url"
     6  	"strings"
     7  
     8  	"github.com/liamawhite/cli-with-i18n/api/uaa/internal"
     9  )
    10  
    11  // AuthResponse contains the access token and refresh token which are granted
    12  // after UAA has authorized a user.
    13  type AuthResponse struct {
    14  	AccessToken  string `json:"access_token"`
    15  	RefreshToken string `json:"refresh_token"`
    16  }
    17  
    18  // Authenticate sends a username and password to UAA then returns an access
    19  // token and a refresh token.
    20  func (client Client) Authenticate(username string, password string) (string, string, error) {
    21  	requestBody := url.Values{}
    22  	requestBody.Set("username", username)
    23  	requestBody.Set("password", password)
    24  	requestBody.Set("grant_type", "password")
    25  
    26  	request, err := client.newRequest(requestOptions{
    27  		RequestName: internal.PostOAuthTokenRequest,
    28  		Header: http.Header{
    29  			"Content-Type": {"application/x-www-form-urlencoded"},
    30  		},
    31  		Body: strings.NewReader(requestBody.Encode()),
    32  	})
    33  	if err != nil {
    34  		return "", "", err
    35  	}
    36  	request.SetBasicAuth(client.id, client.secret)
    37  
    38  	responseBody := AuthResponse{}
    39  	response := Response{
    40  		Result: &responseBody,
    41  	}
    42  
    43  	err = client.connection.Make(request, &response)
    44  	return responseBody.AccessToken, responseBody.RefreshToken, err
    45  }