Skip to content
This repository has been archived by the owner on Feb 27, 2023. It is now read-only.

Commit

Permalink
time.Unix(0,0) does not return time.Time{} as one would expect. This …
Browse files Browse the repository at this point in the history
…is a workaround so that a call Expiry.Time() returns an accurate representation of what the JWT expiry actually is
  • Loading branch information
dtuck9 committed Jan 11, 2019
1 parent e94fb17 commit 64da96a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
5 changes: 5 additions & 0 deletions jwt/claims.go
Expand Up @@ -73,6 +73,11 @@ func (n *NumericDate) UnmarshalJSON(b []byte) error {

// Time returns time.Time representation of NumericDate.
func (n NumericDate) Time() time.Time {
if n == NumericDate(0) {
// time.Unix(0,0) != time.Time{} (it should, but it doesn't).
// This is a workaround.
return time.Time{}
}
return time.Unix(int64(n), 0)
}

Expand Down
29 changes: 29 additions & 0 deletions jwt/claims_test.go
Expand Up @@ -78,3 +78,32 @@ func TestDecodeClaims(t *testing.T) {
assert.Equal(t, v.Err, json.Unmarshal([]byte(v.Raw), &c))
}
}

func TestTime(t *testing.T) {
tests := []struct {
description string
input NumericDate
expected time.Time
}{
{
description: "0 returns time.Time{}",
input: NumericDate(0),
expected: time.Time{},
},
{
description: "Other number returns appropriate time",
input: NumericDate(1547232324),
expected: time.Date(2019, 1, 11, 18, 45, 24, 0, time.UTC),
},
}

for _, test := range tests {
test := test
t.Run(test.description, func(t *testing.T) {
t.Parallel()

output := test.input.Time()
assert.Truef(t, test.expected.Equal(output), "Expected [%s] but received [%s]", test.expected, output)
})
}
}

0 comments on commit 64da96a

Please sign in to comment.