From 9b61ce2531a2b9f68ac6cd7c065743f38c6f672b Mon Sep 17 00:00:00 2001 From: corebreaker Date: Tue, 1 Aug 2017 11:00:30 +0300 Subject: [PATCH] Add `IsNew` flag on sessions Former-commit-id: 94ac010a156bbe124033da2cbaac05fc4726d189 --- sessions/session.go | 13 ++++++++++++- sessions/sessions.go | 4 +++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/sessions/session.go b/sessions/session.go index 7c91a659..b998d9f8 100644 --- a/sessions/session.go +++ b/sessions/session.go @@ -17,6 +17,7 @@ type ( // This is what will be returned when sess := sessions.Start(). Session struct { sid string + isNew bool values memstore.Store // here are the real values // we could set the flash messages inside values but this will bring us more problems // because of session databases and because of @@ -26,7 +27,6 @@ type ( // NOTE: flashes are not managed by third-party, only inside session struct. flashes map[string]*flashMessage mu sync.RWMutex - createdAt time.Time expireAt *time.Time // nil pointer means no expire date timer *time.Timer provider *provider @@ -44,6 +44,11 @@ func (s *Session) ID() string { return s.sid } +// IsNew returns true if is's a new session +func (s *Session) IsNew() bool { + return s.isNew +} + // HasExpireDate test if this session has an expire date, if not, this session never expires func (s *Session) HasExpireDate() bool { return s.expireAt != nil @@ -285,6 +290,7 @@ func (s *Session) set(key string, value interface{}, immutable bool) { s.mu.Unlock() s.updateDatabases() + s.isNew = false } // Set fills the session with an entry"value", based on its "key". @@ -336,6 +342,10 @@ func (s *Session) Delete(key string) bool { s.mu.Unlock() s.updateDatabases() + if removed { + s.isNew = false + } + return removed } @@ -357,6 +367,7 @@ func (s *Session) Clear() { s.mu.Unlock() s.updateDatabases() + s.isNew = false } // ClearFlashes removes all flash messages. diff --git a/sessions/sessions.go b/sessions/sessions.go index 43054b7b..eead9553 100644 --- a/sessions/sessions.go +++ b/sessions/sessions.go @@ -107,6 +107,8 @@ func (s *Sessions) Start(ctx context.Context) *Session { sid := s.config.SessionIDGenerator() sess := s.provider.Init(sid, s.config.Expires) + sess.isNew = len(sess.values) == 0 + s.updateCookie(sid, ctx, s.config.Expires) return sess @@ -114,8 +116,8 @@ func (s *Sessions) Start(ctx context.Context) *Session { cookieValue = s.decodeCookieValue(cookieValue) sess := s.provider.Read(cookieValue, s.config.Expires) - return sess + return sess } // ShiftExpiraton move the expire date of a session to a new date by using session default timeout configuration