99 "net/http"
1010 "net/url"
1111 "strings"
12+ "time"
1213
1314 "golang.org/x/net/context/ctxhttp"
1415)
@@ -20,17 +21,44 @@ const (
2021 errExpiredToken = "expired_token"
2122)
2223
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"`
3031 raw map [string ]interface {}
3132}
3233
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 ) {
3462 req , err := http .NewRequest ("POST" , c .Endpoint .DeviceAuthURL , strings .NewReader (v .Encode ()))
3563 if err != nil {
3664 return nil , err
@@ -54,7 +82,7 @@ func retrieveDeviceAuth(ctx context.Context, c *Config, v url.Values) (*DeviceAu
5482 }
5583 }
5684
57- da := & DeviceAuth {}
85+ da := & DeviceAuthResponse {}
5886 err = json .Unmarshal (body , & da )
5987 if err != nil {
6088 return nil , fmt .Errorf ("unmarshal %s" , err )
0 commit comments