From 97f188f1269d78bf075b1abface065edcf1d4537 Mon Sep 17 00:00:00 2001 From: jeessy2 <6205259+jeessy2@users.noreply.github.com> Date: Thu, 13 Jun 2024 07:29:17 -0700 Subject: [PATCH] fix: add token expires for system (#1151) --- web/auth.go | 6 ++++-- web/login.go | 30 +++++++++++++++++------------- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/web/auth.go b/web/auth.go index 26d546d21..bbfb04fb9 100644 --- a/web/auth.go +++ b/web/auth.go @@ -14,7 +14,7 @@ type ViewFunc func(http.ResponseWriter, *http.Request) // Auth 验证Token是否已经通过 func Auth(f ViewFunc) ViewFunc { return func(w http.ResponseWriter, r *http.Request) { - tokenInCookie, err := r.Cookie("token") + cookieInWeb, err := r.Cookie(cookieName) if err != nil { http.Redirect(w, r, "./login", http.StatusTemporaryRedirect) return @@ -32,7 +32,9 @@ func Auth(f ViewFunc) ViewFunc { } // 验证token - if tokenInSystem != "" && tokenInSystem == tokenInCookie.Value { + if cookieInSystem.Value != "" && + cookieInSystem.Value == cookieInWeb.Value && + cookieInSystem.Expires.After(time.Now()) { f(w, r) // 执行被装饰的函数 return } diff --git a/web/login.go b/web/login.go index cedbba11f..f02ca9243 100755 --- a/web/login.go +++ b/web/login.go @@ -15,8 +15,11 @@ import ( //go:embed login.html var loginEmbedFile embed.FS -// only need one token -var tokenInSystem = "" +// CookieName cookie name +var cookieName = "token" + +// CookieInSystem only one cookie +var cookieInSystem = &http.Cookie{} // 登录检测 type loginDetect struct { @@ -76,26 +79,27 @@ func LoginFunc(w http.ResponseWriter, r *http.Request) { if data.Username == conf.Username && util.PasswordOK(conf.Password, data.Password) { ld.ticker.Stop() ld.failedTimes = 0 - tokenInSystem = util.GenerateToken(data.Username) // 设置cookie过期时间为1天 - cookieTimeout := 24 + timeoutDays := 1 if conf.NotAllowWanAccess { // 内网访问cookie过期时间为30天 - cookieTimeout = 24 * 30 + timeoutDays = 30 } - // return cookie - cookie := http.Cookie{ - Name: "token", - Value: tokenInSystem, - Path: "/", - Expires: time.Now().Add(time.Hour * time.Duration(cookieTimeout)), + // 覆盖cookie + cookieInSystem = &http.Cookie{ + Name: cookieName, + Value: util.GenerateToken(data.Username), // 生成token + Path: "/", + Expires: time.Now().AddDate(0, 0, timeoutDays), // 设置过期时间 + HttpOnly: true, } - http.SetCookie(w, &cookie) + // 写入cookie + http.SetCookie(w, cookieInSystem) util.Log("%q 登陆成功", util.GetRequestIPStr(r)) - returnOK(w, util.LogStr("登陆成功"), tokenInSystem) + returnOK(w, util.LogStr("登陆成功"), cookieInSystem.Value) return }