Fix CookieNeverExpires time, set an option for -1 for browser-based session (when browser closes cookie is removed)

This commit is contained in:
Gerasimos Maropoulos 2016-07-26 21:26:54 +03:00
parent c26ce245c7
commit 8288161b30
3 changed files with 12 additions and 8 deletions

View File

@ -8,8 +8,8 @@ import (
var (
universe time.Time // 0001-01-01 00:00:00 +0000 UTC
// CookieExpireNever the default cookie's life for sessions, unlimited
CookieExpireNever = universe
// CookieExpireNever the default cookie's life for sessions, unlimited (23 years)
CookieExpireNever = time.Now().AddDate(23, 0, 0)
)
const (
@ -35,7 +35,10 @@ type (
// Defaults to false
DecodeCookie bool
// Expires the duration of which the cookie must expires (created_time.Add(Expires)).
// If you want to delete the cookie when the browser closes, set it to -1 but in this case, the server side's session duration is up to GcDuration
//
// Default infinitive/unlimited life duration(0)
Expires time.Duration
// GcDuration every how much duration(GcDuration) the memory should be clear for unused cookies (GcDuration)
// for example: time.Duration(2)*time.Hour. it will check every 2 hours if cookie hasn't be used for 2 hours,

View File

@ -343,14 +343,15 @@ func (s *Server) FullHost() string {
// Hostname returns the hostname part of the host (host expect port)
func (s *Server) Hostname() string {
idxPort := strings.IndexByte(s.Host(), ':')
a := s.Host()
idxPort := strings.IndexByte(a, ':')
if idxPort > 0 {
// port exists, (it always exists for Config.ListeningAddr
return s.Host()[0:idxPort] // except the port
return a[0:idxPort] // except the port
} // but for Config.VListeningAddr the developer maybe doesn't uses the host:port format
// so, if no port found, then return the Host as it is, it should be something 'mydomain.com'
return s.Host()
return a
}
func (s *Server) listen() error {

View File

@ -154,7 +154,7 @@ func (p *sessionProvider) newSession(sid string) *session {
lastAccessedTime: time.Now(),
values: p.loadSessionValues(sid),
}
if p.expires > 0 { // if not unlimited life duration
if p.expires > 0 { // if not unlimited life duration and no -1 (cookie remove action is based on browser's session)
time.AfterFunc(p.expires, func() {
// the destroy makes the check if this session is exists then or not,
// this is used to destroy the session from the server-side also
@ -348,9 +348,9 @@ func (m *sessionsManager) start(ctx *Context) *session {
if m.config.Expires == 0 {
// unlimited life
cookie.SetExpire(config.CookieExpireNever)
} else {
} else if m.config.Expires > 0 {
cookie.SetExpire(time.Now().Add(m.config.Expires))
}
} // if it's -1 then the cookie is deleted when the browser closes
ctx.SetCookie(cookie)
fasthttp.ReleaseCookie(cookie)