-
Notifications
You must be signed in to change notification settings - Fork 8
/
token.go
73 lines (56 loc) · 1.53 KB
/
token.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
package metadata
import (
"context"
"fmt"
"strconv"
"time"
)
type TokenOption func(opts *tokenCreateOpts)
// TokenWithExpiry configures the expiry in seconds for a token.
// Default: 3600
func TokenWithExpiry(seconds int) TokenOption {
return func(opts *tokenCreateOpts) {
opts.ExpirySeconds = seconds
}
}
type tokenCreateOpts struct {
ExpirySeconds int
}
// GenerateToken generates a token to access the Metadata API.
func (c *Client) GenerateToken(ctx context.Context, opts ...TokenOption) (string, error) {
// Handle create options
createOpts := tokenCreateOpts{
ExpirySeconds: 3600,
}
for _, opt := range opts {
opt(&createOpts)
}
req := c.R(ctx).
SetResult(&[]string{}).
SetHeader("Metadata-Token-Expiry-Seconds", strconv.Itoa(createOpts.ExpirySeconds))
resp, err := req.Put("token")
if err != nil {
return "", err
}
result := *resp.Result().(*[]string)
if len(result) < 1 {
return "", fmt.Errorf("no token returned from API")
}
return result[0], nil
}
// UseToken applies the given token to this Metadata client.
func (c *Client) UseToken(token string) *Client {
c.resty.SetHeader("Metadata-Token", token)
return c
}
// RefreshToken generates and applies a new token for this client.
func (c *Client) RefreshToken(ctx context.Context, opts ...TokenOption) (*Client, error) {
creationTime := time.Now()
token, err := c.GenerateToken(ctx, opts...)
if err != nil {
return nil, fmt.Errorf("failed to generate metadata token: %w", err)
}
c.UseToken(token)
c.managedTokenExpiry = creationTime
return c, nil
}