-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
client.go
104 lines (88 loc) · 2.51 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
104
package dockerhub
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/replication/model"
"github.com/goharbor/harbor/src/replication/util"
)
// Client is a client to interact with DockerHub
type Client struct {
client *http.Client
token string
host string
credential LoginCredential
}
// NewClient creates a new DockerHub client.
func NewClient(registry *model.Registry) (*Client, error) {
client := &Client{
host: registry.URL,
client: &http.Client{
Transport: util.GetHTTPTransport(false),
},
}
// For anonymous access, no need to refresh token.
if registry.Credential == nil ||
(len(registry.Credential.AccessKey) == 0 && len(registry.Credential.AccessSecret) == 0) {
return client, nil
}
// Login to DockerHub to get access token, default expire date is 30d.
client.credential = LoginCredential{
User: registry.Credential.AccessKey,
Password: registry.Credential.AccessSecret,
}
err := client.refreshToken()
if err != nil {
return nil, fmt.Errorf("login to dockerhub error: %v", err)
}
return client, nil
}
// refreshToken login to DockerHub with user/password, and retrieve access token.
func (c *Client) refreshToken() error {
b, err := json.Marshal(c.credential)
if err != nil {
return fmt.Errorf("marshal credential error: %v", err)
}
request, err := http.NewRequest(http.MethodPost, baseURL+loginPath, bytes.NewReader(b))
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
resp, err := c.client.Do(request)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode/100 != 2 {
return fmt.Errorf("login to dockerhub error: %s", string(body))
}
token := &TokenResp{}
err = json.Unmarshal(body, token)
if err != nil {
return fmt.Errorf("unmarshal token response error: %v", err)
}
c.token = token.Token
return nil
}
// Do performs http request to DockerHub, it will set token automatically.
func (c *Client) Do(method, path string, body io.Reader) (*http.Response, error) {
url := baseURL + path
log.Infof("%s %s", method, url)
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
if body != nil || method == http.MethodPost || method == http.MethodPut {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Authorization", fmt.Sprintf("JWT %s", c.token))
return c.client.Do(req)
}