Skip to content

Commit

Permalink
calculate cookie max-age using TimeFunc (#249)
Browse files Browse the repository at this point in the history
  • Loading branch information
JorritSalverda authored Jun 6, 2020
1 parent f4a6a29 commit 653dcba
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
2 changes: 1 addition & 1 deletion auth_jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ func (mw *GinJWTMiddleware) LoginHandler(c *gin.Context) {
// set cookie
if mw.SendCookie {
expireCookie := mw.TimeFunc().Add(mw.CookieMaxAge)
maxage := int(expireCookie.Unix() - time.Now().Unix())
maxage := int(expireCookie.Unix() - mw.TimeFunc().Unix())
c.SetCookie(
mw.CookieName,
tokenString,
Expand Down
15 changes: 9 additions & 6 deletions auth_jwt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -200,6 +201,8 @@ func TestMissingAuthenticatorForLoginHandler(t *testing.T) {
func TestLoginHandler(t *testing.T) {

// the middleware to test
cookieName := "jwt"
cookieDomain := "example.com"
authMiddleware, err := New(&GinJWTMiddleware{
Realm: "test zone",
Key: key,
Expand Down Expand Up @@ -236,7 +239,10 @@ func TestLoginHandler(t *testing.T) {
"cookie": cookie,
})
},
SendCookie: true,
SendCookie: true,
CookieName: cookieName,
CookieDomain: cookieDomain,
TimeFunc: func() time.Time { return time.Now().Add(time.Duration(5) * time.Minute) },
})

assert.NoError(t, err)
Expand Down Expand Up @@ -269,19 +275,16 @@ func TestLoginHandler(t *testing.T) {
})

r.POST("/login").
SetCookie(gofight.H{
"jwt": "jwt",
}).
SetJSON(gofight.D{
"username": "admin",
"password": "admin",
}).
Run(handler, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
message := gjson.Get(r.Body.String(), "message")
cookie := gjson.Get(r.Body.String(), "cookie")
assert.Equal(t, "login successfully", message.String())
assert.Equal(t, http.StatusOK, r.Code)
assert.Equal(t, "jwt", cookie.String())
assert.True(t, strings.HasPrefix(r.HeaderMap.Get("Set-Cookie"), "jwt="))
assert.True(t, strings.HasSuffix(r.HeaderMap.Get("Set-Cookie"), "; Path=/; Domain=example.com; Max-Age=3600"))
})
}

Expand Down

0 comments on commit 653dcba

Please sign in to comment.