I am using gorilla/sessions for session handling. Below is my code for session:
var STORE = sessions.NewCookieStore([]byte("some_secret_text"))
session, err := STORE.Get(c.Request, "user")
if err != nil {
fmt.Println("Error: ",err)
}
if session.IsNew {
session.Options.MaxAge = 10 * 60
}
I want to logout user only if he is idle for 10 minutes. Currently user gets logged out even if he is working.
Here is sample code that I use to do this:
func SessionHandler(ses sessions.Session, timeout int64) {
timeNow := time.Now().Unix()
if ses.Get("authenticated").(bool) {
switch ses.Get("timestamp").(type) {
case int64:
sessiontime := ses.Get("timestamp").(int64)
if sessiontime > 0 {
if timeNow > (sessiontime + timeout) {
ses.Clear()
ses.Save()
return
}
ses.Set("timestamp", timeNow)
ses.Save()
}
default:
ses.Set("timestamp", timeNow)
ses.Save()
}
}
}
I had some good experience using https://github.com/alexedwards/scs for session-handling.
It also includes a setting for idle-timeout:
session.IdleTimeout(30*time.Minute)
I don't know if switching the session-library is an option for you, but scs integrates pretty seamlessly, so it might be worth looking at it at least. :)