This repository has been archived on 2026-06-21. You can view files and clone it, but cannot push or open issues or pull requests.
Files
MetaLab/internal/session/session.go
Victor_Jay daf87f895b 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 到期字段依赖
2026-05-30 23:36:52 +08:00

39 lines
980 B
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 session
import (
"crypto/rand"
"encoding/hex"
"time"
)
// Session 服务端会话,替代 JWT 无状态令牌
type Session struct {
ID string // 会话唯一标识64 位 hex
UserID uint // 用户 ID
Email string // 邮箱
Username string // 用户名
Role string // 角色
RememberMe bool // 是否持久化(决定 cookie maxAge
CreatedAt time.Time // 创建时间
LastAccess time.Time // 最后访问时间(滑动窗口)
}
// IsExpired 检查会话是否已过期
func (s *Session) IsExpired(idleTimeout time.Duration) bool {
return time.Since(s.LastAccess) > idleTimeout
}
// Touch 更新最后访问时间(续期)
func (s *Session) Touch() {
s.LastAccess = time.Now()
}
// NewID 生成 32 字节随机 hex 字符串作为会话 ID
func NewID() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}