package utils import ( "backend/internal/model" "time" "github.com/gin-gonic/gin" "gorm.io/gorm" ) // LogAction 记录操作日志(成功) // Logan.Li func LogAction(db *gorm.DB, c *gin.Context, action, targetType string, targetID uint, targetName, oldData, newData, detail string) { logEntry := model.AuditLog{ Action: action, TargetType: targetType, TargetID: targetID, TargetName: targetName, OldData: oldData, NewData: newData, Detail: detail, Result: "success", IP: c.ClientIP(), CreatedAt: time.Now(), } // 从上下文中获取操作人信息(管理后台调用时存在) // Logan.Li if c != nil { if userID, exists := c.Get("user_id"); exists { if id, ok := userID.(uint); ok { logEntry.UserID = id } } if username, exists := c.Get("username"); exists { if name, ok := username.(string); ok { logEntry.Username = name } } } db.Create(&logEntry) } // LogSystemAction 记录系统操作日志(无 HTTP 上下文,如支付回调) // Logan.Li func LogSystemAction(db *gorm.DB, action, targetType string, targetID uint, targetName, detail, ip string) { db.Create(&model.AuditLog{ UserID: 0, Username: "system", Action: action, TargetType: targetType, TargetID: targetID, TargetName: targetName, Detail: detail, Result: "success", IP: ip, CreatedAt: time.Now(), }) } // GetClientIP 获取客户端真实 IP(兼容代理) // Logan.Li func GetClientIP(c *gin.Context) string { return c.ClientIP() } // LogAuthAction 记录认证类日志(登录成功/失败/锁定),登录前无用户上下文,显式传用户名 // Logan.Li func LogAuthAction(db *gorm.DB, c *gin.Context, action, username, detail, result string) { db.Create(&model.AuditLog{ Username: username, Action: action, TargetType: "user", TargetName: username, Detail: detail, Result: result, IP: c.ClientIP(), CreatedAt: time.Now(), }) }