refactor: JWT 无状态认证替换为服务端 Session,修复记住我掉线问题
- 新增 internal/session 包:Session 结构体、Store 接口、MemoryStore(内存+后台清理)、RedisStore 预留 - Cookie 从 3 个精简为 1 个 mlb_sid(HttpOnly),移除 JWT access/refresh cookie - 会话过期采用滑动窗口:每次请求自动续期,记住我 30 天无操作过期 - AuthMiddleware/AuthAdmin/Maintenance 中间件改用 SessionManager.Validate() - AuthService Login/Register/ConfirmRestore 去除 token 生成,返回 *model.User - Controller 层在登录/注册后调用 SessionManager.Create 创建会话 - AdminService UpdateUserStatus/ResetUserToken 同步销毁 session 实现即时退登 - 改密/注销时通过 DestroyByUID 删除所有 session(替换 TokenVersion 检查) - config.yaml 新增 session 配置段(idle_timeout/remember_timeout/cleanup_interval) - TokenService/auth_parser/auth_token 标记废弃,移除 JWT 到期字段依赖
This commit is contained in:
@ -1,48 +1,81 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/config"
|
||||
"metazone.cc/metalab/internal/session"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// AuthMiddleware 认证中间件(结构体模式,持有 DB 依赖用于实时令牌吊销校验)
|
||||
// AuthMiddleware 认证中间件(结构体模式,持有 SessionManager)
|
||||
type AuthMiddleware struct {
|
||||
cfg *config.Config
|
||||
userRepo tokenVersionStore
|
||||
cfg *config.Config
|
||||
sessionManager *session.Manager
|
||||
}
|
||||
|
||||
// NewAuthMiddleware 构造函数
|
||||
func NewAuthMiddleware(cfg *config.Config, userRepo tokenVersionStore) *AuthMiddleware {
|
||||
return &AuthMiddleware{cfg: cfg, userRepo: userRepo}
|
||||
func NewAuthMiddleware(cfg *config.Config, sm *session.Manager) *AuthMiddleware {
|
||||
return &AuthMiddleware{cfg: cfg, sessionManager: sm}
|
||||
}
|
||||
|
||||
// Required 登录认证中间件:校验 JWT → 检查 token_version → 注入用户信息
|
||||
// Required 登录认证中间件:读 session cookie → 验证会话 → 注入用户信息
|
||||
// 验证失败 → 清除 cookie → 返回 401
|
||||
func (am *AuthMiddleware) Required() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
claims, err := am.authenticateToken(c)
|
||||
if err != nil {
|
||||
common.ClearAuthCookies(c, am.cfg)
|
||||
c.AbortWithStatusJSON(401, gin.H{
|
||||
sid, err := c.Cookie(common.SessionCookieName)
|
||||
if err != nil || sid == "" {
|
||||
common.ClearSessionCookie(c, am.cfg)
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
|
||||
"success": false, "message": "登录已过期,请重新登录",
|
||||
})
|
||||
return
|
||||
}
|
||||
injectUserContext(c, claims)
|
||||
|
||||
s, err := am.sessionManager.Validate(sid)
|
||||
if err != nil || s == nil {
|
||||
common.ClearSessionCookie(c, am.cfg)
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
|
||||
"success": false, "message": "登录已过期,请重新登录",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
injectSessionContext(c, s)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// Optional 可选认证:已登录且版本通过则注入,未登录或版本不匹配也放行
|
||||
// Optional 可选认证:已登录则注入用户信息,未登录也放行
|
||||
func (am *AuthMiddleware) Optional() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
claims, err := am.authenticateToken(c)
|
||||
if err != nil {
|
||||
sid, err := c.Cookie(common.SessionCookieName)
|
||||
if err != nil || sid == "" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
injectUserContext(c, claims)
|
||||
|
||||
s, err := am.sessionManager.Validate(sid)
|
||||
if err != nil || s == nil {
|
||||
common.ClearSessionCookie(c, am.cfg)
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
injectSessionContext(c, s)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// injectSessionContext 将会话中的用户信息注入 gin context
|
||||
func injectSessionContext(c *gin.Context, s *session.Session) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
c.Set("uid", s.UserID)
|
||||
c.Set("email", s.Email)
|
||||
c.Set("username", s.Username)
|
||||
c.Set("role", s.Role)
|
||||
}
|
||||
|
||||
@ -12,16 +12,25 @@ import (
|
||||
// AdminAuth 管理后台页面认证:失败时 302 跳首页而非返回 JSON
|
||||
func (am *AuthMiddleware) AdminAuth() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
claims, err := am.authenticateToken(c)
|
||||
if err != nil {
|
||||
log.Printf("[AdminAuth] auth failed path=%s err=%v → 302", c.Request.URL.Path, err)
|
||||
common.ClearAuthCookies(c, am.cfg)
|
||||
sid, err := c.Cookie(common.SessionCookieName)
|
||||
if err != nil || sid == "" {
|
||||
common.ClearSessionCookie(c, am.cfg)
|
||||
c.Redirect(http.StatusFound, "/")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
log.Printf("[AdminAuth] OK: uid=%v role=%v path=%s", claims["uid"], claims["role"], c.Request.URL.Path)
|
||||
injectUserContext(c, claims)
|
||||
|
||||
s, err := am.sessionManager.Validate(sid)
|
||||
if err != nil || s == nil {
|
||||
log.Printf("[AdminAuth] session invalid path=%s → 302", c.Request.URL.Path)
|
||||
common.ClearSessionCookie(c, am.cfg)
|
||||
c.Redirect(http.StatusFound, "/")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("[AdminAuth] OK uid=%d role=%s path=%s", s.UserID, s.Role, c.Request.URL.Path)
|
||||
injectSessionContext(c, s)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,46 +1,3 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// parseToken 解析并验证 JWT
|
||||
func parseToken(tokenStr, secret string) (jwt.MapClaims, error) {
|
||||
now := time.Now()
|
||||
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
|
||||
return []byte(secret), nil
|
||||
})
|
||||
if err != nil || !token.Valid {
|
||||
log.Printf("[parseToken] FAIL: now=%v err=%v (secret_len=%d token_len=%d)",
|
||||
now, err, len(secret), len(tokenStr))
|
||||
return nil, err
|
||||
}
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return nil, jwt.ErrSignatureInvalid
|
||||
}
|
||||
if exp, exists := claims["exp"]; exists {
|
||||
var expTime time.Time
|
||||
switch v := exp.(type) {
|
||||
case float64:
|
||||
expTime = time.Unix(int64(v), 0)
|
||||
case *jwt.NumericDate:
|
||||
expTime = v.Time
|
||||
}
|
||||
if !expTime.IsZero() {
|
||||
log.Printf("[parseToken] OK: exp=%v (%d) now=%v isExpired=%v",
|
||||
expTime, expTime.Unix(), now, now.After(expTime))
|
||||
}
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
// IsLoginPage 检查是否已在登录状态,已登录用户跳过登录/注册页
|
||||
func IsLoginPage(c *gin.Context) bool {
|
||||
return strings.HasPrefix(c.Request.URL.Path, "/auth/")
|
||||
}
|
||||
// auth_parser.go: JWT 解析逻辑已被服务端 Session 替换,本文件保留占位,后续清理。
|
||||
|
||||
@ -1,48 +1,3 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// authenticateToken 统一的认证核心流程:读 Cookie → 解析 JWT → 检查 token_version
|
||||
func (am *AuthMiddleware) authenticateToken(c *gin.Context) (jwt.MapClaims, error) {
|
||||
tokenStr, err := c.Cookie(common.CookieName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
claims, err := parseToken(tokenStr, am.cfg.JWT.Secret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
uid := uint(claims["uid"].(float64))
|
||||
tokenVer := int(claims["ver"].(float64))
|
||||
currentVer, err := am.userRepo.FindTokenVersion(uid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if tokenVer != currentVer {
|
||||
log.Printf("[authenticateToken] REVOKED: uid=%d tokenVer=%d dbVer=%d", uid, tokenVer, currentVer)
|
||||
return nil, common.ErrTokenRevoked
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
// injectUserContext 将 JWT claims 中的用户信息注入 gin context
|
||||
func injectUserContext(c *gin.Context, claims jwt.MapClaims) {
|
||||
if claims == nil {
|
||||
return
|
||||
}
|
||||
uid, ok := claims["uid"].(float64)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
c.Set("uid", uint(uid))
|
||||
c.Set("email", claims["email"])
|
||||
c.Set("username", claims["username"])
|
||||
c.Set("role", claims["role"])
|
||||
}
|
||||
// auth_token.go: JWT 解析逻辑已被服务端 Session 替换,本文件保留占位,后续清理。
|
||||
|
||||
@ -26,7 +26,7 @@ func SetCSRFToken(c *gin.Context, cfg *config.Config) string {
|
||||
}
|
||||
|
||||
c.SetSameSite(http.SameSiteStrictMode)
|
||||
maxAge := int(cfg.JWT.RememberExpire * 3600)
|
||||
maxAge := cfg.Session.RememberTimeout * 60
|
||||
c.SetCookie(csrfCookieName, token, maxAge, "/", "", secure, false)
|
||||
c.Set(csrfMetaName, token)
|
||||
return token
|
||||
|
||||
@ -7,19 +7,21 @@ import (
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/config"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
"metazone.cc/metalab/internal/session"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// MaintenanceMiddleware 维护模式中间件:维护期间仅站长(Owner)可访问
|
||||
type MaintenanceMiddleware struct {
|
||||
cfg *config.Config
|
||||
siteSettings *config.SiteSettings
|
||||
cfg *config.Config
|
||||
siteSettings *config.SiteSettings
|
||||
sessionManager *session.Manager
|
||||
}
|
||||
|
||||
// NewMaintenanceMiddleware 构造函数
|
||||
func NewMaintenanceMiddleware(cfg *config.Config, siteSettings *config.SiteSettings) *MaintenanceMiddleware {
|
||||
return &MaintenanceMiddleware{cfg: cfg, siteSettings: siteSettings}
|
||||
func NewMaintenanceMiddleware(cfg *config.Config, siteSettings *config.SiteSettings, sm *session.Manager) *MaintenanceMiddleware {
|
||||
return &MaintenanceMiddleware{cfg: cfg, siteSettings: siteSettings, sessionManager: sm}
|
||||
}
|
||||
|
||||
// Handler 返回 Gin 中间件处理函数
|
||||
@ -39,51 +41,43 @@ func (mm *MaintenanceMiddleware) Handler() gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
// 尝试读取 token 并解析角色
|
||||
tokenStr, err := c.Cookie(common.CookieName)
|
||||
if err != nil {
|
||||
// 未登录 → 重定向到登录页(API 返回 403)
|
||||
// 读取 session cookie 并验证
|
||||
sid, err := c.Cookie(common.SessionCookieName)
|
||||
if err != nil || sid == "" {
|
||||
blockAccess(c, path)
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := parseToken(tokenStr, mm.cfg.JWT.Secret)
|
||||
if err != nil {
|
||||
s, err := mm.sessionManager.Validate(sid)
|
||||
if err != nil || s == nil {
|
||||
blockAccess(c, path)
|
||||
return
|
||||
}
|
||||
|
||||
role, _ := claims["role"].(string)
|
||||
if !model.HasMinRole(role, model.RoleOwner) {
|
||||
if !model.HasMinRole(s.Role, model.RoleOwner) {
|
||||
blockAccess(c, path)
|
||||
return
|
||||
}
|
||||
|
||||
// 注入用户信息到 context(后续 auth 中间件可能还需要)
|
||||
injectUserContext(c, claims)
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// isMaintenanceWhitelist 判断路径是否在维护白名单中
|
||||
func isMaintenanceWhitelist(path string) bool {
|
||||
// 登录页面和认证 API
|
||||
if path == "/auth/login" || strings.HasPrefix(path, "/api/auth/") {
|
||||
return true
|
||||
}
|
||||
// 静态资源
|
||||
if strings.HasPrefix(path, "/static/") || strings.HasPrefix(path, "/shared/") {
|
||||
return true
|
||||
}
|
||||
// favicon
|
||||
if path == "/favicon.ico" || path == "/favicon.svg" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// blockAccess 根据请求类型阻止访问(页面重定向,API 返回 403 JSON)
|
||||
// blockAccess 根据请求类型阻止访问
|
||||
func blockAccess(c *gin.Context, path string) {
|
||||
if strings.HasPrefix(path, "/api/") || strings.HasPrefix(path, "/admin/api/") {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
package middleware
|
||||
|
||||
// tokenVersionStore 最小接口:仅暴露 AuthMiddleware 需要的 1 个方法
|
||||
// tokenVersionStore 最小接口:AuthMiddleware 不再需要此接口(session 替换 JWT)
|
||||
// 保留占位,待后续清理
|
||||
type tokenVersionStore interface {
|
||||
FindTokenVersion(userID uint) (int, error)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user