-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
session.go
89 lines (67 loc) · 1.89 KB
/
session.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
package internal
import (
"context"
"encoding/json"
"net/http"
"github.com/go-acme/lego/v4/providers/dns/internal/errutils"
)
type token string
const tokenKey token = "token"
const authTokenHeader = "Auth-Token"
// login Starts a new Dyn API Session. Authenticates using customerName, username, password
// and receives a token to be used in for subsequent requests.
// https://help.dyn.com/session-log-in/
func (c *Client) login(ctx context.Context) (session, error) {
endpoint := c.baseURL.JoinPath("Session")
payload := &credentials{Customer: c.customerName, User: c.username, Pass: c.password}
req, err := newJSONRequest(ctx, http.MethodPost, endpoint, payload)
if err != nil {
return session{}, err
}
dynRes, err := c.do(req)
if err != nil {
return session{}, err
}
var s session
err = json.Unmarshal(dynRes.Data, &s)
if err != nil {
return session{}, errutils.NewUnmarshalError(req, http.StatusOK, dynRes.Data, err)
}
return s, nil
}
// Logout Destroys Dyn Session.
// https://help.dyn.com/session-log-out/
func (c *Client) Logout(ctx context.Context) error {
endpoint := c.baseURL.JoinPath("Session")
req, err := newJSONRequest(ctx, http.MethodDelete, endpoint, nil)
if err != nil {
return err
}
tok := getToken(ctx)
if tok != "" {
req.Header.Set(authTokenHeader, tok)
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return errutils.NewHTTPDoError(req, err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return errutils.NewUnexpectedResponseStatusCodeError(req, resp)
}
return nil
}
func (c *Client) CreateAuthenticatedContext(ctx context.Context) (context.Context, error) {
tok, err := c.login(ctx)
if err != nil {
return nil, err
}
return context.WithValue(ctx, tokenKey, tok.Token), nil
}
func getToken(ctx context.Context) string {
tok, ok := ctx.Value(tokenKey).(string)
if !ok {
return ""
}
return tok
}