-
Notifications
You must be signed in to change notification settings - Fork 17
/
uaa.go
71 lines (59 loc) · 1.71 KB
/
uaa.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
package pivnet
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"time"
)
type AuthResp struct {
Token string `json:"access_token"`
}
type TokenFetcher struct {
Endpoint string
RefreshToken string
SkipSSLValidation bool
UserAgent string
}
func NewTokenFetcher(endpoint, refreshToken string, skipSSLValidation bool, userAgent string) *TokenFetcher {
return &TokenFetcher{endpoint, refreshToken, skipSSLValidation, userAgent }
}
func (t TokenFetcher) GetToken() (string, error) {
httpClient := &http.Client{
Timeout: 60 * time.Second,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: t.SkipSSLValidation,
},
Proxy: http.ProxyFromEnvironment,
},
}
body := AuthBody{RefreshToken: t.RefreshToken}
b, err := json.Marshal(body)
if err != nil {
return "", fmt.Errorf("failed to marshal API token request body: %s", err.Error())
}
req, err := http.NewRequest("POST", t.Endpoint+"/authentication/access_tokens", bytes.NewReader(b))
req.Header.Add("Content-Type", "application/json")
if t.UserAgent != "" {
req.Header.Add("User-Agent", t.UserAgent)
}
if err != nil {
return "", fmt.Errorf("failed to construct API token request: %s", err.Error())
}
resp, err := httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("API token request failed: %s", err.Error())
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to fetch API token - received status %v", resp.StatusCode)
}
var response AuthResp
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
return "", fmt.Errorf("failed to decode API token response: %s", err.Error())
}
return response.Token, nil
}