github.com/franc20/ayesa_sap@v7.0.0-beta.28.0.20200124003224-302d4d52fa6c+incompatible/api/uaa/auth.go (about)

     1  package uaa
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  	"net/url"
     7  	"strings"
     8  
     9  	"code.cloudfoundry.org/cli/api/uaa/constant"
    10  	"code.cloudfoundry.org/cli/api/uaa/internal"
    11  )
    12  
    13  // AuthResponse contains the access token and refresh token which are granted
    14  // after UAA has authorized a user.
    15  type AuthResponse struct {
    16  	AccessToken  string `json:"access_token"`
    17  	RefreshToken string `json:"refresh_token"`
    18  }
    19  
    20  // Authenticate sends a username and password to UAA then returns an access
    21  // token and a refresh token.
    22  func (client Client) Authenticate(creds map[string]string, origin string, grantType constant.GrantType) (string, string, error) {
    23  	requestBody := url.Values{
    24  		"grant_type": {string(grantType)},
    25  	}
    26  
    27  	for k, v := range creds {
    28  		requestBody.Set(k, v)
    29  	}
    30  
    31  	type loginHint struct {
    32  		Origin string `json:"origin"`
    33  	}
    34  
    35  	originStruct := loginHint{origin}
    36  	originParam, err := json.Marshal(originStruct)
    37  	if err != nil {
    38  		return "", "", err
    39  	}
    40  
    41  	var query url.Values
    42  	if origin != "" {
    43  		query = url.Values{
    44  			"login_hint": {string(originParam)},
    45  		}
    46  	}
    47  
    48  	request, err := client.newRequest(requestOptions{
    49  		RequestName: internal.PostOAuthTokenRequest,
    50  		Header: http.Header{
    51  			"Content-Type": {"application/x-www-form-urlencoded"},
    52  		},
    53  		Body:  strings.NewReader(requestBody.Encode()),
    54  		Query: query,
    55  	})
    56  
    57  	if err != nil {
    58  		return "", "", err
    59  	}
    60  
    61  	if grantType == constant.GrantTypePassword {
    62  		request.SetBasicAuth(client.config.UAAOAuthClient(), client.config.UAAOAuthClientSecret())
    63  	}
    64  
    65  	responseBody := AuthResponse{}
    66  	response := Response{
    67  		Result: &responseBody,
    68  	}
    69  
    70  	err = client.connection.Make(request, &response)
    71  	return responseBody.AccessToken, responseBody.RefreshToken, err
    72  }