9
9
"net/http"
10
10
"net/url"
11
11
"strings"
12
+ "time"
12
13
13
14
"golang.org/x/net/context/ctxhttp"
14
15
)
@@ -20,17 +21,44 @@ const (
20
21
errExpiredToken = "expired_token"
21
22
)
22
23
23
- type DeviceAuth struct {
24
- DeviceCode string `json:"device_code"`
25
- UserCode string `json:"user_code"`
26
- VerificationURI string `json:"verification_uri,verification_url "`
27
- VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
28
- ExpiresIn int `json:"expires_in"`
29
- Interval int `json:"interval,omitempty"`
24
+ type DeviceAuthResponse struct {
25
+ DeviceCode string `json:"device_code"`
26
+ UserCode string `json:"user_code"`
27
+ VerificationURI string `json:"verification_uri"`
28
+ VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
29
+ Expiry time. Time `json:"expires_in"`
30
+ Interval int `json:"interval,omitempty"`
30
31
raw map [string ]interface {}
31
32
}
32
33
33
- func retrieveDeviceAuth (ctx context.Context , c * Config , v url.Values ) (* DeviceAuth , error ) {
34
+ func (d DeviceAuthResponse ) MarshalJSON () ([]byte , error ) {
35
+ type Alias DeviceAuthResponse
36
+ return json .Marshal (& struct {
37
+ ExpiresIn int64 `json:"expires_in"`
38
+ * Alias
39
+ }{
40
+ ExpiresIn : int64 (time .Until (d .Expiry ).Seconds ()),
41
+ Alias : (* Alias )(& d ),
42
+ })
43
+
44
+ }
45
+
46
+ func (c * DeviceAuthResponse ) UnmarshalJSON (data []byte ) error {
47
+ type Alias DeviceAuthResponse
48
+ aux := & struct {
49
+ ExpiresIn int64 `json:"expires_in"`
50
+ * Alias
51
+ }{
52
+ Alias : (* Alias )(c ),
53
+ }
54
+ if err := json .Unmarshal (data , & aux ); err != nil {
55
+ return err
56
+ }
57
+ c .Expiry = time .Now ().UTC ().Add (time .Second * time .Duration (aux .ExpiresIn ))
58
+ return nil
59
+ }
60
+
61
+ func retrieveDeviceAuth (ctx context.Context , c * Config , v url.Values ) (* DeviceAuthResponse , error ) {
34
62
req , err := http .NewRequest ("POST" , c .Endpoint .DeviceAuthURL , strings .NewReader (v .Encode ()))
35
63
if err != nil {
36
64
return nil , err
@@ -54,7 +82,7 @@ func retrieveDeviceAuth(ctx context.Context, c *Config, v url.Values) (*DeviceAu
54
82
}
55
83
}
56
84
57
- da := & DeviceAuth {}
85
+ da := & DeviceAuthResponse {}
58
86
err = json .Unmarshal (body , & da )
59
87
if err != nil {
60
88
return nil , fmt .Errorf ("unmarshal %s" , err )
0 commit comments