2
0
mirror of https://github.com/acepanel/panel.git synced 2026-02-04 10:17:17 +08:00

feat: 优化会话机制

This commit is contained in:
2025-09-17 05:09:15 +08:00
parent 978ae70e44
commit 261e92a659
9 changed files with 77 additions and 19 deletions

View File

@@ -3,6 +3,7 @@ package middleware
import (
"log/slog"
"net/http"
"path/filepath"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
@@ -12,6 +13,8 @@ import (
"github.com/leonelquinteros/gotext"
"github.com/libtnb/sessions"
sessionmiddleware "github.com/libtnb/sessions/middleware"
"github.com/tnborg/panel/internal/app"
"gopkg.in/natefinch/lumberjack.v2"
"github.com/tnborg/panel/internal/biz"
)
@@ -22,16 +25,23 @@ type Middlewares struct {
conf *koanf.Koanf
log *slog.Logger
session *sessions.Manager
app biz.AppRepo
appRepo biz.AppRepo
userToken biz.UserTokenRepo
}
func NewMiddlewares(conf *koanf.Koanf, log *slog.Logger, session *sessions.Manager, app biz.AppRepo, userToken biz.UserTokenRepo) *Middlewares {
func NewMiddlewares(conf *koanf.Koanf, session *sessions.Manager, appRepo biz.AppRepo, userToken biz.UserTokenRepo) *Middlewares {
ljLogger := &lumberjack.Logger{
Filename: filepath.Join(app.Root, "panel/storage/logs/http.log"),
MaxSize: 10,
MaxAge: 30,
Compress: true,
}
return &Middlewares{
conf: conf,
log: log,
log: slog.New(slog.NewJSONHandler(ljLogger, &slog.HandlerOptions{Level: slog.LevelInfo})),
session: session,
app: app,
appRepo: appRepo,
userToken: userToken,
}
}
@@ -50,6 +60,6 @@ func (r *Middlewares) Globals(t *gotext.Locale, mux *chi.Mux) []func(http.Handle
Status(t),
Entrance(t, r.conf, r.session),
MustLogin(t, r.session, r.userToken),
MustInstall(t, r.app),
MustInstall(t, r.appRepo),
}
}

View File

@@ -8,6 +8,7 @@ import (
"net/http"
"slices"
"strings"
"time"
"github.com/leonelquinteros/gotext"
"github.com/libtnb/sessions"
@@ -72,6 +73,20 @@ func MustLogin(t *gotext.Locale, session *sessions.Manager, userToken biz.UserTo
}
userID = cast.ToUint(sess.Get("user_id"))
refreshAt := cast.ToInt64(sess.Get("refresh_at")) // 上次刷新的时间戳
// 距离上次刷新时间超过 10 分钟刷新 Cookie 有效期
if time.Now().Unix()-refreshAt > 600 {
sess.Put("refresh_at", time.Now().Unix())
// 重新设置 Cookie
http.SetCookie(w, &http.Cookie{
Name: sess.GetName(),
Value: sess.GetID(),
Expires: time.Now().Add(time.Duration(session.Lifetime) * time.Minute),
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
}
}
if userID == 0 {