-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
85 lines (72 loc) · 2.12 KB
/
api.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
package cephrestclient
//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen -config codegen-config.yaml https://raw.githubusercontent.com/ceph/ceph/reef/src/pybind/mgr/dashboard/openapi.yaml
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/oapi-codegen/oapi-codegen/v2/pkg/securityprovider"
)
type NewAuthenticatedClientOpts struct {
Username string
Password string
Server string
SkipTLS bool
}
func CephAPIVersionHeaderIntercepter(version string) RequestEditorFn {
return func(ctx context.Context, req *http.Request) error {
req.Header.Set("Accept", fmt.Sprintf("application/vnd.ceph.api.v%s+json", version))
return nil
}
}
func NewAuthenticatedClient(ctx context.Context, opts NewAuthenticatedClientOpts) (*Client, error) {
client, err := NewClient(
opts.Server,
WithHTTPClient(&http.Client{Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
DisableCompression: true,
}}),
WithRequestEditorFn(CephAPIVersionHeaderIntercepter("1.0")),
WithRequestEditorFn(func(ctx context.Context, req *http.Request) error {
req.Header.Set("Content-Type", "application/json")
return nil
}),
)
if err != nil {
return nil, err
}
res, err := client.PostApiAuth(ctx, PostApiAuthJSONRequestBody{
Username: opts.Username,
Password: opts.Password,
})
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusCreated {
return nil, fmt.Errorf("unexpected status code %d. respnse body: %s", res.StatusCode, string(body))
}
var AuthResponse struct{ Token string }
err = json.Unmarshal(body, &AuthResponse)
if err != nil {
return nil, err
}
if AuthResponse.Token == "" {
return nil, fmt.Errorf("expected non blank token in body: %s", string(body))
}
securityProvicder, err := securityprovider.NewSecurityProviderBearerToken(AuthResponse.Token)
if err != nil {
return nil, err
}
err = WithRequestEditorFn(securityProvicder.Intercept)(client)
if err != nil {
return nil, err
}
return client, nil
}