-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtoken.go
119 lines (100 loc) · 2.26 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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package nordigen
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"strings"
)
type Token struct {
Access string `json:"access"`
AccessExpires int `json:"access_expires"`
Refresh string `json:"refresh"`
RefreshExpires int `json:"refresh_expires"`
}
type TokenRefresh struct {
Refresh string `json:"refresh"`
}
type Secret struct {
SecretId string `json:"secret_id"`
AccessId string `json:"secret_key"`
}
const tokenPath = "token"
const tokenNewPath = "new/"
const tokenRefreshPath = "refresh/"
// newToken gets a new access token
func (c *Client) newToken(ctx context.Context) error {
c.m.Lock()
defer c.m.Unlock()
data, err := json.Marshal(Secret{
SecretId: c.secretId,
AccessId: c.secretKey,
})
if err != nil {
return err
}
req := &http.Request{
Method: http.MethodPost,
Body: io.NopCloser(bytes.NewBuffer(data)),
URL: &url.URL{
Path: strings.Join([]string{tokenPath, tokenNewPath}, "/"),
},
}
req = req.WithContext(ctx)
resp, err := c.c.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, readErr := io.ReadAll(resp.Body)
if readErr != nil {
return readErr
}
if resp.StatusCode != http.StatusOK {
return &APIError{StatusCode: resp.StatusCode, Body: string(body)}
}
t := &Token{}
if err := json.Unmarshal(body, t); err != nil {
return err
}
c.token = t
return nil
}
// refreshToken gets a new access token using the refresh token
func (c *Client) refreshToken(ctx context.Context) error {
c.m.Lock()
defer c.m.Unlock()
data, err := json.Marshal(TokenRefresh{Refresh: c.token.Refresh})
if err != nil {
return err
}
req := &http.Request{
Method: http.MethodPost,
Body: io.NopCloser(bytes.NewBuffer(data)),
URL: &url.URL{
Path: strings.Join([]string{tokenPath, tokenRefreshPath}, "/"),
},
}
req = req.WithContext(ctx)
resp, err := c.c.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, readErr := io.ReadAll(resp.Body)
if readErr != nil {
return readErr
}
if resp.StatusCode != http.StatusOK {
return &APIError{StatusCode: resp.StatusCode, Body: string(body)}
}
t := &Token{}
if err := json.Unmarshal(body, t); err != nil {
return err
}
c.token.Access = t.Access
c.token.AccessExpires = t.AccessExpires
return nil
}