Skip to content

Commit

Permalink
fix: add token expires for system (#1151)
Browse files Browse the repository at this point in the history
  • Loading branch information
jeessy2 authored Jun 13, 2024
1 parent 6f4c790 commit 97f188f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 15 deletions.
6 changes: 4 additions & 2 deletions web/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
Expand Down
30 changes: 17 additions & 13 deletions web/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}

Expand Down

0 comments on commit 97f188f

Please sign in to comment.