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