-
Notifications
You must be signed in to change notification settings - Fork 72
/
client.go
103 lines (86 loc) · 2.52 KB
/
client.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package uaa_client
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"code.cloudfoundry.org/lager"
)
type BadUaaResponse struct {
StatusCode int
UaaResponseBody string
}
func (r BadUaaResponse) Error() string {
return fmt.Sprintf("bad uaa response: %d: %s", r.StatusCode, r.UaaResponseBody)
}
type Client struct {
BaseURL string
Name string
Secret string
HTTPClient httpClient
Logger lager.Logger
}
//go:generate counterfeiter -o fakes/http_client.go --fake-name HTTPClient . httpClient
type httpClient interface {
Do(*http.Request) (*http.Response, error)
}
type CheckTokenResponse struct {
Scope []string `json:"scope"`
UserID string `json:"user_id"`
UserName string `json:"user_name"`
}
func (c *Client) GetToken() (string, error) {
reqURL := fmt.Sprintf("%s/oauth/token", c.BaseURL)
bodyString := fmt.Sprintf("client_id=%s&grant_type=client_credentials", c.Name)
request, err := http.NewRequest("POST", reqURL, strings.NewReader(bodyString))
request.SetBasicAuth(c.Name, c.Secret)
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
c.Logger.Debug("get-token", lager.Data{"URL": request.URL})
type getTokenResponse struct {
AccessToken string `json:"access_token"`
}
response := &getTokenResponse{}
err = c.makeRequest(request, response)
if err != nil {
return "", err
}
return response.AccessToken, nil
}
func (c *Client) CheckToken(token string) (CheckTokenResponse, error) {
reqURL := fmt.Sprintf("%s/check_token", c.BaseURL)
bodyString := "token=" + token
request, err := http.NewRequest("POST", reqURL, strings.NewReader(bodyString))
request.SetBasicAuth(c.Name, c.Secret)
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
c.Logger.Debug("check-token", lager.Data{"URL": request.URL})
response := &CheckTokenResponse{}
err = c.makeRequest(request, response)
if err != nil {
return CheckTokenResponse{}, err
}
return *response, nil
}
func (c *Client) makeRequest(request *http.Request, response interface{}) error {
resp, err := c.HTTPClient.Do(request)
if err != nil {
return fmt.Errorf("http client: %s", err)
}
defer resp.Body.Close()
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("read body: %s", err)
}
if resp.StatusCode != 200 {
err = BadUaaResponse{
StatusCode: resp.StatusCode,
UaaResponseBody: string(respBytes),
}
return err
}
err = json.Unmarshal(respBytes, &response)
if err != nil {
return fmt.Errorf("unmarshal json: %s", err)
}
return nil
}