forked from Kong/kubernetes-ingress-controller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
credential.go
103 lines (86 loc) · 2.51 KB
/
credential.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 admin
import (
"encoding/json"
"fmt"
"net/url"
"reflect"
adminv1 "github.com/kong/kubernetes-ingress-controller/internal/apis/admin/v1"
"k8s.io/client-go/rest"
)
type CredentialGetter interface {
Credentials() CredentialInterface
}
type CredentialInterface interface {
List(string, url.Values) (*adminv1.CredentialList, error)
GetByType(string, string, string) (*adminv1.Credential, *APIResponse)
CreateByType(map[string]interface{}, string, string) *APIResponse
}
type credentialAPI struct {
client rest.Interface
}
// curl -X POST http://kong:8001/consumers/{consumer}/{name} -d ''
func (a *credentialAPI) CreateByType(obj map[string]interface{}, consumer, name string) *APIResponse {
rawData, err := json.Marshal(obj)
if err != nil {
return &APIResponse{err: err}
}
resp := a.client.Post().
Resource("consumers").
SubResource(consumer, name).
Body(rawData).
SetHeader("Content-Type", "application/json").
Do()
statusCode := reflect.ValueOf(resp).FieldByName("statusCode").Int()
raw, err := resp.Raw()
response := &APIResponse{StatusCode: int(statusCode), err: err}
if err != nil {
response.Raw = raw
}
return response
}
// GetByType returns a credential of a particular type applied to a consumer
func (a *credentialAPI) GetByType(consumerID, credentialID, credentialType string) (*adminv1.Credential, *APIResponse) {
resp := a.client.Get().
Resource("consumers").
SubResource(consumerID, credentialType, credentialID).
Do()
statusCode := reflect.ValueOf(resp).FieldByName("statusCode").Int()
raw, err := resp.Raw()
response := &APIResponse{StatusCode: int(statusCode), err: err}
if err != nil {
response.Raw = raw
return nil, response
}
out := &adminv1.Credential{}
response.err = json.Unmarshal(raw, out)
return out, response
}
func (a *credentialAPI) List(name string, params url.Values) (*adminv1.CredentialList, error) {
if params == nil {
params = url.Values{}
}
plural := fmt.Sprintf("%vs", name)
credentials := &adminv1.CredentialList{}
request := a.client.Get().Resource(plural)
for k, vals := range params {
for _, v := range vals {
request.Param(k, v)
}
}
data, err := request.DoRaw()
if err != nil {
return nil, err
}
if err := json.Unmarshal(data, credentials); err != nil {
return nil, err
}
if len(credentials.NextPage) > 0 {
params.Set("offset", credentials.Offset)
result, err := a.List(name, params)
if err != nil {
return nil, err
}
credentials.Items = append(credentials.Items, result.Items...)
}
return credentials, err
}