From 64da96a9bd0f051c0068a3d3938d438d02565830 Mon Sep 17 00:00:00 2001 From: Diana Tuck Date: Fri, 11 Jan 2019 11:04:07 -0800 Subject: [PATCH] time.Unix(0,0) does not return time.Time{} as one would expect. This is a workaround so that a call Expiry.Time() returns an accurate representation of what the JWT expiry actually is --- jwt/claims.go | 5 +++++ jwt/claims_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/jwt/claims.go b/jwt/claims.go index 31274b0..c02215b 100644 --- a/jwt/claims.go +++ b/jwt/claims.go @@ -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) } diff --git a/jwt/claims_test.go b/jwt/claims_test.go index 6799aab..ed742da 100644 --- a/jwt/claims_test.go +++ b/jwt/claims_test.go @@ -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) + }) + } +}