fix: 前后台 Token Redis 存储隔离,修复同账号互相覆盖问题

核心变更:
- Redis key 加入 clientType 前缀:echo:auth:token:{frontend|admin}:{user_id}
- JWT Claims 新增 client_type 字段区分前台/管理端
- 新增 constants/client_type.go 定义 ClientTypeFrontend / ClientTypeAdmin
- 全链路传递 clientType:Controller → Service → TokenStore → Redis
- 中间件从 JWT Claims 提取 clientType 做 Redis 校验
- 登出只删除当前端 Token,不影响另一端

前端变更:
- 管理端 login API 改为调用 POST /api/v1/admin/auth/login(之前错误调用了前台接口)

文档更新:
- 系统设计文档、实施计划、API文档、开发规范、项目进度全部同步

Made-with: Cursor
This commit is contained in:
bujinyuan
2026-03-02 14:28:45 +08:00
parent cfb1651480
commit c3e8600b24
13 changed files with 206 additions and 76 deletions

View File

@@ -12,15 +12,16 @@ import (
)
const (
ContextKeyUserID = "user_id" // Context 中存储当前用户 ID 的 Key
ContextKeyUsername = "username" // Context 中存储当前用户名的 Key
ContextKeyRoles = "roles" // Context 中存储当前用户角色列表的 Key
ContextKeyUserID = "user_id" // Context 中存储当前用户 ID 的 Key
ContextKeyUsername = "username" // Context 中存储当前用户名的 Key
ContextKeyRoles = "roles" // Context 中存储当前用户角色列表的 Key
ContextKeyClientType = "client_type" // Context 中存储客户端类型的 Keyfrontend / admin
)
// TokenValidator Token 有效性校验接口
// 由 AuthService 实现,中间件通过此接口检查 Token 是否在 Redis 中有效
type TokenValidator interface {
ValidateAccessToken(ctx context.Context, userID int64, token string) bool
ValidateAccessToken(ctx context.Context, userID int64, clientType, token string) bool
}
// JWTAuth JWT 认证中间件(有状态 JWT
@@ -62,10 +63,17 @@ func JWTAuth(jwtCfg *config.JWTConfig, validator TokenValidator) gin.HandlerFunc
return
}
// 校验 Token 是否在 Redis 中有效(有状态 JWT 核心逻辑
if !validator.ValidateAccessToken(ctx, claims.UserID, tokenStr) {
// 从 Claims 获取 clientType兼容旧 Token 无该字段的情况
clientType := claims.ClientType
if clientType == "" {
clientType = "frontend"
}
// 校验 Token 是否在 Redis 中有效(有状态 JWT 核心逻辑,按 clientType 隔离)
if !validator.ValidateAccessToken(ctx, claims.UserID, clientType, tokenStr) {
logs.Warn(ctx, funcName, "Token 已失效(已登出或被覆盖)",
zap.Int64("user_id", claims.UserID),
zap.String("client_type", clientType),
zap.String("ip", c.ClientIP()),
)
utils.ResponseUnauthorized(c, "认证已失效,请重新登录")
@@ -76,6 +84,7 @@ func JWTAuth(jwtCfg *config.JWTConfig, validator TokenValidator) gin.HandlerFunc
c.Set(ContextKeyUserID, claims.UserID)
c.Set(ContextKeyUsername, claims.Username)
c.Set(ContextKeyRoles, claims.Roles)
c.Set(ContextKeyClientType, clientType)
c.Next()
}
@@ -141,3 +150,16 @@ func GetCurrentUsername(c *gin.Context) (string, bool) {
username, ok := val.(string)
return username, ok
}
// GetCurrentClientType 从 Gin Context 获取当前客户端类型frontend / admin
func GetCurrentClientType(c *gin.Context) string {
val, exists := c.Get(ContextKeyClientType)
if !exists {
return "frontend"
}
clientType, ok := val.(string)
if !ok {
return "frontend"
}
return clientType
}