generated from kyma-project/template-repository
-
Notifications
You must be signed in to change notification settings - Fork 18
/
registry.go
93 lines (79 loc) · 2.08 KB
/
registry.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
package docker
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"io"
)
const (
keyUsername = "username"
keyPassword = "password"
keyServerAddress = "serverAddress"
)
var (
errUsernameNotFound = errors.New("username field not found")
errPasswordNotFound = errors.New("password field not found")
errServerAddressNotFound = errors.New("serverAddress field not found")
)
type registryCfgCredentials struct {
username, password, serverAddress []byte
provideEncoder
}
type provideEncoder func(enc *base64.Encoding, w io.Writer) io.WriteCloser
func (e provideEncoder) encodeUserAndPassword(username, password []byte) (string, error) {
var buff bytes.Buffer
base64encoder := e(base64.StdEncoding, &buff)
// encode username:password to buffer
for _, bytes := range [3][]byte{
username,
[]byte(":"),
password,
} {
if _, err := base64encoder.Write(bytes); err != nil {
return "", err
}
}
// close to flush
if err := base64encoder.Close(); err != nil {
return "", err
}
return buff.String(), nil
}
func createAuthMap(usernameAndPassword string) map[string]interface{} {
return map[string]interface{}{
"auth": usernameAndPassword,
}
}
func (r *registryCfgCredentials) MarshalJSON() ([]byte, error) {
userAndPassword, err := r.provideEncoder.encodeUserAndPassword(r.username, r.password)
if err != nil {
return nil, err
}
config := map[string]interface{}{
"auths": map[string]interface{}{
string(r.serverAddress): createAuthMap(userAndPassword),
},
}
return json.Marshal(&config)
}
// NewRegistryCfgMarshaler creates registry configuration marshaler
func NewRegistryCfgMarshaler(data map[string][]byte) (json.Marshaler, error) {
result := registryCfgCredentials{
provideEncoder: base64.NewEncoder,
}
var found bool
result.username, found = data[keyUsername]
if !found {
return nil, errUsernameNotFound
}
result.password, found = data[keyPassword]
if !found {
return nil, errPasswordNotFound
}
result.serverAddress, found = data[keyServerAddress]
if !found {
return nil, errServerAddressNotFound
}
return &result, nil
}