-
-
Notifications
You must be signed in to change notification settings - Fork 993
/
identity.go
74 lines (59 loc) · 1.68 KB
/
identity.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
package internal
import (
"context"
"encoding/json"
"io"
"net/http"
"time"
"github.com/go-acme/lego/v4/providers/dns/internal/errutils"
)
// DefaultIdentityURL represents the Identity API endpoint to call.
const DefaultIdentityURL = "https://identity.api.rackspacecloud.com/v2.0/tokens"
type Identifier struct {
baseURL string
httpClient *http.Client
}
// NewIdentifier creates a new Identifier.
func NewIdentifier(httpClient *http.Client, baseURL string) *Identifier {
if httpClient == nil {
httpClient = &http.Client{Timeout: 5 * time.Second}
}
if baseURL == "" {
baseURL = DefaultIdentityURL
}
return &Identifier{baseURL: baseURL, httpClient: httpClient}
}
// Login sends an authentication request.
// https://docs.rackspace.com/docs/cloud-dns/v1/getting-started/authenticate
func (a *Identifier) Login(ctx context.Context, apiUser, apiKey string) (*Identity, error) {
authData := AuthData{
Auth: Auth{
APIKeyCredentials: APIKeyCredentials{
Username: apiUser,
APIKey: apiKey,
},
},
}
req, err := newJSONRequest(ctx, http.MethodPost, a.baseURL, authData)
if err != nil {
return nil, err
}
resp, err := a.httpClient.Do(req)
if err != nil {
return nil, errutils.NewHTTPDoError(req, err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return nil, errutils.NewUnexpectedResponseStatusCodeError(req, resp)
}
raw, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errutils.NewReadResponseError(req, resp.StatusCode, err)
}
var identity Identity
err = json.Unmarshal(raw, &identity)
if err != nil {
return nil, errutils.NewUnmarshalError(req, resp.StatusCode, raw, err)
}
return &identity, nil
}