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:
104
internal/session/manager.go
Normal file
104
internal/session/manager.go
Normal file
@ -0,0 +1,104 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"metazone.cc/metalab/internal/config"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
)
|
||||
|
||||
// userStore SessionManager 对 UserRepo 的最小接口(ISP:1 个方法)
|
||||
type userStore interface {
|
||||
FindByIDForAuth(userID uint) (*model.User, error)
|
||||
}
|
||||
|
||||
// Manager 会话管理器:创建、验证、销毁、续期
|
||||
type Manager struct {
|
||||
store Store
|
||||
userRepo userStore
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
// NewManager 构造函数
|
||||
func NewManager(store Store, userRepo userStore, cfg *config.Config) *Manager {
|
||||
return &Manager{store: store, userRepo: userRepo, cfg: cfg}
|
||||
}
|
||||
|
||||
// Create 创建会话并写入存储
|
||||
func (m *Manager) Create(user *model.User, rememberMe bool) (string, error) {
|
||||
sid, err := NewID()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
now := time.Now()
|
||||
s := &Session{
|
||||
ID: sid,
|
||||
UserID: user.ID,
|
||||
Email: user.Email,
|
||||
Username: user.Username,
|
||||
Role: user.Role,
|
||||
RememberMe: rememberMe,
|
||||
CreatedAt: now,
|
||||
LastAccess: now,
|
||||
}
|
||||
if err := m.store.Set(s); err != nil {
|
||||
return "", err
|
||||
}
|
||||
log.Printf("[SessionManager] Created sid=%s uid=%d rememberMe=%v", sid[:16]+"...", user.ID, rememberMe)
|
||||
return sid, nil
|
||||
}
|
||||
|
||||
// Validate 验证会话:读取 → 检查过期 → 检查用户状态 → 续期 → 返回
|
||||
// 返回 nil 表示会话无效(不存在/过期/用户被封禁)
|
||||
func (m *Manager) Validate(sid string) (*Session, error) {
|
||||
if sid == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
s, err := m.store.Get(sid)
|
||||
if err != nil || s == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// 检查用户是否仍然有效(封禁/注销后拒绝已有会话)
|
||||
user, err := m.userRepo.FindByIDForAuth(s.UserID)
|
||||
if err != nil {
|
||||
log.Printf("[SessionManager] Validate: user not found uid=%d err=%v", s.UserID, err)
|
||||
m.store.Delete(sid)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// 封禁用户直接拒绝
|
||||
if user.Status == model.StatusBanned {
|
||||
log.Printf("[SessionManager] Validate: user banned uid=%d", s.UserID)
|
||||
m.store.Delete(sid)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// 滑动窗口续期
|
||||
s.Touch()
|
||||
if err := m.store.Set(s); err != nil {
|
||||
log.Printf("[SessionManager] Validate: touch failed sid=%s err=%v", sid[:16]+"...", err)
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Destroy 销毁单个会话(用户主动退出登录)
|
||||
func (m *Manager) Destroy(sid string) error {
|
||||
return m.store.Delete(sid)
|
||||
}
|
||||
|
||||
// DestroyByUID 销毁某用户的所有会话(改密/注销/强制下线)
|
||||
func (m *Manager) DestroyByUID(uid uint) error {
|
||||
return m.store.DeleteByUID(uid)
|
||||
}
|
||||
|
||||
// IdleTimeout 根据 rememberMe 返回对应的空闲超时时间
|
||||
func (m *Manager) IdleTimeout(rememberMe bool) time.Duration {
|
||||
if rememberMe {
|
||||
return time.Duration(m.cfg.Session.RememberTimeout) * time.Minute
|
||||
}
|
||||
return time.Duration(m.cfg.Session.IdleTimeout) * time.Minute
|
||||
}
|
||||
143
internal/session/memory_store.go
Normal file
143
internal/session/memory_store.go
Normal file
@ -0,0 +1,143 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// MemoryStore 基于内存的会话存储(sync.Map + RWMutex,适合单实例部署)
|
||||
type MemoryStore struct {
|
||||
mu sync.RWMutex
|
||||
sessions map[string]*Session // sid → session
|
||||
byUID map[uint][]string // uid → []sid(用于批量删除)
|
||||
idleTimeout time.Duration // 不记住我:空闲超时
|
||||
rememberTimeout time.Duration // 记住我:空闲超时
|
||||
}
|
||||
|
||||
// NewMemoryStore 创建内存存储实例
|
||||
func NewMemoryStore(idleTimeout, rememberTimeout time.Duration) *MemoryStore {
|
||||
return &MemoryStore{
|
||||
sessions: make(map[string]*Session),
|
||||
byUID: make(map[uint][]string),
|
||||
idleTimeout: idleTimeout,
|
||||
rememberTimeout: rememberTimeout,
|
||||
}
|
||||
}
|
||||
|
||||
// Get 获取会话(根据 RememberMe 选择对应的空闲超时检查过期)
|
||||
func (ms *MemoryStore) Get(id string) (*Session, error) {
|
||||
ms.mu.RLock()
|
||||
s, ok := ms.sessions[id]
|
||||
ms.mu.RUnlock()
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
// 记住我 → 使用更长的超时
|
||||
timeout := ms.idleTimeout
|
||||
if s.RememberMe {
|
||||
timeout = ms.rememberTimeout
|
||||
}
|
||||
if s.IsExpired(timeout) {
|
||||
ms.Delete(id)
|
||||
return nil, nil
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Set 写入会话(同步更新 byUID 索引)
|
||||
func (ms *MemoryStore) Set(s *Session) error {
|
||||
ms.mu.Lock()
|
||||
defer ms.mu.Unlock()
|
||||
|
||||
// 如果 sid 已存在且 uid 不同,先从旧 uid 索引移除
|
||||
if old, ok := ms.sessions[s.ID]; ok && old.UserID != s.UserID {
|
||||
ms.removeFromUIDIndex(old.UserID, s.ID)
|
||||
}
|
||||
|
||||
ms.sessions[s.ID] = s
|
||||
ms.byUID[s.UserID] = append(ms.byUID[s.UserID], s.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete 删除会话(同步更新 byUID 索引)
|
||||
func (ms *MemoryStore) Delete(id string) error {
|
||||
ms.mu.Lock()
|
||||
defer ms.mu.Unlock()
|
||||
|
||||
s, ok := ms.sessions[id]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
ms.removeFromUIDIndex(s.UserID, id)
|
||||
delete(ms.sessions, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteByUID 删除某用户的所有会话
|
||||
func (ms *MemoryStore) DeleteByUID(uid uint) error {
|
||||
ms.mu.Lock()
|
||||
defer ms.mu.Unlock()
|
||||
|
||||
sids, ok := ms.byUID[uid]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
for _, sid := range sids {
|
||||
delete(ms.sessions, sid)
|
||||
}
|
||||
delete(ms.byUID, uid)
|
||||
log.Printf("[MemoryStore] DeleteByUID uid=%d count=%d", uid, len(sids))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Cleanup 清理过期会话(根据 RememberMe 选择对应超时)
|
||||
func (ms *MemoryStore) Cleanup() int {
|
||||
ms.mu.Lock()
|
||||
defer ms.mu.Unlock()
|
||||
|
||||
var expiredSids []string
|
||||
for sid, s := range ms.sessions {
|
||||
timeout := ms.idleTimeout
|
||||
if s.RememberMe {
|
||||
timeout = ms.rememberTimeout
|
||||
}
|
||||
if s.IsExpired(timeout) {
|
||||
expiredSids = append(expiredSids, sid)
|
||||
}
|
||||
}
|
||||
for _, sid := range expiredSids {
|
||||
s := ms.sessions[sid]
|
||||
ms.removeFromUIDIndex(s.UserID, sid)
|
||||
delete(ms.sessions, sid)
|
||||
}
|
||||
if len(expiredSids) > 0 {
|
||||
log.Printf("[MemoryStore] Cleanup removed=%d remaining=%d", len(expiredSids), len(ms.sessions))
|
||||
}
|
||||
return len(expiredSids)
|
||||
}
|
||||
|
||||
// removeFromUIDIndex 从 byUID 索引中移除指定 sid(调用者需持有写锁)
|
||||
func (ms *MemoryStore) removeFromUIDIndex(uid uint, sid string) {
|
||||
sids := ms.byUID[uid]
|
||||
for i, s := range sids {
|
||||
if s == sid {
|
||||
ms.byUID[uid] = append(sids[:i], sids[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(ms.byUID[uid]) == 0 {
|
||||
delete(ms.byUID, uid)
|
||||
}
|
||||
}
|
||||
|
||||
// StartCleanup 启动后台清理 goroutine(应在 main 中调用)
|
||||
func (ms *MemoryStore) StartCleanup(interval time.Duration) {
|
||||
go func() {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
ms.Cleanup()
|
||||
}
|
||||
}()
|
||||
}
|
||||
29
internal/session/redis_store.go
Normal file
29
internal/session/redis_store.go
Normal file
@ -0,0 +1,29 @@
|
||||
package session
|
||||
|
||||
// RedisStore Redis 会话存储(预留实现,切换到 Redis 时启用)
|
||||
// import "github.com/redis/go-redis/v9"
|
||||
//
|
||||
// type RedisStore struct {
|
||||
// client *redis.Client
|
||||
// ttl time.Duration
|
||||
// }
|
||||
//
|
||||
// func NewRedisStore(client *redis.Client, ttl time.Duration) *RedisStore {
|
||||
// return &RedisStore{client: client, ttl: ttl}
|
||||
// }
|
||||
//
|
||||
// func (rs *RedisStore) Get(id string) (*Session, error) { ... }
|
||||
// func (rs *RedisStore) Set(s *Session) error { ... }
|
||||
// func (rs *RedisStore) Delete(id string) error { ... }
|
||||
// func (rs *RedisStore) DeleteByUID(uid uint) error { ... }
|
||||
// func (rs *RedisStore) Cleanup() int { return 0 }
|
||||
//
|
||||
// Redis key pattern:
|
||||
// session:{sid} → serialized Session (TTL = idle timeout)
|
||||
// user_sessions:{uid} → Set of sids (for batch deletion)
|
||||
|
||||
// 当前使用内存存储,Redis 支持预留接口,未来需切换时:
|
||||
// 1. go get github.com/redis/go-redis/v9
|
||||
// 2. 取消本文件注释并实现 RedisStore
|
||||
// 3. 在 deps_core.go 中将 NewMemoryStore → NewRedisStore
|
||||
// 4. 注入 redis client(从 config 读取 Redis 连接信息)
|
||||
38
internal/session/session.go
Normal file
38
internal/session/session.go
Normal file
@ -0,0 +1,38 @@
|
||||
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
|
||||
}
|
||||
19
internal/session/store.go
Normal file
19
internal/session/store.go
Normal file
@ -0,0 +1,19 @@
|
||||
package session
|
||||
|
||||
// Store 会话存储接口(内存实现 / Redis 实现均实现此接口)
|
||||
type Store interface {
|
||||
// Get 按会话 ID 获取会话,不存在或已过期返回 nil
|
||||
Get(id string) (*Session, error)
|
||||
|
||||
// Set 写入/更新会话
|
||||
Set(s *Session) error
|
||||
|
||||
// Delete 删除单个会话
|
||||
Delete(id string) error
|
||||
|
||||
// DeleteByUID 删除某用户的所有会话(改密/注销/强制下线时调用)
|
||||
DeleteByUID(uid uint) error
|
||||
|
||||
// Cleanup 清理过期会话,返回清理数量(由后台 goroutine 定期调用)
|
||||
Cleanup() int
|
||||
}
|
||||
Reference in New Issue
Block a user