Skip to content

Commit

Permalink
Add CookieFunc to alter cookie based on request before writing it to …
Browse files Browse the repository at this point in the history
…the http-response
  • Loading branch information
guybrush committed May 14, 2024
1 parent 7e11d57 commit 0af7d64
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions session.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ type SessionManager struct {
// Cookie contains the configuration settings for session cookies.
Cookie SessionCookie

// CookieFunc allows you to set update attributes on the session cookie
// before it gets written to the http-response.
CookieFunc func(*http.Request, *http.Cookie)

// Codec controls the encoder/decoder used to transform session data to a
// byte slice for use by the session store. By default session data is
// encoded/decoded using encoding/gob.
Expand Down Expand Up @@ -107,6 +111,7 @@ func New() *SessionManager {
Codec: GobCodec{},
ErrorFunc: defaultErrorFunc,
contextKey: generateContextKey(),
CookieFunc: defaultCookieFunc,
Cookie: SessionCookie{
Name: "session",
Domain: "",
Expand Down Expand Up @@ -172,9 +177,9 @@ func (s *SessionManager) commitAndWriteSessionCookie(w http.ResponseWriter, r *h
return
}

s.WriteSessionCookie(ctx, w, token, expiry)
s.WriteSessionCookie(ctx, w, r, token, expiry)
case Destroyed:
s.WriteSessionCookie(ctx, w, "", time.Time{})
s.WriteSessionCookie(ctx, w, r, "", time.Time{})
}
}

Expand All @@ -188,7 +193,7 @@ func (s *SessionManager) commitAndWriteSessionCookie(w http.ResponseWriter, r *h
//
// Most applications will use the LoadAndSave() middleware and will not need to
// use this method.
func (s *SessionManager) WriteSessionCookie(ctx context.Context, w http.ResponseWriter, token string, expiry time.Time) {
func (s *SessionManager) WriteSessionCookie(ctx context.Context, w http.ResponseWriter, r *http.Request, token string, expiry time.Time) {
cookie := &http.Cookie{
Name: s.Cookie.Name,
Value: token,
Expand All @@ -198,6 +203,7 @@ func (s *SessionManager) WriteSessionCookie(ctx context.Context, w http.Response
HttpOnly: s.Cookie.HttpOnly,
SameSite: s.Cookie.SameSite,
}
s.CookieFunc(r, cookie)

if expiry.IsZero() {
cookie.Expires = time.Unix(1, 0)
Expand All @@ -216,6 +222,9 @@ func defaultErrorFunc(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}

func defaultCookieFunc(r *http.Request, c *http.Cookie) {
}

type sessionResponseWriter struct {
http.ResponseWriter
request *http.Request
Expand Down

0 comments on commit 0af7d64

Please sign in to comment.