Files
mce/internal/common/cookie.go

41 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package common
import (
"log"
"net/http"
"metazone.cc/mce/internal/config"
"github.com/gin-gonic/gin"
)
// Cookie 名称常量
const (
SessionCookieName = "mlb_sid" // 会话 ID CookieHttpOnly
)
// SetSessionCookie 写入会话 ID Cookie
// rememberMe=true → Cookie maxAge=30天关浏览器后仍保持登录
// rememberMe=false → Cookie maxAge=空闲超时默认2h与Redis TTL一致关浏览器后自动清除
func SetSessionCookie(c *gin.Context, sid string, rememberMe bool, cfg *config.Config) {
secure := cfg.Server.Mode != "debug"
c.SetSameSite(http.SameSiteLaxMode)
var maxAge int
if rememberMe {
maxAge = cfg.Session.RememberTimeout * 60 // 分钟 → 秒
} else {
maxAge = cfg.Session.IdleTimeout * 60 // 分钟 → 秒,与 Redis TTL 一致
}
log.Printf("[SetSessionCookie] sid=%s rememberMe=%v maxAge=%ds secure=%v", sid[:16]+"...", rememberMe, maxAge, secure)
c.SetCookie(SessionCookieName, sid, maxAge, "/", "", secure, true)
}
// ClearSessionCookie 清除会话 ID Cookielogout 调用)
func ClearSessionCookie(c *gin.Context, cfg *config.Config) {
secure := cfg.Server.Mode != "debug"
c.SetCookie(SessionCookieName, "", -1, "/", "", secure, true)
}