Skip to content

Commit

Permalink
Merge pull request #283 from go-kivik/earlyAuth
Browse files Browse the repository at this point in the history
Re-authenticate if the cookie is nearing expiration
  • Loading branch information
flimzy authored Jun 6, 2021
2 parents 7a5e3ef + bb0ef81 commit 7c3aefb
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 14 deletions.
2 changes: 1 addition & 1 deletion chttp/cookieauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func (a *CookieAuth) shouldAuth(req *http.Request) bool {
return true
}
if !cookie.Expires.IsZero() {
return cookie.Expires.Before(time.Now())
return cookie.Expires.Before(time.Now().Add(time.Minute))
}
// If we get here, it means the server did not include an expiry time in
// the session cookie. Some CouchDB configurations do this, but rather than
Expand Down
33 changes: 20 additions & 13 deletions chttp/cookieauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ func Test_shouldAuth(t *testing.T) {
c, _ := New("http://example.com/")
c.Jar = &dummyJar{&http.Cookie{
Name: kivik.SessionCookieName,
Expires: time.Now().Add(20 * time.Second),
Expires: time.Now().Add(20 * time.Minute),
}}
a := &CookieAuth{client: c}

Expand Down Expand Up @@ -240,6 +240,20 @@ func Test_shouldAuth(t *testing.T) {
want: false,
}
})
tests.Add("about to expire", func() interface{} {
c, _ := New("http://example.com/")
c.Jar = &dummyJar{&http.Cookie{
Name: kivik.SessionCookieName,
Expires: time.Now().Add(20 * time.Second),
}}
a := &CookieAuth{client: c}

return tt{
a: a,
req: httptest.NewRequest("GET", "/", nil),
want: true,
}
})

tests.Run(t, func(t *testing.T, tt tt) {
got := tt.a.shouldAuth(tt.req)
Expand Down Expand Up @@ -321,19 +335,12 @@ func Test401Response(t *testing.T) {
_, err = c.DoError(context.Background(), "GET", "/foo", nil)

// this causes a skip so this won't work for us.
//testy.StatusError(t, "Unauthorized: You are not authorized to access this db.", 401, err)
if err == nil {
t.Fatal("Should have an auth error")
// testy.StatusError(t, "Unauthorized: You are not authorized to access this db.", 401, err)
if !testy.ErrorMatches("Unauthorized: You are not authorized to access this db.", err) {
t.Fatalf("Unexpected error: %s", err)
}
if err != nil {
errString := err.Error()
if errString != "Unauthorized: You are not authorized to access this db." {
t.Errorf("Unexpected error: %s", err)
}
actualStatus := testy.StatusCode(err)
if 401 != actualStatus {
t.Errorf("Unexpected status code: %d (expected %d)", actualStatus, 401)
}
if status := testy.StatusCode(err); status != http.StatusUnauthorized {
t.Errorf("Unexpected status code: %d", status)
}

var noCookie *http.Cookie
Expand Down

0 comments on commit 7c3aefb

Please sign in to comment.