Files
opsxsql/backend/internal/middleware/auth.go
T
logan bc2092a980 feat: 平台配置全面生效 — 配置策略接入实际逻辑
- query组: ExecuteQuery读取query_limit_max/query_timeout/query_dangerous_pattern
  - 查询超时通过context.WithTimeout生效,db.QueryContext/QueryRowContext
  - 危险模式检测拦截无WHERE的DELETE/UPDATE/DROP/TRUNCATE
  - LIMIT上限从settings读取,不再硬编码1000

- security组: Login读取login_max_attempts/login_lockout_minutes
  - 新增User字段: failed_login_attempts + locked_until
  - 登录失败达到阈值自动锁定,成功时清除计数
  - JWT Token过期时间读取session_timeout_hours设置

- executor组: ExecuteTicket读取executor_timeout/executor_dry_run
  - 执行超时通过context.WithTimeout控制
  - 开启dry_run时先EXPLAIN预检查SQL语法
  - db.ExecContext替代db.Exec

- cleanup组: SettingsCleanupPreview/Run从占位改为真实实现
  - 预览统计4类数据(工单/查询历史/慢日志/审计日志)待清理数量
  - 执行清理按retention_days配置删除过期数据

- ghost组: 13项gh-ost配置加入seedDefaultSettings
  - enabled/path/mode/osc_priority/env/cloud/trigger/chunk/load/lag等
  - 已被ghost.go中getGhostConfig等函数读取

- 前端: PlatformConfigPage新增Ghost/OSC分组显示
2026-06-01 01:00:23 +08:00

108 lines
2.6 KiB
Go

package middleware
import (
"net/http"
"strconv"
"strings"
"time"
"sql-platform/config"
"sql-platform/internal/model"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
// getSessionTimeoutHours reads session_timeout_hours from system_settings,
// falls back to config/env, then default 24h.
func getSessionTimeoutHours() int {
var s model.SystemSetting
if model.DB.Where("`key` = ?", "session_timeout_hours").Take(&s).Error == nil {
if v, err := strconv.Atoi(s.Value); err == nil && v > 0 {
return v
}
}
if config.C.JWTExpire > 0 {
return config.C.JWTExpire
}
return 24
}
type Claims struct {
UserID int `json:"user_id"`
Username string `json:"username"`
Role string `json:"role"`
jwt.RegisteredClaims
}
func GenerateToken(user *model.User) (string, error) {
claims := Claims{
UserID: user.ID,
Username: user.Username,
Role: user.Role,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(getSessionTimeoutHours()) * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(config.C.JWTSecret))
}
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{"detail": "Not authenticated"})
c.Abort()
return
}
tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
if tokenStr == authHeader {
c.JSON(http.StatusUnauthorized, gin.H{"detail": "Invalid token format"})
c.Abort()
return
}
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(config.C.JWTSecret), nil
})
if err != nil || !token.Valid {
c.JSON(http.StatusUnauthorized, gin.H{"detail": "Invalid or expired token"})
c.Abort()
return
}
c.Set("user_id", claims.UserID)
c.Set("username", claims.Username)
c.Set("role", claims.Role)
c.Next()
}
}
func GetCurrentUser(c *gin.Context) (int, string, string) {
return c.GetInt("user_id"), c.GetString("username"), c.GetString("role")
}
// RBAC middleware — allow specified roles (superadmin is treated as admin)
func RequireRole(roles ...string) gin.HandlerFunc {
roleSet := make(map[string]bool)
for _, r := range roles {
roleSet[r] = true
}
// superadmin inherits all admin privileges
roleSet["superadmin"] = true
return func(c *gin.Context) {
role := c.GetString("role")
if !roleSet[role] {
c.JSON(http.StatusForbidden, gin.H{"detail": "Permission denied"})
c.Abort()
return
}
c.Next()
}
}