Skip to content

Commit 0f8739e

Browse files
author
Taras.Hots
committed
fix: extended token expiry message with duration
1 parent 1d7bc3f commit 0f8739e

2 files changed

Lines changed: 24 additions & 3 deletions

File tree

validator.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ func (v *Validator) verifyExpiresAt(claims Claims, cmp time.Time, required bool)
182182
return errorIfRequired(required, "exp")
183183
}
184184

185-
return errorIfFalse(cmp.Before((exp.Time).Add(+v.leeway)), ErrTokenExpired)
185+
return errorIfFalse(cmp.Before((exp.Time).Add(+v.leeway)), fmt.Errorf("%w by %s", ErrTokenExpired, cmp.Sub(exp.Time).Truncate(time.Second)))
186186
}
187187

188188
// verifyIssuedAt compares the iat claim in claims against cmp. This function

validator_test.go

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package jwt
22

33
import (
44
"errors"
5+
"strings"
56
"testing"
67
"time"
78
)
@@ -103,6 +104,7 @@ func Test_Validator_verifyExpiresAt(t *testing.T) {
103104
fields fields
104105
args args
105106
wantErr error
107+
wantBy string
106108
}{
107109
{
108110
name: "good claim",
@@ -116,6 +118,19 @@ func Test_Validator_verifyExpiresAt(t *testing.T) {
116118
args: args{claims: MapClaims{"exp": "string"}},
117119
wantErr: ErrInvalidType,
118120
},
121+
{
122+
name: "when leeway is in future",
123+
fields: fields{leeway: 10 * time.Minute},
124+
args: args{claims: RegisteredClaims{ExpiresAt: NewNumericDate(time.Now().Add(9 * time.Minute))}},
125+
wantErr: nil,
126+
},
127+
{
128+
name: "when leeway is in the past",
129+
fields: fields{leeway: 10 * time.Minute},
130+
args: args{claims: RegisteredClaims{ExpiresAt: NewNumericDate(time.Now().Add(-15 * time.Minute))}, cmp: time.Now()},
131+
wantErr: ErrTokenExpired,
132+
wantBy: "by 15m0s",
133+
},
119134
}
120135
for _, tt := range tests {
121136
t.Run(tt.name, func(t *testing.T) {
@@ -125,8 +140,14 @@ func Test_Validator_verifyExpiresAt(t *testing.T) {
125140
}
126141

127142
err := v.verifyExpiresAt(tt.args.claims, tt.args.cmp, tt.args.required)
128-
if (err != nil) && !errors.Is(err, tt.wantErr) {
129-
t.Errorf("validator.verifyExpiresAt() error = %v, wantErr %v", err, tt.wantErr)
143+
if err != nil {
144+
if !errors.Is(err, tt.wantErr) {
145+
t.Errorf("validator.verifyExpiresAt() error = %v, wantErr %v", err, tt.wantErr)
146+
}
147+
148+
if errors.Is(err, ErrTokenExpired) && !strings.Contains(err.Error(), tt.wantBy) {
149+
t.Errorf("Error string %q did not contain %q", err, tt.wantBy)
150+
}
130151
}
131152
})
132153
}

0 commit comments

Comments
 (0)