仅在空闲时注销

huangapple go评论90阅读模式
英文:

Logout only if idle

问题

我正在使用gorilla/sessions来处理会话。以下是我处理会话的代码:

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
}

我希望只有当用户闲置了10分钟后才注销用户。目前,即使用户在工作,也会被注销。

英文:

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.

答案1

得分: 2

我在使用https://github.com/alexedwards/scs进行会话处理时有一些不错的经验。

它还包括一个用于空闲超时的设置:

session.IdleTimeout(30*time.Minute)

我不知道是否可以切换会话库作为一个选项,但是scs集成得非常顺畅,所以至少值得考虑一下。 仅在空闲时注销

英文:

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. 仅在空闲时注销

答案2

得分: 1

以下是我用来完成这个任务的示例代码:

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()
        }
    }
}

希望对你有帮助!

英文:

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()
		}
	}
}

huangapple
  • 本文由 发表于 2017年5月9日 14:30:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/43862627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定