Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions deviceauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"time"

Expand Down Expand Up @@ -59,7 +60,8 @@ func (d DeviceAuthResponse) MarshalJSON() ([]byte, error) {
func (c *DeviceAuthResponse) UnmarshalJSON(data []byte) error {
type Alias DeviceAuthResponse
aux := &struct {
ExpiresIn int64 `json:"expires_in"`
ExpiresIn interface{} `json:"expires_in"`
Interval interface{} `json:"interval"`
// workaround misspelling of verification_uri
VerificationURL string `json:"verification_url"`
*Alias
Expand All @@ -69,9 +71,35 @@ func (c *DeviceAuthResponse) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
if aux.ExpiresIn != 0 {
c.Expiry = time.Now().UTC().Add(time.Second * time.Duration(aux.ExpiresIn))

if aux.ExpiresIn != nil {
if expiresIn, ok := aux.ExpiresIn.(float64); ok {
if expiresIn != 0 {
c.Expiry = time.Now().UTC().Add(time.Second * time.Duration(expiresIn))
}
} else if expiresInStr, ok := aux.ExpiresIn.(string); ok {
expiresIn, err := strconv.ParseInt(expiresInStr, 10, 64)
if err != nil {
return err
}
if expiresIn != 0 {
c.Expiry = time.Now().UTC().Add(time.Second * time.Duration(expiresIn))
}
}
}

if aux.Interval != nil {
if interval, ok := aux.Interval.(float64); ok {
c.Interval = int64(interval)
} else if intervalStr, ok := aux.Interval.(string); ok {
interval, err := strconv.ParseInt(intervalStr, 10, 64)
if err != nil {
return err
}
c.Interval = interval
}
}

if c.VerificationURI == "" {
c.VerificationURI = aux.VerificationURL
}
Expand Down
11 changes: 8 additions & 3 deletions deviceauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,14 @@ func TestDeviceAuthResponseUnmarshalJson(t *testing.T) {
want: DeviceAuthResponse{},
},
{
name: "soon",
data: `{"expires_in":100}`,
want: DeviceAuthResponse{Expiry: time.Now().UTC().Add(100 * time.Second)},
name: "soon - ints",
data: `{"expires_in":100,"interval": 5}`,
want: DeviceAuthResponse{Interval: 5, Expiry: time.Now().UTC().Add(100 * time.Second)},
},
{
name: "soon - strings",
data: `{"expires_in":"100","interval":"5"}`,
want: DeviceAuthResponse{Interval: 5, Expiry: time.Now().UTC().Add(100 * time.Second)},
},
}
for _, tc := range tests {
Expand Down