sessions icon indicating copy to clipboard operation
sessions copied to clipboard

Clear on Server shutdown?

Open MTRNord opened this issue 7 years ago • 7 comments

Hi I would like to clear the Session on Server shutdown because that logs my Users out. Is this possible?

MTRNord avatar Jul 25 '17 20:07 MTRNord

defer ?

ghiewa avatar Jul 26 '17 01:07 ghiewa

Not sure what that means. I am just starting to learn go. Could you give me a code example?

MTRNord avatar Jul 26 '17 07:07 MTRNord

What I said defer should looks like,

	router.Use(func(c *gin.Context) {
		defer func() {
			session := sessions.Default(c)
			session.Clear()
			session.Save()
		}()
		c.Next()
	})

but tricky thing is I fail to archieve the goal. are checking if MaxAge = -1 is ok or not

ghiewa avatar Jul 28 '17 03:07 ghiewa

sad! I can't delete cookie as well. My coding like this in a logout handler,

func Logout(ctx *gin.Context) {
	session := sessions.Default(ctx)
	session.Clear()
	//session.Options(sessions.Options{MaxAge:-1})  // TODO
	err := session.Save()
	if err != nil {
		log.Println(err)
	}
	ctx.Redirect(http.StatusMovedPermanently, login_url)
}

@appleboy help us!

ghiewa avatar Aug 03 '17 11:08 ghiewa

I am facing the issue of losing the session on server restart. Redis key that worked is still in redis, cookie I send is also the same, only thing that changes is server restart and somehow the session is gone! Please let me know what to change.

zereraz avatar Aug 29 '17 13:08 zereraz

Hi @ghiewa , I have same issue, and I found the reason.

In my case, I use 301 code to redirect, first time is working, if I try to logout again and it's not working, I found my browser cache the 301 redirect, 301 is move permanently, when I change from 301 to 302, it's work!

In your case, try to use http.StatusFound.

ShawnOY avatar Mar 27 '18 03:03 ShawnOY

Easiest way to reset all sessions on a server restart would be to change authentication and/or encryption keys on each restart. For example:

sessionStore := cookie.NewStore(generateRandomBytes(64), generateRandomBytes(32))
router.Use(sessions.Sessions("mysite", sessionStore))

Don't forget to use crypto/rand instead of math/rand for generating your random bytes!

jarmo avatar Sep 26 '19 11:09 jarmo