-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtoken.go
307 lines (259 loc) · 8.64 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package egobee
import (
"encoding/json"
"errors"
"io"
"os"
"regexp"
"sync"
"time"
)
var (
// ErrInvalidDuration is returned from UnmarshalJSON when the JSON does not
// represent a Duration.
ErrInvalidDuration = errors.New("invalid duration")
hasUnitRx = regexp.MustCompile("[a-zA-Z]+")
// now overrideable for testing.
now = time.Now
)
// Scope of a token.
type Scope string
// Possible Scopes.
// See https://www.ecobee.com/home/developer/api/documentation/v1/auth/auth-intro.shtml
var (
ScopeSmartRead Scope = "smartRead"
ScopeSmartWrite Scope = "smartWrite"
ScopeEMSWrite Scope = "ems"
)
// PinAuthenticationChallenge is the initial response from the Ecobee API for
// pin-based application authentication.
type PinAuthenticationChallenge struct {
Pin string `json:"ecobeePin"`
AuthorizationCode string `json:"code"`
Scope Scope `json:"scope"`
// expires_in and interval are ignored for now.
}
// TokenDuration wraps time.Duration to add JSON (un)marshalling
type TokenDuration struct {
time.Duration
}
// MarshalJSON returns JSON representation of Duration.
func (d TokenDuration) MarshalJSON() ([]byte, error) {
return json.Marshal(d.Duration.String())
}
// UnmarshalJSON returns a Duration from JSON representation. Since the ecobee
// API returns durations in Seconds, values will be treated as such.
func (d *TokenDuration) UnmarshalJSON(b []byte) error {
var v interface{}
if err := json.Unmarshal(b, &v); err != nil {
return err
}
switch value := v.(type) {
case float64:
d.Duration = time.Second * time.Duration(value)
case string:
if !hasUnitRx.Match([]byte(value)) {
value = value + "s"
}
dv, err := time.ParseDuration(value)
if err != nil {
return err
}
d.Duration = dv
default:
return ErrInvalidDuration
}
return nil
}
// AuthorizationError returned by ecobee.
type AuthorizationError string
// Possible API Errors
var (
AuthorizationErrorAccessDenied AuthorizationError = "access_denied"
AuthorizationErrorInvalidRequest AuthorizationError = "invalid_request"
AuthorizationErrorInvalidClient AuthorizationError = "invalid_client"
AuthorizationErrorInvalidGrant AuthorizationError = "invalid_grant"
AuthorizationErrorUnauthorizeClient AuthorizationError = "unauthorized_client"
AuthorizationErrorUnsupportedGrantType AuthorizationError = "unsupported_grant_type"
AuthorizationErrorInvalidScope AuthorizationError = "invalid_scope"
AuthorizationErrorNotSupported AuthorizationError = "not_supported"
AuthorizationErrorAccountLocked AuthorizationError = "account_locked"
AuthorizationErrorAccountDisabled AuthorizationError = "account_disabled"
AuthorizationErrorAuthorizationPending AuthorizationError = "authorization_pending"
AuthorizationErrorAuthorizationExpired AuthorizationError = "authorization_expired"
AuthorizationErrorSlowDown AuthorizationError = "slow_down"
)
// AuthorizationErrorResponse as returned from the ecobee API.
type AuthorizationErrorResponse struct {
Error AuthorizationError `json:"error"`
Description string `json:"error_description"`
URI string `json:"error_uri"`
}
// Parse a response payload into the receiving AuthorizationErrorResponse. This will
// naturally fail if the payload is not an AuthorizationErrorResponse.
func (r *AuthorizationErrorResponse) Parse(payload []byte) error {
if err := json.Unmarshal(payload, r); err != nil {
return err
}
return nil
}
// ParseString behaves the same as Parse, but on a string.
func (r *AuthorizationErrorResponse) ParseString(payload string) error {
return r.Parse([]byte(payload))
}
// Populate behaves the same as Parse, but reads the content from an io.Reader.
func (r *AuthorizationErrorResponse) Populate(reader io.Reader) error {
d := json.NewDecoder(reader)
return d.Decode(r)
}
// TokenRefreshResponse is returned by the ecobee API on toke refresh.
// See https://www.ecobee.com/home/developer/api/documentation/v1/auth/token-refresh.shtml
type TokenRefreshResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn TokenDuration `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope Scope `json:"scope"`
}
// Parse a response payload into the receiving TokenRefreshResponse. This will
// naturally fail if the payload is not an TokenRefreshResponse.
func (r *TokenRefreshResponse) Parse(payload []byte) error {
if err := json.Unmarshal(payload, r); err != nil {
return err
}
return nil
}
// ParseString behaves the same as Parse, but on a string.
func (r *TokenRefreshResponse) ParseString(payload string) error {
return r.Parse([]byte(payload))
}
// Populate behaves the same as Parse, but reads the content from an io.Reader.
func (r *TokenRefreshResponse) Populate(reader io.Reader) error {
d := json.NewDecoder(reader)
return d.Decode(r)
}
// TokenStorer for ecobee Access and Refresh tokens.
type TokenStorer interface {
// AccessToken gets the access token from the store.
AccessToken() string
// RefreshToken gets the refresh token from the store.
RefreshToken() string
// ValidFor reports how much longer the access token is valid.
ValidFor() time.Duration
// Update the TokenStorer with the contents of the response. This mutates the
// access and refresh tokens.
Update(*TokenRefreshResponse) error
}
// memoryStore implements tokenStore backed only by memory.
type memoryStore struct {
mu sync.RWMutex // protects the following members
accessToken string
refreshToken string
validUntil time.Time
}
func (s *memoryStore) AccessToken() string {
s.mu.RLock()
defer s.mu.RUnlock()
return s.accessToken
}
func (s *memoryStore) RefreshToken() string {
s.mu.RLock()
defer s.mu.RUnlock()
return s.refreshToken
}
func (s *memoryStore) ValidFor() time.Duration {
s.mu.RLock()
defer s.mu.RUnlock()
return s.validUntil.Sub(now())
}
func (s *memoryStore) Update(r *TokenRefreshResponse) error {
s.mu.Lock()
defer s.mu.Unlock()
s.accessToken = r.AccessToken
s.refreshToken = r.RefreshToken
s.validUntil = generateValidUntil(r)
return nil
}
// NewMemoryTokenStore is a TokenStorer with no persistence.
func NewMemoryTokenStore(r *TokenRefreshResponse) TokenStorer {
s := &memoryStore{}
s.Update(r)
return s
}
const persistentStorePermissions = 0640
// persistentStoreData stores the data in memory matching the data stored to disk
type persistentStoreData struct {
AccessTokenData string `json:"accessToken"`
RefreshTokenData string `json:"refreshToken"`
ValidUntilData time.Time `json:"validUntil"`
}
// persistentStore implements tokenStore backed by disk.
type persistentStore struct {
mu sync.RWMutex // protects the following members
path string // path to store file
persistentStoreData
}
func (s *persistentStore) AccessToken() string {
s.mu.RLock()
defer s.mu.RUnlock()
return s.AccessTokenData
}
func (s *persistentStore) RefreshToken() string {
s.mu.RLock()
defer s.mu.RUnlock()
return s.RefreshTokenData
}
func (s *persistentStore) ValidFor() time.Duration {
s.mu.RLock()
defer s.mu.RUnlock()
return s.ValidUntilData.Sub(now())
}
func (s *persistentStore) Update(r *TokenRefreshResponse) error {
// Update in-memory data
s.mu.Lock()
defer s.mu.Unlock()
s.AccessTokenData = r.AccessToken
s.RefreshTokenData = r.RefreshToken
s.ValidUntilData = generateValidUntil(r)
f, err := os.OpenFile(s.path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, persistentStorePermissions)
if err != nil {
return err
}
defer f.Close()
// Write token data to file to be accessed later
return json.NewEncoder(f).Encode(&s.persistentStoreData)
}
// load the data from local file into memory.
func (s *persistentStore) load() error {
s.mu.Lock()
defer s.mu.Unlock()
f, err := os.Open(s.path)
if err != nil {
return err
}
defer f.Close()
return json.NewDecoder(f).Decode(&s.persistentStoreData)
}
// NewPersistentTokenStore is a TokenStorer with persistence to disk
func NewPersistentTokenStore(r *TokenRefreshResponse, path string) (TokenStorer, error) {
s := &persistentStore{
path: path,
}
// update persistent storage tokenstore
if err := s.Update(r); err != nil {
return nil, err
}
return s, nil
}
// NewPersistentTokenFromDisk returns a TokenStorer based on disk location
func NewPersistentTokenFromDisk(path string) (TokenStorer, error) {
s := &persistentStore{
path: path,
}
return s, s.load()
}
// generateValidUntil returns the time the token expires with an added buffer
func generateValidUntil(r *TokenRefreshResponse) time.Time {
// Subtract a few seconds to allow for network and processing delays.
return now().Add(r.ExpiresIn.Duration - (15 * time.Second))
}