From ea9cc3cbe4c57ca8b02d3e679038f4fed65495f6 Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Sat, 27 Sep 2025 23:17:23 +0800 Subject: [PATCH 01/13] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E7=99=BB=E5=BD=95?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C=E4=B8=AD=E9=97=B4=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/app/api/api.go | 73 +++++++++++++++++---------------- internal/app/middleware/auth.go | 50 ++++++++++++++++++++++ 2 files changed, 88 insertions(+), 35 deletions(-) create mode 100644 internal/app/middleware/auth.go diff --git a/internal/app/api/api.go b/internal/app/api/api.go index 6d2dbf9..d7a051d 100644 --- a/internal/app/api/api.go +++ b/internal/app/api/api.go @@ -15,18 +15,19 @@ import ( "net/http/pprof" "time" + _ "git.huangwc.com/pig/pig-farm-controller/docs" // 引入 swag 生成的 docs "git.huangwc.com/pig/pig-farm-controller/internal/app/controller/device" "git.huangwc.com/pig/pig-farm-controller/internal/app/controller/plan" "git.huangwc.com/pig/pig-farm-controller/internal/app/controller/user" + "git.huangwc.com/pig/pig-farm-controller/internal/app/middleware" "git.huangwc.com/pig/pig-farm-controller/internal/app/service/task" "git.huangwc.com/pig/pig-farm-controller/internal/app/service/token" "git.huangwc.com/pig/pig-farm-controller/internal/app/service/transport" "git.huangwc.com/pig/pig-farm-controller/internal/infra/config" "git.huangwc.com/pig/pig-farm-controller/internal/infra/logs" "git.huangwc.com/pig/pig-farm-controller/internal/infra/repository" - "github.com/gin-gonic/gin" - _ "git.huangwc.com/pig/pig-farm-controller/docs" // 引入 swag 生成的 docs + "github.com/gin-gonic/gin" swaggerFiles "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" ) @@ -91,41 +92,14 @@ func NewAPI(cfg config.ServerConfig, // setupRoutes 设置所有 API 路由 // 在此方法中,使用已初始化的控制器实例将其路由注册到 Gin 引擎中。 func (a *API) setupRoutes() { - // 创建 /api/v1 路由组 - v1 := a.engine.Group("/api/v1") - { - // 用户相关路由组 - userGroup := v1.Group("/users") - { - userGroup.POST("", a.userController.CreateUser) // 注册创建用户接口 (POST /api/v1/users) - userGroup.POST("/login", a.userController.Login) // 注册用户登录接口 (POST /api/v1/users/login) - } - a.logger.Info("用户相关接口注册成功") - // 设备相关路由组 - deviceGroup := v1.Group("/devices") - { - deviceGroup.POST("", a.deviceController.CreateDevice) - deviceGroup.GET("", a.deviceController.ListDevices) - deviceGroup.GET("/:id", a.deviceController.GetDevice) - deviceGroup.PUT("/:id", a.deviceController.UpdateDevice) - deviceGroup.DELETE("/:id", a.deviceController.DeleteDevice) - } - a.logger.Info("设备相关接口注册成功") + // --- Public Routes --- + // 这些路由不需要身份验证 - // 计划相关路由组 - planGroup := v1.Group("/plans") - { - planGroup.POST("", a.planController.CreatePlan) - planGroup.GET("", a.planController.ListPlans) - planGroup.GET("/:id", a.planController.GetPlan) - planGroup.PUT("/:id", a.planController.UpdatePlan) - planGroup.DELETE("/:id", a.planController.DeletePlan) - planGroup.POST("/:id/start", a.planController.StartPlan) - planGroup.POST("/:id/stop", a.planController.StopPlan) - } - a.logger.Info("计划相关接口注册成功") - } + // 用户注册和登录 + a.engine.POST("/api/v1/users", a.userController.CreateUser) + a.engine.POST("/api/v1/users/login", a.userController.Login) + a.logger.Info("公开接口注册成功:用户注册、登录") // 注册 pprof 路由 pprofGroup := a.engine.Group("/debug/pprof") @@ -156,6 +130,35 @@ func (a *API) setupRoutes() { a.engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) a.logger.Info("Swagger UI 接口注册成功") + // --- Authenticated Routes --- + // 所有在此注册的路由都需要通过 JWT 身份验证 + authGroup := a.engine.Group("/api/v1") + authGroup.Use(middleware.AuthMiddleware(a.tokenService)) + { + // 设备相关路由组 + deviceGroup := authGroup.Group("/devices") + { + deviceGroup.POST("", a.deviceController.CreateDevice) + deviceGroup.GET("", a.deviceController.ListDevices) + deviceGroup.GET("/:id", a.deviceController.GetDevice) + deviceGroup.PUT("/:id", a.deviceController.UpdateDevice) + deviceGroup.DELETE("/:id", a.deviceController.DeleteDevice) + } + a.logger.Info("设备相关接口注册成功 (需要认证)") + + // 计划相关路由组 + planGroup := authGroup.Group("/plans") + { + planGroup.POST("", a.planController.CreatePlan) + planGroup.GET("", a.planController.ListPlans) + planGroup.GET("/:id", a.planController.GetPlan) + planGroup.PUT("/:id", a.planController.UpdatePlan) + planGroup.DELETE("/:id", a.planController.DeletePlan) + planGroup.POST("/:id/start", a.planController.StartPlan) + planGroup.POST("/:id/stop", a.planController.StopPlan) + } + a.logger.Info("计划相关接口注册成功 (需要认证)") + } } // Start 启动 HTTP 服务器 diff --git a/internal/app/middleware/auth.go b/internal/app/middleware/auth.go new file mode 100644 index 0000000..5d97fa1 --- /dev/null +++ b/internal/app/middleware/auth.go @@ -0,0 +1,50 @@ +// Package middleware 存放 gin 中间件 +package middleware + +import ( + "net/http" + "strings" + + "git.huangwc.com/pig/pig-farm-controller/internal/app/service/token" + "github.com/gin-gonic/gin" +) + +const ( + // ContextUserIDKey 是存储在 gin.Context 中的用户ID的键名 + ContextUserIDKey = "userID" +) + +// AuthMiddleware 创建一个Gin中间件,用于JWT身份验证 +// 它依赖于 TokenService 来解析和验证 token +func AuthMiddleware(tokenService token.TokenService) gin.HandlerFunc { + return func(c *gin.Context) { + // 从 Authorization header 获取 token + authHeader := c.GetHeader("Authorization") + if authHeader == "" { + c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "请求未包含授权标头"}) + return + } + + // 授权标头的格式应为 "Bearer " + parts := strings.Split(authHeader, " ") + if len(parts) != 2 || parts[0] != "Bearer" { + c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "授权标头格式不正确"}) + return + } + + tokenString := parts[1] + + // 解析和验证 token + claims, err := tokenService.ParseToken(tokenString) + if err != nil { + c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "无效的Token"}) + return + } + + // 将解析出的用户ID存储在 context 中,以便后续的处理函数使用 + c.Set(ContextUserIDKey, claims.UserID) + + // 继续处理请求链中的下一个处理程序 + c.Next() + } +} From 6d9d4ff91ba2f30075bb6fc339ba226f05a442aa Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Sat, 27 Sep 2025 23:22:27 +0800 Subject: [PATCH 02/13] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E7=A4=BE=E4=BA=A4?= =?UTF-8?q?=E4=BF=A1=E6=81=AFmodel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/infra/models/user.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/internal/infra/models/user.go b/internal/infra/models/user.go index 6b42d65..9d94286 100644 --- a/internal/infra/models/user.go +++ b/internal/infra/models/user.go @@ -6,6 +6,15 @@ import ( "gorm.io/gorm" ) +// ContactInfo 存储用户的多种联系方式 +// 使用 jsonb 类型存入数据库 +type ContactInfo struct { + Email string `json:"email,omitempty"` + Phone string `json:"phone,omitempty"` + WeChat string `json:"wechat,omitempty"` + Feishu string `json:"feishu,omitempty"` +} + // User 代表系统中的用户模型 type User struct { // gorm.Model 内嵌了 ID, CreatedAt, UpdatedAt, 和 DeletedAt @@ -19,6 +28,9 @@ type User struct { // Password 存储的是加密后的密码哈希,而不是明文 // json:"-" 标签确保此字段在序列化为 JSON 时被忽略,防止密码泄露 Password string `gorm:"not null" json:"-"` + + // Contact 存储用户的联系方式,以 JSONB 格式存入数据库 + Contact ContactInfo `gorm:"type:jsonb" json:"contact"` } // TableName 自定义 User 模型对应的数据库表名 From b177781fa15a06abc6908bf0a7c78eced0f98606 Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Sat, 27 Sep 2025 23:28:06 +0800 Subject: [PATCH 03/13] =?UTF-8?q?=E6=94=AF=E6=8C=81=E7=94=A8=E6=89=8B?= =?UTF-8?q?=E6=9C=BA=E5=8F=B7=E7=AD=89=E4=BF=A1=E6=81=AF=E4=BB=A3=E6=9B=BF?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E5=90=8D=E7=99=BB=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/app/controller/user/user_controller.go | 14 ++++++++------ internal/infra/repository/user_repository.go | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/internal/app/controller/user/user_controller.go b/internal/app/controller/user/user_controller.go index 14579b5..9e13a17 100644 --- a/internal/app/controller/user/user_controller.go +++ b/internal/app/controller/user/user_controller.go @@ -34,8 +34,9 @@ type CreateUserRequest struct { // LoginRequest 定义登录请求的结构体 type LoginRequest struct { - Username string `json:"username" binding:"required" example:"testuser"` - Password string `json:"password" binding:"required" example:"password123"` + // Identifier 可以是用户名、邮箱、手机号、微信号或飞书账号 + Identifier string `json:"identifier" binding:"required" example:"testuser"` + Password string `json:"password" binding:"required" example:"password123"` } // CreateUserResponse 定义创建用户成功响应的结构体 @@ -96,7 +97,7 @@ func (c *Controller) CreateUser(ctx *gin.Context) { // Login godoc // @Summary 用户登录 -// @Description 用户使用用户名和密码登录,成功后返回 JWT 令牌。 +// @Description 用户可以使用用户名、邮箱、手机号、微信号或飞书账号进行登录,成功后返回 JWT 令牌。 // @Tags 用户管理 // @Accept json // @Produce json @@ -111,10 +112,11 @@ func (c *Controller) Login(ctx *gin.Context) { return } - user, err := c.userRepo.FindByUsername(req.Username) + // 使用新的方法,通过唯一标识符(用户名、邮箱等)查找用户 + user, err := c.userRepo.FindUserForLogin(req.Identifier) if err != nil { if err == gorm.ErrRecordNotFound { - controller.SendErrorResponse(ctx, controller.CodeUnauthorized, "用户名或密码不正确") + controller.SendErrorResponse(ctx, controller.CodeUnauthorized, "登录凭证不正确") return } c.logger.Errorf("登录: 查询用户失败: %v", err) @@ -123,7 +125,7 @@ func (c *Controller) Login(ctx *gin.Context) { } if !user.CheckPassword(req.Password) { - controller.SendErrorResponse(ctx, controller.CodeUnauthorized, "用户名或密码不正确") + controller.SendErrorResponse(ctx, controller.CodeUnauthorized, "登录凭证不正确") return } diff --git a/internal/infra/repository/user_repository.go b/internal/infra/repository/user_repository.go index dcee8fa..8a290cf 100644 --- a/internal/infra/repository/user_repository.go +++ b/internal/infra/repository/user_repository.go @@ -12,6 +12,7 @@ type UserRepository interface { Create(user *models.User) error FindByUsername(username string) (*models.User, error) FindByID(id uint) (*models.User, error) + FindUserForLogin(identifier string) (*models.User, error) } // gormUserRepository 是 UserRepository 的 GORM 实现 @@ -39,6 +40,22 @@ func (r *gormUserRepository) FindByUsername(username string) (*models.User, erro return &user, nil } +// FindUserForLogin 根据提供的标识符查找用户,可用于登录验证 +// 标识符可以是用户名、邮箱、手机号、微信号或飞书账号 +func (r *gormUserRepository) FindUserForLogin(identifier string) (*models.User, error) { + var user models.User + // 使用 ->> 操作符来查询 JSONB 字段中的文本值 + err := r.db.Where( + "username = ? OR contact ->> 'email' = ? OR contact ->> 'phone' = ? OR contact ->> 'wechat' = ? OR contact ->> 'feishu' = ?", + identifier, identifier, identifier, identifier, identifier, + ).First(&user).Error + + if err != nil { + return nil, err + } + return &user, nil +} + // FindByID 根据 ID 查找用户 func (r *gormUserRepository) FindByID(id uint) (*models.User, error) { var user models.User From 1c7e13b9658aaa0f741f54786a7edcd57bbefbfc Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Sun, 28 Sep 2025 00:13:47 +0800 Subject: [PATCH 04/13] =?UTF-8?q?=E5=88=9D=E6=AD=A5=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E5=AE=A1=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/app/api/api.go | 11 ++- internal/app/controller/response.go | 63 +++++++++--- internal/app/middleware/audit.go | 98 +++++++++++++++++++ internal/app/middleware/auth.go | 29 ++++-- internal/app/service/audit/service.go | 83 ++++++++++++++++ internal/core/application.go | 8 ++ internal/infra/database/postgres.go | 2 + internal/infra/models/execution.go | 30 ++++++ .../repository/user_action_log_repository.go | 27 +++++ 9 files changed, 324 insertions(+), 27 deletions(-) create mode 100644 internal/app/middleware/audit.go create mode 100644 internal/app/service/audit/service.go create mode 100644 internal/infra/repository/user_action_log_repository.go diff --git a/internal/app/api/api.go b/internal/app/api/api.go index d7a051d..3fea745 100644 --- a/internal/app/api/api.go +++ b/internal/app/api/api.go @@ -20,6 +20,7 @@ import ( "git.huangwc.com/pig/pig-farm-controller/internal/app/controller/plan" "git.huangwc.com/pig/pig-farm-controller/internal/app/controller/user" "git.huangwc.com/pig/pig-farm-controller/internal/app/middleware" + "git.huangwc.com/pig/pig-farm-controller/internal/app/service/audit" "git.huangwc.com/pig/pig-farm-controller/internal/app/service/task" "git.huangwc.com/pig/pig-farm-controller/internal/app/service/token" "git.huangwc.com/pig/pig-farm-controller/internal/app/service/transport" @@ -38,6 +39,7 @@ type API struct { logger *logs.Logger // 日志记录器,用于输出日志信息 userRepo repository.UserRepository // 用户数据仓库接口,用于用户数据操作 tokenService token.TokenService // Token 服务接口,用于 JWT token 的生成和解析 + auditService audit.Service // 审计服务,用于记录用户操作 httpServer *http.Server // 标准库的 HTTP 服务器实例,用于启动和停止服务 config config.ServerConfig // API 服务器的配置,使用 infra/config 包中的 ServerConfig userController *user.Controller // 用户控制器实例 @@ -55,6 +57,7 @@ func NewAPI(cfg config.ServerConfig, deviceRepository repository.DeviceRepository, planRepository repository.PlanRepository, tokenService token.TokenService, + auditService audit.Service, // 注入审计服务 listenHandler transport.ListenHandler, analysisTaskManager *task.AnalysisPlanTaskManager) *API { // 设置 Gin 模式,例如 gin.ReleaseMode (生产模式) 或 gin.DebugMode (开发模式) @@ -75,6 +78,7 @@ func NewAPI(cfg config.ServerConfig, logger: logger, userRepo: userRepo, tokenService: tokenService, + auditService: auditService, config: cfg, listenHandler: listenHandler, // 在 NewAPI 中初始化用户控制器,并将其作为 API 结构体的成员 @@ -133,7 +137,8 @@ func (a *API) setupRoutes() { // --- Authenticated Routes --- // 所有在此注册的路由都需要通过 JWT 身份验证 authGroup := a.engine.Group("/api/v1") - authGroup.Use(middleware.AuthMiddleware(a.tokenService)) + authGroup.Use(middleware.AuthMiddleware(a.tokenService, a.userRepo)) // 1. 身份认证 + authGroup.Use(middleware.AuditLogMiddleware(a.auditService)) // 2. 审计日志 { // 设备相关路由组 deviceGroup := authGroup.Group("/devices") @@ -144,7 +149,7 @@ func (a *API) setupRoutes() { deviceGroup.PUT("/:id", a.deviceController.UpdateDevice) deviceGroup.DELETE("/:id", a.deviceController.DeleteDevice) } - a.logger.Info("设备相关接口注册成功 (需要认证)") + a.logger.Info("设备相关接口注册成功 (需要认证和审计)") // 计划相关路由组 planGroup := authGroup.Group("/plans") @@ -157,7 +162,7 @@ func (a *API) setupRoutes() { planGroup.POST("/:id/start", a.planController.StartPlan) planGroup.POST("/:id/stop", a.planController.StopPlan) } - a.logger.Info("计划相关接口注册成功 (需要认证)") + a.logger.Info("计划相关接口注册成功 (需要认证和审计)") } } diff --git a/internal/app/controller/response.go b/internal/app/controller/response.go index 136356c..bfcf5b2 100644 --- a/internal/app/controller/response.go +++ b/internal/app/controller/response.go @@ -3,37 +3,40 @@ package controller import ( "net/http" + "git.huangwc.com/pig/pig-farm-controller/internal/app/middleware" "github.com/gin-gonic/gin" ) // --- 业务状态码 --- +type ResponseCode int + const ( // 成功状态码 (2000-2999) - CodeSuccess = 2000 // 操作成功 - CodeCreated = 2001 // 创建成功 + CodeSuccess ResponseCode = 2000 // 操作成功 + CodeCreated ResponseCode = 2001 // 创建成功 // 客户端错误状态码 (4000-4999) - CodeBadRequest = 4000 // 请求参数错误 - CodeUnauthorized = 4001 // 未授权 - CodeNotFound = 4004 // 资源未找到 - CodeConflict = 4009 // 资源冲突 + CodeBadRequest ResponseCode = 4000 // 请求参数错误 + CodeUnauthorized ResponseCode = 4001 // 未授权 + CodeNotFound ResponseCode = 4004 // 资源未找到 + CodeConflict ResponseCode = 4009 // 资源冲突 // 服务器错误状态码 (5000-5999) - CodeInternalError = 5000 // 服务器内部错误 - CodeServiceUnavailable = 5003 // 服务不可用 + CodeInternalError ResponseCode = 5000 // 服务器内部错误 + CodeServiceUnavailable ResponseCode = 5003 // 服务不可用 ) // --- 通用响应结构 --- // Response 定义统一的API响应结构体 type Response struct { - Code int `json:"code"` // 业务状态码 - Message string `json:"message"` // 提示信息 - Data interface{} `json:"data"` // 业务数据 + Code ResponseCode `json:"code"` // 业务状态码 + Message string `json:"message"` // 提示信息 + Data interface{} `json:"data"` // 业务数据 } -// SendResponse 发送统一格式的JSON响应 -func SendResponse(ctx *gin.Context, code int, message string, data interface{}) { +// SendResponse 发送统一格式的JSON响应 (基础函数,不带审计) +func SendResponse(ctx *gin.Context, code ResponseCode, message string, data interface{}) { ctx.JSON(http.StatusOK, Response{ Code: code, Message: message, @@ -41,7 +44,37 @@ func SendResponse(ctx *gin.Context, code int, message string, data interface{}) }) } -// SendErrorResponse 发送统一格式的错误响应 -func SendErrorResponse(ctx *gin.Context, code int, message string) { +// SendErrorResponse 发送统一格式的错误响应 (基础函数,不带审计) +func SendErrorResponse(ctx *gin.Context, code ResponseCode, message string) { SendResponse(ctx, code, message, nil) } + +// --- 带审计功能的响应函数 --- + +// setAuditDetails 是一个内部辅助函数,用于在 gin.Context 中设置业务相关的审计信息。 +func setAuditDetails(c *gin.Context, actionType, description string, targetResource interface{}) { + // 只有当 actionType 不为空时,才设置审计信息,这作为触发审计的标志 + if actionType != "" { + c.Set(middleware.ContextAuditActionType, actionType) + c.Set(middleware.ContextAuditDescription, description) + c.Set(middleware.ContextAuditTargetResource, targetResource) + } +} + +// SendSuccessWithAudit 发送成功的响应,并设置审计日志所需的信息。 +// 这是控制器中用于记录成功操作并返回响应的首选函数。 +func SendSuccessWithAudit(ctx *gin.Context, code ResponseCode, message string, data interface{}, actionType, description string, targetResource interface{}) { + // 1. 设置审计信息 + setAuditDetails(ctx, actionType, description, targetResource) + // 2. 发送响应 + SendResponse(ctx, code, message, data) +} + +// SendErrorWithAudit 发送失败的响应,并设置审计日志所需的信息。 +// 这是控制器中用于记录失败操作并返回响应的首选函数。 +func SendErrorWithAudit(ctx *gin.Context, code ResponseCode, message string, actionType, description string, targetResource interface{}) { + // 1. 设置审计信息 + setAuditDetails(ctx, actionType, description, targetResource) + // 2. 发送响应 + SendErrorResponse(ctx, code, message) +} diff --git a/internal/app/middleware/audit.go b/internal/app/middleware/audit.go new file mode 100644 index 0000000..93dabef --- /dev/null +++ b/internal/app/middleware/audit.go @@ -0,0 +1,98 @@ +// Package middleware 存放 gin 中间件 +package middleware + +import ( + "bytes" + "encoding/json" + "io" + "strconv" + + "git.huangwc.com/pig/pig-farm-controller/internal/app/service/audit" + "github.com/gin-gonic/gin" +) + +// --- 审计日志相关上下文键 --- +const ( + ContextAuditActionType = "auditActionType" + ContextAuditTargetResource = "auditTargetResource" + ContextAuditDescription = "auditDescription" +) + +// AuditLogMiddleware 创建一个Gin中间件,用于在请求结束后记录用户操作审计日志 +func AuditLogMiddleware(auditService audit.Service) gin.HandlerFunc { + return func(c *gin.Context) { + // 使用自定义的 response body writer 来捕获响应体 + blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer} + c.Writer = blw + + // 首先执行请求链中的后续处理程序(即业务控制器) + c.Next() + + // --- 在这里,请求已经处理完毕 --- + + // 从上下文中尝试获取由控制器设置的业务审计信息 + actionType, exists := c.Get(ContextAuditActionType) + if !exists { + // 如果上下文中没有 actionType,说明此接口无需记录审计日志,直接返回 + return + } + + // 获取其他审计信息 + description, _ := c.Get(ContextAuditDescription) + targetResource, _ := c.Get(ContextAuditTargetResource) + + // 判断操作状态 + status := "success" + resultDetails := "" + if c.Writer.Status() >= 400 { + status = "failed" + // 尝试从捕获的响应体中解析错误信息 + var errResp struct { + Error string `json:"error"` + } + if err := json.Unmarshal(blw.body.Bytes(), &errResp); err == nil { + resultDetails = errResp.Error + } else { + resultDetails = "HTTP Status: " + strconv.Itoa(c.Writer.Status()) + } + } + + // 调用审计服务记录日志(异步) + auditService.LogAction( + c, + actionType.(string), + description.(string), + targetResource, + status, + resultDetails, + ) + } +} + +// bodyLogWriter 是一个自定义的 gin.ResponseWriter,用于捕获响应体 +// 这对于在操作失败时记录详细的错误信息非常有用 +type bodyLogWriter struct { + gin.ResponseWriter + body *bytes.Buffer +} + +func (w bodyLogWriter) Write(b []byte) (int, error) { + w.body.Write(b) + return w.ResponseWriter.Write(b) +} + +func (w bodyLogWriter) WriteString(s string) (int, error) { + w.body.WriteString(s) + return w.ResponseWriter.WriteString(s) +} + +// ReadBody 用于安全地读取请求体,并防止其被重复读取 +func ReadBody(c *gin.Context) ([]byte, error) { + bodyBytes, err := io.ReadAll(c.Request.Body) + if err != nil { + return nil, err + } + // 将读取的内容放回 Body 中,以便后续的处理函数可以再次读取 + c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) + return bodyBytes, nil +} diff --git a/internal/app/middleware/auth.go b/internal/app/middleware/auth.go index 5d97fa1..29cc36e 100644 --- a/internal/app/middleware/auth.go +++ b/internal/app/middleware/auth.go @@ -5,18 +5,16 @@ import ( "net/http" "strings" + "git.huangwc.com/pig/pig-farm-controller/internal/app/service/audit" "git.huangwc.com/pig/pig-farm-controller/internal/app/service/token" + "git.huangwc.com/pig/pig-farm-controller/internal/infra/repository" "github.com/gin-gonic/gin" -) - -const ( - // ContextUserIDKey 是存储在 gin.Context 中的用户ID的键名 - ContextUserIDKey = "userID" + "gorm.io/gorm" ) // AuthMiddleware 创建一个Gin中间件,用于JWT身份验证 -// 它依赖于 TokenService 来解析和验证 token -func AuthMiddleware(tokenService token.TokenService) gin.HandlerFunc { +// 它依赖于 TokenService 来解析和验证 token,并使用 UserRepository 来获取完整的用户信息 +func AuthMiddleware(tokenService token.TokenService, userRepo repository.UserRepository) gin.HandlerFunc { return func(c *gin.Context) { // 从 Authorization header 获取 token authHeader := c.GetHeader("Authorization") @@ -41,8 +39,21 @@ func AuthMiddleware(tokenService token.TokenService) gin.HandlerFunc { return } - // 将解析出的用户ID存储在 context 中,以便后续的处理函数使用 - c.Set(ContextUserIDKey, claims.UserID) + // 根据 token 中的用户ID,从数据库中获取完整的用户信息 + user, err := userRepo.FindByID(claims.UserID) + if err != nil { + if err == gorm.ErrRecordNotFound { + // Token有效,但对应的用户已不存在 + c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "授权用户不存在"}) + return + } + // 其他数据库查询错误 + c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "获取用户信息失败"}) + return + } + + // 将完整的用户对象存储在 context 中,以便后续的处理函数使用 + c.Set(audit.ContextUserKey, user) // 继续处理请求链中的下一个处理程序 c.Next() diff --git a/internal/app/service/audit/service.go b/internal/app/service/audit/service.go new file mode 100644 index 0000000..105561c --- /dev/null +++ b/internal/app/service/audit/service.go @@ -0,0 +1,83 @@ +// Package audit 提供了用户操作审计相关的功能 +package audit + +import ( + "encoding/json" + "time" + + "git.huangwc.com/pig/pig-farm-controller/internal/infra/logs" + "git.huangwc.com/pig/pig-farm-controller/internal/infra/models" + "git.huangwc.com/pig/pig-farm-controller/internal/infra/repository" + "github.com/gin-gonic/gin" + "gorm.io/datatypes" +) + +const ( + // ContextUserKey 是存储在 gin.Context 中的用户对象的键名 + ContextUserKey = "user" +) + +// Service 定义了审计服务的接口 +type Service interface { + LogAction(c *gin.Context, actionType, description string, targetResource interface{}, status string, resultDetails string) +} + +// service 是 Service 接口的实现 +type service struct { + userActionLogRepository repository.UserActionLogRepository + logger *logs.Logger +} + +// NewService 创建一个新的审计服务实例 +func NewService(repo repository.UserActionLogRepository, logger *logs.Logger) Service { + return &service{userActionLogRepository: repo, logger: logger} +} + +// LogAction 记录一个用户操作。它在一个新的 goroutine 中异步执行,以避免阻塞主请求。 +func (s *service) LogAction(c *gin.Context, actionType, description string, targetResource interface{}, status string, resultDetails string) { + // 从 context 中获取预加载的用户信息 + userCtx, exists := c.Get(ContextUserKey) + if !exists { + // 如果上下文中没有用户信息(例如,在未认证的路由上调用了此函数),则不记录日志 + s.logger.Warnw("无法记录审计日志:上下文中缺少用户信息") + return + } + + user, ok := userCtx.(*models.User) + if !ok { + s.logger.Errorw("无法记录审计日志:上下文中的用户对象类型不正确") + return + } + + // 将 targetResource 转换为 JSONB,如果失败则记录错误但继续 + var targetResourceJSON datatypes.JSON + if targetResource != nil { + bytes, err := json.Marshal(targetResource) + if err != nil { + s.logger.Errorw("无法记录审计日志:序列化 targetResource 失败", "error", err) + } else { + targetResourceJSON = bytes + } + } + + log := &models.UserActionLog{ + Time: time.Now(), + UserID: user.ID, + Username: user.Username, // 用户名快照 + SourceIP: c.ClientIP(), + ActionType: actionType, + TargetResource: targetResourceJSON, + Description: description, + Status: status, + HTTPPath: c.Request.URL.Path, + HTTPMethod: c.Request.Method, + ResultDetails: resultDetails, + } + + // 异步写入数据库,不阻塞当前请求 + go func() { + if err := s.userActionLogRepository.Create(log); err != nil { + s.logger.Errorw("异步保存审计日志失败", "error", err) + } + }() +} diff --git a/internal/core/application.go b/internal/core/application.go index 216c205..7fed25f 100644 --- a/internal/core/application.go +++ b/internal/core/application.go @@ -8,6 +8,7 @@ import ( "time" "git.huangwc.com/pig/pig-farm-controller/internal/app/api" + "git.huangwc.com/pig/pig-farm-controller/internal/app/service/audit" "git.huangwc.com/pig/pig-farm-controller/internal/app/service/device" "git.huangwc.com/pig/pig-farm-controller/internal/app/service/task" "git.huangwc.com/pig/pig-farm-controller/internal/app/service/token" @@ -81,6 +82,12 @@ func NewApplication(configPath string) (*Application, error) { // 初始化待采集请求仓库 pendingCollectionRepo := repository.NewGormPendingCollectionRepository(storage.GetDB()) + // 初始化审计日志仓库 + userActionLogRepo := repository.NewGormUserActionLogRepository(storage.GetDB()) + + // 初始化审计服务 + auditService := audit.NewService(userActionLogRepo, logger) + // 初始化设备上行监听器 listenHandler := transport.NewChirpStackListener(logger, sensorDataRepo, deviceRepo, deviceCommandLogRepo, pendingCollectionRepo) @@ -121,6 +128,7 @@ func NewApplication(configPath string) (*Application, error) { deviceRepo, planRepo, tokenService, + auditService, listenHandler, analysisPlanTaskManager, ) diff --git a/internal/infra/database/postgres.go b/internal/infra/database/postgres.go index 60d775f..bfab23d 100644 --- a/internal/infra/database/postgres.go +++ b/internal/infra/database/postgres.go @@ -159,6 +159,7 @@ func (ps *PostgresStorage) creatingHyperTable() error { {models.PlanExecutionLog{}, "started_at"}, {models.TaskExecutionLog{}, "started_at"}, {models.PendingCollection{}, "created_at"}, + {models.UserActionLog{}, "time"}, } for _, table := range tablesToConvert { @@ -187,6 +188,7 @@ func (ps *PostgresStorage) applyCompressionPolicies() error { {models.PlanExecutionLog{}, "plan_id"}, {models.TaskExecutionLog{}, "task_id"}, {models.PendingCollection{}, "device_id"}, + {models.UserActionLog{}, "user_id"}, } for _, policy := range policies { diff --git a/internal/infra/models/execution.go b/internal/infra/models/execution.go index 4e4eaf5..257dcea 100644 --- a/internal/infra/models/execution.go +++ b/internal/infra/models/execution.go @@ -3,6 +3,7 @@ package models import ( "time" + "gorm.io/datatypes" "gorm.io/gorm" ) @@ -140,3 +141,32 @@ type PendingCollection struct { func (PendingCollection) TableName() string { return "pending_collections" } + +// --- 用户审计日志 --- + +// UserActionLog 记录用户的操作历史,用于审计 +type UserActionLog struct { + // Time 是操作发生的时间,作为主键和超表的时间分区键 + Time time.Time `gorm:"primaryKey" json:"time"` + + // --- Who (谁) --- + UserID uint `gorm:"index" json:"user_id,omitempty"` + Username string `json:"username,omitempty"` // 操作发生时用户名的快照 + + // --- Where (何地) --- + SourceIP string `json:"source_ip,omitempty"` + + // --- What (什么) & How (如何) --- + ActionType string `gorm:"index" json:"action_type,omitempty"` // 标准化的操作类型,如 "CREATE_DEVICE" + TargetResource datatypes.JSON `gorm:"type:jsonb" json:"target_resource,omitempty"` // 被操作的资源, e.g., {"type": "device", "id": 123} + Description string `json:"description,omitempty"` // 人类可读的操作描述 + Status string `json:"status,omitempty"` // success 或 failed + HTTPPath string `json:"http_path,omitempty"` // 请求的API路径 + HTTPMethod string `json:"http_method,omitempty"` // 请求的HTTP方法 + ResultDetails string `json:"result_details,omitempty"` // 结果详情,如失败时的错误信息 +} + +// TableName 自定义 GORM 使用的数据库表名 +func (UserActionLog) TableName() string { + return "user_action_logs" +} diff --git a/internal/infra/repository/user_action_log_repository.go b/internal/infra/repository/user_action_log_repository.go new file mode 100644 index 0000000..cfaac10 --- /dev/null +++ b/internal/infra/repository/user_action_log_repository.go @@ -0,0 +1,27 @@ +// Package repository 提供了数据访问的仓库实现 +package repository + +import ( + "git.huangwc.com/pig/pig-farm-controller/internal/infra/models" + "gorm.io/gorm" +) + +// UserActionLogRepository 定义了与用户操作日志相关的数据库操作接口 +type UserActionLogRepository interface { + Create(log *models.UserActionLog) error +} + +// gormUserActionLogRepository 是 UserActionLogRepository 的 GORM 实现 +type gormUserActionLogRepository struct { + db *gorm.DB +} + +// NewGormUserActionLogRepository 创建一个新的 UserActionLogRepository GORM 实现实例 +func NewGormUserActionLogRepository(db *gorm.DB) UserActionLogRepository { + return &gormUserActionLogRepository{db: db} +} + +// Create 创建一条新的用户操作日志记录 +func (r *gormUserActionLogRepository) Create(log *models.UserActionLog) error { + return r.db.Create(log).Error +} From 3c8b91ff6a75589a3307cb49c888947ef80d7e57 Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Sun, 28 Sep 2025 00:37:20 +0800 Subject: [PATCH 05/13] =?UTF-8?q?JSON=E8=BD=AC=E6=8D=A2=E6=94=BE=E5=9C=A8?= =?UTF-8?q?=E5=86=85=E7=BD=AE=E5=87=BD=E6=95=B0=E9=87=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/app/service/audit/service.go | 38 +++++++++++---------------- internal/infra/models/execution.go | 25 ++++++++++++++++++ 2 files changed, 40 insertions(+), 23 deletions(-) diff --git a/internal/app/service/audit/service.go b/internal/app/service/audit/service.go index 105561c..7412236 100644 --- a/internal/app/service/audit/service.go +++ b/internal/app/service/audit/service.go @@ -2,14 +2,12 @@ package audit import ( - "encoding/json" "time" "git.huangwc.com/pig/pig-farm-controller/internal/infra/logs" "git.huangwc.com/pig/pig-farm-controller/internal/infra/models" "git.huangwc.com/pig/pig-farm-controller/internal/infra/repository" "github.com/gin-gonic/gin" - "gorm.io/datatypes" ) const ( @@ -49,29 +47,23 @@ func (s *service) LogAction(c *gin.Context, actionType, description string, targ return } - // 将 targetResource 转换为 JSONB,如果失败则记录错误但继续 - var targetResourceJSON datatypes.JSON - if targetResource != nil { - bytes, err := json.Marshal(targetResource) - if err != nil { - s.logger.Errorw("无法记录审计日志:序列化 targetResource 失败", "error", err) - } else { - targetResourceJSON = bytes - } + log := &models.UserActionLog{ + Time: time.Now(), + UserID: user.ID, + Username: user.Username, // 用户名快照 + SourceIP: c.ClientIP(), + ActionType: actionType, + Description: description, + Status: status, + HTTPPath: c.Request.URL.Path, + HTTPMethod: c.Request.Method, + ResultDetails: resultDetails, } - log := &models.UserActionLog{ - Time: time.Now(), - UserID: user.ID, - Username: user.Username, // 用户名快照 - SourceIP: c.ClientIP(), - ActionType: actionType, - TargetResource: targetResourceJSON, - Description: description, - Status: status, - HTTPPath: c.Request.URL.Path, - HTTPMethod: c.Request.Method, - ResultDetails: resultDetails, + // 使用模型提供的方法来设置 TargetResource + if err := log.SetTargetResource(targetResource); err != nil { + s.logger.Errorw("无法记录审计日志:序列化 targetResource 失败", "error", err) + // 即使序列化失败,我们可能仍然希望记录操作本身,所以不在此处 return } // 异步写入数据库,不阻塞当前请求 diff --git a/internal/infra/models/execution.go b/internal/infra/models/execution.go index 257dcea..90073e7 100644 --- a/internal/infra/models/execution.go +++ b/internal/infra/models/execution.go @@ -1,6 +1,8 @@ package models import ( + "encoding/json" + "errors" "time" "gorm.io/datatypes" @@ -170,3 +172,26 @@ type UserActionLog struct { func (UserActionLog) TableName() string { return "user_action_logs" } + +// ParseTargetResource 解析 JSON 属性到一个具体的结构体中。 +// 调用方需要传入一个指向目标结构体实例的指针。 +func (l *UserActionLog) ParseTargetResource(v interface{}) error { + if l.TargetResource == nil { + return errors.New("目标资源为空,无法解析") + } + return json.Unmarshal(l.TargetResource, v) +} + +// SetTargetResource 将任意结构体序列化为 JSON 并设置到 TargetResource 字段 +func (l *UserActionLog) SetTargetResource(data interface{}) error { + if data == nil { + l.TargetResource = nil + return nil + } + bytes, err := json.Marshal(data) + if err != nil { + return err + } + l.TargetResource = bytes + return nil +} From e3c0a972fb2c0d183eaab96af7b956b14d07d8b1 Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Sun, 28 Sep 2025 00:54:19 +0800 Subject: [PATCH 06/13] =?UTF-8?q?=E5=93=8D=E5=BA=94=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E6=94=B9=E6=88=90=E8=87=AA=E5=AE=9A=E4=B9=89=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/app/controller/response.go | 8 ++-- internal/app/middleware/audit.go | 46 ++++++++++--------- .../repository/user_action_log_repository.go | 13 ++++++ 3 files changed, 42 insertions(+), 25 deletions(-) diff --git a/internal/app/controller/response.go b/internal/app/controller/response.go index bfcf5b2..5d0c3f3 100644 --- a/internal/app/controller/response.go +++ b/internal/app/controller/response.go @@ -3,7 +3,7 @@ package controller import ( "net/http" - "git.huangwc.com/pig/pig-farm-controller/internal/app/middleware" + "git.huangwc.com/pig/pig-farm-controller/internal/infra/repository" "github.com/gin-gonic/gin" ) @@ -55,9 +55,9 @@ func SendErrorResponse(ctx *gin.Context, code ResponseCode, message string) { func setAuditDetails(c *gin.Context, actionType, description string, targetResource interface{}) { // 只有当 actionType 不为空时,才设置审计信息,这作为触发审计的标志 if actionType != "" { - c.Set(middleware.ContextAuditActionType, actionType) - c.Set(middleware.ContextAuditDescription, description) - c.Set(middleware.ContextAuditTargetResource, targetResource) + c.Set(repository.ContextAuditActionType, actionType) + c.Set(repository.ContextAuditDescription, description) + c.Set(repository.ContextAuditTargetResource, targetResource) } } diff --git a/internal/app/middleware/audit.go b/internal/app/middleware/audit.go index 93dabef..c57ad3f 100644 --- a/internal/app/middleware/audit.go +++ b/internal/app/middleware/audit.go @@ -1,4 +1,3 @@ -// Package middleware 存放 gin 中间件 package middleware import ( @@ -8,15 +7,14 @@ import ( "strconv" "git.huangwc.com/pig/pig-farm-controller/internal/app/service/audit" + "git.huangwc.com/pig/pig-farm-controller/internal/infra/repository" "github.com/gin-gonic/gin" ) -// --- 审计日志相关上下文键 --- -const ( - ContextAuditActionType = "auditActionType" - ContextAuditTargetResource = "auditTargetResource" - ContextAuditDescription = "auditDescription" -) +type auditResponse struct { + Code int `json:"code"` + Message string `json:"message"` +} // AuditLogMiddleware 创建一个Gin中间件,用于在请求结束后记录用户操作审计日志 func AuditLogMiddleware(auditService audit.Service) gin.HandlerFunc { @@ -31,30 +29,36 @@ func AuditLogMiddleware(auditService audit.Service) gin.HandlerFunc { // --- 在这里,请求已经处理完毕 --- // 从上下文中尝试获取由控制器设置的业务审计信息 - actionType, exists := c.Get(ContextAuditActionType) + actionType, exists := c.Get(repository.ContextAuditActionType) if !exists { // 如果上下文中没有 actionType,说明此接口无需记录审计日志,直接返回 return } // 获取其他审计信息 - description, _ := c.Get(ContextAuditDescription) - targetResource, _ := c.Get(ContextAuditTargetResource) + description, _ := c.Get(repository.ContextAuditDescription) + targetResource, _ := c.Get(repository.ContextAuditTargetResource) - // 判断操作状态 - status := "success" + // 默认操作状态为成功 + status := repository.AuditStatusSuccess resultDetails := "" - if c.Writer.Status() >= 400 { - status = "failed" - // 尝试从捕获的响应体中解析错误信息 - var errResp struct { - Error string `json:"error"` + + // 尝试从捕获的响应体中解析平台响应 + var platformResponse auditResponse + if err := json.Unmarshal(blw.body.Bytes(), &platformResponse); err == nil { + // 如果解析成功,根据平台状态码判断操作是否失败 + // 成功状态码范围是 2000-2999 + if platformResponse.Code < 2000 || platformResponse.Code >= 3000 { + status = repository.AuditStatusFailed + resultDetails = platformResponse.Message } - if err := json.Unmarshal(blw.body.Bytes(), &errResp); err == nil { - resultDetails = errResp.Error - } else { - resultDetails = "HTTP Status: " + strconv.Itoa(c.Writer.Status()) + } else { + // 如果响应体不是预期的平台响应格式,或者解析失败,则记录原始HTTP状态码作为详情 + // 并且如果HTTP状态码不是2xx,则标记为失败 + if c.Writer.Status() < 200 || c.Writer.Status() >= 300 { + status = repository.AuditStatusFailed } + resultDetails = "HTTP Status: " + strconv.Itoa(c.Writer.Status()) + ", Body Parse Error: " + err.Error() } // 调用审计服务记录日志(异步) diff --git a/internal/infra/repository/user_action_log_repository.go b/internal/infra/repository/user_action_log_repository.go index cfaac10..7faa97c 100644 --- a/internal/infra/repository/user_action_log_repository.go +++ b/internal/infra/repository/user_action_log_repository.go @@ -6,6 +6,19 @@ import ( "gorm.io/gorm" ) +// --- 审计日志状态常量 --- +const ( + AuditStatusSuccess = "success" + AuditStatusFailed = "failed" +) + +// --- 审计日志相关上下文键 --- +const ( + ContextAuditActionType = "auditActionType" + ContextAuditTargetResource = "auditTargetResource" + ContextAuditDescription = "auditDescription" +) + // UserActionLogRepository 定义了与用户操作日志相关的数据库操作接口 type UserActionLogRepository interface { Create(log *models.UserActionLog) error From d995498199cafb4e53fad5b906698dd89c142de0 Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Sun, 28 Sep 2025 01:02:29 +0800 Subject: [PATCH 07/13] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/app/middleware/audit.go | 18 +++++++++- internal/app/middleware/auth.go | 3 +- internal/app/service/audit/service.go | 36 ++++++++----------- .../repository/user_action_log_repository.go | 2 ++ 4 files changed, 35 insertions(+), 24 deletions(-) diff --git a/internal/app/middleware/audit.go b/internal/app/middleware/audit.go index c57ad3f..bea39f2 100644 --- a/internal/app/middleware/audit.go +++ b/internal/app/middleware/audit.go @@ -7,6 +7,7 @@ import ( "strconv" "git.huangwc.com/pig/pig-farm-controller/internal/app/service/audit" + "git.huangwc.com/pig/pig-farm-controller/internal/infra/models" "git.huangwc.com/pig/pig-farm-controller/internal/infra/repository" "github.com/gin-gonic/gin" ) @@ -35,6 +36,20 @@ func AuditLogMiddleware(auditService audit.Service) gin.HandlerFunc { return } + // 从 Gin Context 中获取用户对象 + userCtx, userExists := c.Get(repository.ContextUserKey) + var user *models.User + if userExists { + user, _ = userCtx.(*models.User) + } + + // 构建 RequestContext + reqCtx := audit.RequestContext{ + ClientIP: c.ClientIP(), + HTTPPath: c.Request.URL.Path, + HTTPMethod: c.Request.Method, + } + // 获取其他审计信息 description, _ := c.Get(repository.ContextAuditDescription) targetResource, _ := c.Get(repository.ContextAuditTargetResource) @@ -63,7 +78,8 @@ func AuditLogMiddleware(auditService audit.Service) gin.HandlerFunc { // 调用审计服务记录日志(异步) auditService.LogAction( - c, + user, + reqCtx, actionType.(string), description.(string), targetResource, diff --git a/internal/app/middleware/auth.go b/internal/app/middleware/auth.go index 29cc36e..264841c 100644 --- a/internal/app/middleware/auth.go +++ b/internal/app/middleware/auth.go @@ -5,7 +5,6 @@ import ( "net/http" "strings" - "git.huangwc.com/pig/pig-farm-controller/internal/app/service/audit" "git.huangwc.com/pig/pig-farm-controller/internal/app/service/token" "git.huangwc.com/pig/pig-farm-controller/internal/infra/repository" "github.com/gin-gonic/gin" @@ -53,7 +52,7 @@ func AuthMiddleware(tokenService token.TokenService, userRepo repository.UserRep } // 将完整的用户对象存储在 context 中,以便后续的处理函数使用 - c.Set(audit.ContextUserKey, user) + c.Set(repository.ContextUserKey, user) // 继续处理请求链中的下一个处理程序 c.Next() diff --git a/internal/app/service/audit/service.go b/internal/app/service/audit/service.go index 7412236..bcd6971 100644 --- a/internal/app/service/audit/service.go +++ b/internal/app/service/audit/service.go @@ -7,17 +7,19 @@ import ( "git.huangwc.com/pig/pig-farm-controller/internal/infra/logs" "git.huangwc.com/pig/pig-farm-controller/internal/infra/models" "git.huangwc.com/pig/pig-farm-controller/internal/infra/repository" - "github.com/gin-gonic/gin" + // 移除对 "github.com/gin-gonic/gin" 的直接依赖 ) -const ( - // ContextUserKey 是存储在 gin.Context 中的用户对象的键名 - ContextUserKey = "user" -) +// RequestContext 封装了审计日志所需的请求上下文信息 +type RequestContext struct { + ClientIP string + HTTPPath string + HTTPMethod string +} // Service 定义了审计服务的接口 type Service interface { - LogAction(c *gin.Context, actionType, description string, targetResource interface{}, status string, resultDetails string) + LogAction(user *models.User, reqCtx RequestContext, actionType, description string, targetResource interface{}, status string, resultDetails string) } // service 是 Service 接口的实现 @@ -32,18 +34,10 @@ func NewService(repo repository.UserActionLogRepository, logger *logs.Logger) Se } // LogAction 记录一个用户操作。它在一个新的 goroutine 中异步执行,以避免阻塞主请求。 -func (s *service) LogAction(c *gin.Context, actionType, description string, targetResource interface{}, status string, resultDetails string) { - // 从 context 中获取预加载的用户信息 - userCtx, exists := c.Get(ContextUserKey) - if !exists { - // 如果上下文中没有用户信息(例如,在未认证的路由上调用了此函数),则不记录日志 - s.logger.Warnw("无法记录审计日志:上下文中缺少用户信息") - return - } - - user, ok := userCtx.(*models.User) - if !ok { - s.logger.Errorw("无法记录审计日志:上下文中的用户对象类型不正确") +func (s *service) LogAction(user *models.User, reqCtx RequestContext, actionType, description string, targetResource interface{}, status string, resultDetails string) { + // 不再从 context 中获取用户信息,直接使用传入的 user 对象 + if user == nil { + s.logger.Warnw("无法记录审计日志:传入的用户对象为 nil") return } @@ -51,12 +45,12 @@ func (s *service) LogAction(c *gin.Context, actionType, description string, targ Time: time.Now(), UserID: user.ID, Username: user.Username, // 用户名快照 - SourceIP: c.ClientIP(), + SourceIP: reqCtx.ClientIP, ActionType: actionType, Description: description, Status: status, - HTTPPath: c.Request.URL.Path, - HTTPMethod: c.Request.Method, + HTTPPath: reqCtx.HTTPPath, + HTTPMethod: reqCtx.HTTPMethod, ResultDetails: resultDetails, } diff --git a/internal/infra/repository/user_action_log_repository.go b/internal/infra/repository/user_action_log_repository.go index 7faa97c..ea20942 100644 --- a/internal/infra/repository/user_action_log_repository.go +++ b/internal/infra/repository/user_action_log_repository.go @@ -13,10 +13,12 @@ const ( ) // --- 审计日志相关上下文键 --- +// TODO 这些变量放这个包合适吗? const ( ContextAuditActionType = "auditActionType" ContextAuditTargetResource = "auditTargetResource" ContextAuditDescription = "auditDescription" + ContextUserKey = "user" // 存储在 gin.Context 中的用户对象的键名 ) // UserActionLogRepository 定义了与用户操作日志相关的数据库操作接口 From fdbea5b7e9feb8c5b9e097c001af39ab69bb5ffe Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Sun, 28 Sep 2025 01:10:04 +0800 Subject: [PATCH 08/13] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/app/controller/response.go | 8 +++--- internal/app/middleware/audit.go | 15 ++++++----- internal/app/middleware/auth.go | 3 ++- internal/app/service/audit/service.go | 4 +-- internal/infra/models/execution.go | 25 ++++++++++++++++++- .../repository/user_action_log_repository.go | 15 ----------- 6 files changed, 39 insertions(+), 31 deletions(-) diff --git a/internal/app/controller/response.go b/internal/app/controller/response.go index 5d0c3f3..422026b 100644 --- a/internal/app/controller/response.go +++ b/internal/app/controller/response.go @@ -3,7 +3,7 @@ package controller import ( "net/http" - "git.huangwc.com/pig/pig-farm-controller/internal/infra/repository" + "git.huangwc.com/pig/pig-farm-controller/internal/infra/models" "github.com/gin-gonic/gin" ) @@ -55,9 +55,9 @@ func SendErrorResponse(ctx *gin.Context, code ResponseCode, message string) { func setAuditDetails(c *gin.Context, actionType, description string, targetResource interface{}) { // 只有当 actionType 不为空时,才设置审计信息,这作为触发审计的标志 if actionType != "" { - c.Set(repository.ContextAuditActionType, actionType) - c.Set(repository.ContextAuditDescription, description) - c.Set(repository.ContextAuditTargetResource, targetResource) + c.Set(models.ContextAuditActionType.String(), actionType) + c.Set(models.ContextAuditDescription.String(), description) + c.Set(models.ContextAuditTargetResource.String(), targetResource) } } diff --git a/internal/app/middleware/audit.go b/internal/app/middleware/audit.go index bea39f2..db2a8b2 100644 --- a/internal/app/middleware/audit.go +++ b/internal/app/middleware/audit.go @@ -8,7 +8,6 @@ import ( "git.huangwc.com/pig/pig-farm-controller/internal/app/service/audit" "git.huangwc.com/pig/pig-farm-controller/internal/infra/models" - "git.huangwc.com/pig/pig-farm-controller/internal/infra/repository" "github.com/gin-gonic/gin" ) @@ -30,14 +29,14 @@ func AuditLogMiddleware(auditService audit.Service) gin.HandlerFunc { // --- 在这里,请求已经处理完毕 --- // 从上下文中尝试获取由控制器设置的业务审计信息 - actionType, exists := c.Get(repository.ContextAuditActionType) + actionType, exists := c.Get(models.ContextAuditActionType.String()) if !exists { // 如果上下文中没有 actionType,说明此接口无需记录审计日志,直接返回 return } // 从 Gin Context 中获取用户对象 - userCtx, userExists := c.Get(repository.ContextUserKey) + userCtx, userExists := c.Get(models.ContextUserKey.String()) var user *models.User if userExists { user, _ = userCtx.(*models.User) @@ -51,11 +50,11 @@ func AuditLogMiddleware(auditService audit.Service) gin.HandlerFunc { } // 获取其他审计信息 - description, _ := c.Get(repository.ContextAuditDescription) - targetResource, _ := c.Get(repository.ContextAuditTargetResource) + description, _ := c.Get(models.ContextAuditDescription.String()) + targetResource, _ := c.Get(models.ContextAuditTargetResource.String()) // 默认操作状态为成功 - status := repository.AuditStatusSuccess + status := models.AuditStatusSuccess resultDetails := "" // 尝试从捕获的响应体中解析平台响应 @@ -64,14 +63,14 @@ func AuditLogMiddleware(auditService audit.Service) gin.HandlerFunc { // 如果解析成功,根据平台状态码判断操作是否失败 // 成功状态码范围是 2000-2999 if platformResponse.Code < 2000 || platformResponse.Code >= 3000 { - status = repository.AuditStatusFailed + status = models.AuditStatusFailed resultDetails = platformResponse.Message } } else { // 如果响应体不是预期的平台响应格式,或者解析失败,则记录原始HTTP状态码作为详情 // 并且如果HTTP状态码不是2xx,则标记为失败 if c.Writer.Status() < 200 || c.Writer.Status() >= 300 { - status = repository.AuditStatusFailed + status = models.AuditStatusFailed } resultDetails = "HTTP Status: " + strconv.Itoa(c.Writer.Status()) + ", Body Parse Error: " + err.Error() } diff --git a/internal/app/middleware/auth.go b/internal/app/middleware/auth.go index 264841c..8684acb 100644 --- a/internal/app/middleware/auth.go +++ b/internal/app/middleware/auth.go @@ -6,6 +6,7 @@ import ( "strings" "git.huangwc.com/pig/pig-farm-controller/internal/app/service/token" + "git.huangwc.com/pig/pig-farm-controller/internal/infra/models" "git.huangwc.com/pig/pig-farm-controller/internal/infra/repository" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -52,7 +53,7 @@ func AuthMiddleware(tokenService token.TokenService, userRepo repository.UserRep } // 将完整的用户对象存储在 context 中,以便后续的处理函数使用 - c.Set(repository.ContextUserKey, user) + c.Set(models.ContextUserKey.String(), user) // 继续处理请求链中的下一个处理程序 c.Next() diff --git a/internal/app/service/audit/service.go b/internal/app/service/audit/service.go index bcd6971..6f72396 100644 --- a/internal/app/service/audit/service.go +++ b/internal/app/service/audit/service.go @@ -19,7 +19,7 @@ type RequestContext struct { // Service 定义了审计服务的接口 type Service interface { - LogAction(user *models.User, reqCtx RequestContext, actionType, description string, targetResource interface{}, status string, resultDetails string) + LogAction(user *models.User, reqCtx RequestContext, actionType, description string, targetResource interface{}, status models.AuditStatus, resultDetails string) } // service 是 Service 接口的实现 @@ -34,7 +34,7 @@ func NewService(repo repository.UserActionLogRepository, logger *logs.Logger) Se } // LogAction 记录一个用户操作。它在一个新的 goroutine 中异步执行,以避免阻塞主请求。 -func (s *service) LogAction(user *models.User, reqCtx RequestContext, actionType, description string, targetResource interface{}, status string, resultDetails string) { +func (s *service) LogAction(user *models.User, reqCtx RequestContext, actionType, description string, targetResource interface{}, status models.AuditStatus, resultDetails string) { // 不再从 context 中获取用户信息,直接使用传入的 user 对象 if user == nil { s.logger.Warnw("无法记录审计日志:传入的用户对象为 nil") diff --git a/internal/infra/models/execution.go b/internal/infra/models/execution.go index 90073e7..392187a 100644 --- a/internal/infra/models/execution.go +++ b/internal/infra/models/execution.go @@ -145,6 +145,29 @@ func (PendingCollection) TableName() string { } // --- 用户审计日志 --- +// TODO 这些变量放这个包合适吗? + +// --- 审计日志状态常量 --- +type AuditStatus string + +const ( + AuditStatusSuccess AuditStatus = "success" + AuditStatusFailed AuditStatus = "failed" +) + +// --- 审计日志相关上下文键 --- +type AuditContextKey string + +const ( + ContextAuditActionType AuditContextKey = "auditActionType" + ContextAuditTargetResource AuditContextKey = "auditTargetResource" + ContextAuditDescription AuditContextKey = "auditDescription" + ContextUserKey AuditContextKey = "user" +) + +func (a AuditContextKey) String() string { + return string(a) +} // UserActionLog 记录用户的操作历史,用于审计 type UserActionLog struct { @@ -162,7 +185,7 @@ type UserActionLog struct { ActionType string `gorm:"index" json:"action_type,omitempty"` // 标准化的操作类型,如 "CREATE_DEVICE" TargetResource datatypes.JSON `gorm:"type:jsonb" json:"target_resource,omitempty"` // 被操作的资源, e.g., {"type": "device", "id": 123} Description string `json:"description,omitempty"` // 人类可读的操作描述 - Status string `json:"status,omitempty"` // success 或 failed + Status AuditStatus `json:"status,omitempty"` // success 或 failed HTTPPath string `json:"http_path,omitempty"` // 请求的API路径 HTTPMethod string `json:"http_method,omitempty"` // 请求的HTTP方法 ResultDetails string `json:"result_details,omitempty"` // 结果详情,如失败时的错误信息 diff --git a/internal/infra/repository/user_action_log_repository.go b/internal/infra/repository/user_action_log_repository.go index ea20942..cfaac10 100644 --- a/internal/infra/repository/user_action_log_repository.go +++ b/internal/infra/repository/user_action_log_repository.go @@ -6,21 +6,6 @@ import ( "gorm.io/gorm" ) -// --- 审计日志状态常量 --- -const ( - AuditStatusSuccess = "success" - AuditStatusFailed = "failed" -) - -// --- 审计日志相关上下文键 --- -// TODO 这些变量放这个包合适吗? -const ( - ContextAuditActionType = "auditActionType" - ContextAuditTargetResource = "auditTargetResource" - ContextAuditDescription = "auditDescription" - ContextUserKey = "user" // 存储在 gin.Context 中的用户对象的键名 -) - // UserActionLogRepository 定义了与用户操作日志相关的数据库操作接口 type UserActionLogRepository interface { Create(log *models.UserActionLog) error From 7d527d9a6712a93deb564ced89c512af24b9abad Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Sun, 28 Sep 2025 01:14:35 +0800 Subject: [PATCH 09/13] =?UTF-8?q?=E5=8A=A0=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/app/controller/response.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/internal/app/controller/response.go b/internal/app/controller/response.go index 422026b..7f180c7 100644 --- a/internal/app/controller/response.go +++ b/internal/app/controller/response.go @@ -63,7 +63,15 @@ func setAuditDetails(c *gin.Context, actionType, description string, targetResou // SendSuccessWithAudit 发送成功的响应,并设置审计日志所需的信息。 // 这是控制器中用于记录成功操作并返回响应的首选函数。 -func SendSuccessWithAudit(ctx *gin.Context, code ResponseCode, message string, data interface{}, actionType, description string, targetResource interface{}) { +func SendSuccessWithAudit( + ctx *gin.Context, // Gin上下文,用于处理HTTP请求和响应 + code ResponseCode, // 业务状态码,表示操作结果 + message string, // 提示信息,向用户展示操作结果的文本描述 + data interface{}, // 业务数据,操作成功后返回的具体数据 + actionType string, // 审计操作类型,例如"创建用户", "更新配置" + description string, // 审计描述,对操作的详细说明 + targetResource interface{}, // 审计目标资源,被操作的资源对象或其标识 +) { // 1. 设置审计信息 setAuditDetails(ctx, actionType, description, targetResource) // 2. 发送响应 @@ -72,7 +80,14 @@ func SendSuccessWithAudit(ctx *gin.Context, code ResponseCode, message string, d // SendErrorWithAudit 发送失败的响应,并设置审计日志所需的信息。 // 这是控制器中用于记录失败操作并返回响应的首选函数。 -func SendErrorWithAudit(ctx *gin.Context, code ResponseCode, message string, actionType, description string, targetResource interface{}) { +func SendErrorWithAudit( + ctx *gin.Context, // Gin上下文,用于处理HTTP请求和响应 + code ResponseCode, // 业务状态码,表示操作结果 + message string, // 提示信息,向用户展示操作结果的文本描述 + actionType string, // 审计操作类型,例如"登录失败", "删除失败" + description string, // 审计描述,对操作的详细说明 + targetResource interface{}, // 审计目标资源,被操作的资源对象或其标识 +) { // 1. 设置审计信息 setAuditDetails(ctx, actionType, description, targetResource) // 2. 发送响应 From 17344cdb896b6880e25bbd5bb882c78a35d65f30 Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Sun, 28 Sep 2025 01:23:50 +0800 Subject: [PATCH 10/13] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=AE=A1=E8=AE=A1?= =?UTF-8?q?=E8=BE=93=E5=87=BA(=E5=88=9D=E6=AD=A5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/device/device_controller.go | 52 +++++------ .../app/controller/plan/plan_controller.go | 88 +++++++++---------- 2 files changed, 70 insertions(+), 70 deletions(-) diff --git a/internal/app/controller/device/device_controller.go b/internal/app/controller/device/device_controller.go index 97d5d10..95f10ba 100644 --- a/internal/app/controller/device/device_controller.go +++ b/internal/app/controller/device/device_controller.go @@ -123,14 +123,14 @@ func (c *Controller) CreateDevice(ctx *gin.Context) { var req CreateDeviceRequest if err := ctx.ShouldBindJSON(&req); err != nil { c.logger.Errorf("创建设备: 参数绑定失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeBadRequest, err.Error()) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), "创建设备", "请求体绑定失败", req) return } propertiesJSON, err := json.Marshal(req.Properties) if err != nil { c.logger.Errorf("创建设备: 序列化属性失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "属性字段格式错误") + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "属性字段格式错误", "创建设备", "属性序列化失败", req.Properties) return } @@ -146,24 +146,24 @@ func (c *Controller) CreateDevice(ctx *gin.Context) { // 在创建设备前进行自检 if !device.SelfCheck() { c.logger.Errorf("创建设备: 设备属性自检失败: %v", device) - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "设备属性不符合要求") + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "设备属性不符合要求", "创建设备", "设备属性自检失败", device) return } if err := c.repo.Create(device); err != nil { c.logger.Errorf("创建设备: 数据库操作失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "创建设备失败") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "创建设备失败", "创建设备", "数据库创建失败", device) return } resp, err := newDeviceResponse(device) if err != nil { c.logger.Errorf("创建设备: 序列化响应失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "设备创建成功,但响应生成失败") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备创建成功,但响应生成失败", "创建设备", "响应序列化失败", device) return } - controller.SendResponse(ctx, controller.CodeCreated, "设备创建成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeCreated, "设备创建成功", resp, "创建设备", "设备创建成功", resp) } // GetDevice godoc @@ -180,26 +180,26 @@ func (c *Controller) GetDevice(ctx *gin.Context) { device, err := c.repo.FindByIDString(deviceID) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - controller.SendErrorResponse(ctx, controller.CodeNotFound, "设备未找到") + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", "获取设备", "设备不存在", deviceID) return } if strings.Contains(err.Error(), "无效的设备ID格式") { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, err.Error()) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), "获取设备", "设备ID格式错误", deviceID) return } c.logger.Errorf("获取设备: 数据库操作失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取设备信息失败") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备信息失败", "获取设备", "数据库查询失败", deviceID) return } resp, err := newDeviceResponse(device) if err != nil { c.logger.Errorf("获取设备: 序列化响应失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取设备信息失败: 内部数据格式错误") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备信息失败: 内部数据格式错误", "获取设备", "响应序列化失败", device) return } - controller.SendResponse(ctx, controller.CodeSuccess, "获取设备信息成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取设备信息成功", resp, "获取设备", "获取设备信息成功", resp) } // ListDevices godoc @@ -213,18 +213,18 @@ func (c *Controller) ListDevices(ctx *gin.Context) { devices, err := c.repo.ListAll() if err != nil { c.logger.Errorf("获取设备列表: 数据库操作失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取设备列表失败") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备列表失败", "获取设备列表", "数据库查询失败", nil) return } resp, err := newListDeviceResponse(devices) if err != nil { c.logger.Errorf("获取设备列表: 序列化响应失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取设备列表失败: 内部数据格式错误") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备列表失败: 内部数据格式错误", "获取设备列表", "响应序列化失败", devices) return } - controller.SendResponse(ctx, controller.CodeSuccess, "获取设备列表成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取设备列表成功", resp, "获取设备列表", "获取设备列表成功", resp) } // UpdateDevice godoc @@ -244,15 +244,15 @@ func (c *Controller) UpdateDevice(ctx *gin.Context) { existingDevice, err := c.repo.FindByIDString(deviceID) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - controller.SendErrorResponse(ctx, controller.CodeNotFound, "设备未找到") + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", "更新设备", "设备不存在", deviceID) return } if strings.Contains(err.Error(), "无效的设备ID格式") { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, err.Error()) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), "更新设备", "设备ID格式错误", deviceID) return } c.logger.Errorf("更新设备: 查找设备失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "更新设备失败") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新设备失败", "更新设备", "数据库查询失败", deviceID) return } @@ -260,14 +260,14 @@ func (c *Controller) UpdateDevice(ctx *gin.Context) { var req UpdateDeviceRequest if err := ctx.ShouldBindJSON(&req); err != nil { c.logger.Errorf("更新设备: 参数绑定失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeBadRequest, err.Error()) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), "更新设备", "请求体绑定失败", req) return } propertiesJSON, err := json.Marshal(req.Properties) if err != nil { c.logger.Errorf("更新设备: 序列化属性失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "属性字段格式错误") + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "属性字段格式错误", "更新设备", "属性序列化失败", req.Properties) return } @@ -282,25 +282,25 @@ func (c *Controller) UpdateDevice(ctx *gin.Context) { // 在更新设备前进行自检 if !existingDevice.SelfCheck() { c.logger.Errorf("更新设备: 设备属性自检失败: %v", existingDevice) - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "设备属性不符合要求") + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "设备属性不符合要求", "更新设备", "设备属性自检失败", existingDevice) return } // 4. 将修改后的 existingDevice 对象保存回数据库 if err := c.repo.Update(existingDevice); err != nil { c.logger.Errorf("更新设备: 数据库操作失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "更新设备失败") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新设备失败", "更新设备", "数据库更新失败", existingDevice) return } resp, err := newDeviceResponse(existingDevice) if err != nil { c.logger.Errorf("更新设备: 序列化响应失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "设备更新成功,但响应生成失败") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备更新成功,但响应生成失败", "更新设备", "响应序列化失败", existingDevice) return } - controller.SendResponse(ctx, controller.CodeSuccess, "设备更新成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "设备更新成功", resp, "更新设备", "设备更新成功", resp) } // DeleteDevice godoc @@ -317,15 +317,15 @@ func (c *Controller) DeleteDevice(ctx *gin.Context) { // 我们需要先将字符串ID转换为uint,因为Delete方法需要uint类型 idUint, err := strconv.ParseUint(deviceID, 10, 64) if err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的设备ID格式") + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的设备ID格式", "删除设备", "设备ID格式错误", deviceID) return } if err := c.repo.Delete(uint(idUint)); err != nil { c.logger.Errorf("删除设备: 数据库操作失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "删除设备失败") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除设备失败", "删除设备", "数据库删除失败", deviceID) return } - controller.SendResponse(ctx, controller.CodeSuccess, "设备删除成功", nil) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "设备删除成功", nil, "删除设备", "设备删除成功", deviceID) } diff --git a/internal/app/controller/plan/plan_controller.go b/internal/app/controller/plan/plan_controller.go index 746f0df..1877417 100644 --- a/internal/app/controller/plan/plan_controller.go +++ b/internal/app/controller/plan/plan_controller.go @@ -119,14 +119,14 @@ func NewController(logger *logs.Logger, planRepo repository.PlanRepository, anal func (c *Controller) CreatePlan(ctx *gin.Context) { var req CreatePlanRequest if err := ctx.ShouldBindJSON(&req); err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error()) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), "创建计划", "请求体绑定失败", req) return } // 使用已有的转换函数,它已经包含了验证和重排逻辑 planToCreate, err := PlanFromCreateRequest(&req) if err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error()) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error(), "创建计划", "计划数据校验失败", req) return } @@ -140,7 +140,7 @@ func (c *Controller) CreatePlan(ctx *gin.Context) { // 调用仓库方法创建计划 if err := c.planRepo.CreatePlan(planToCreate); err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "创建计划失败: "+err.Error()) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "创建计划失败: "+err.Error(), "创建计划", "数据库创建计划失败", planToCreate) return } @@ -154,12 +154,12 @@ func (c *Controller) CreatePlan(ctx *gin.Context) { resp, err := PlanToResponse(planToCreate) if err != nil { c.logger.Errorf("创建计划: 序列化响应失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "计划创建成功,但响应生成失败") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划创建成功,但响应生成失败", "创建计划", "响应序列化失败", planToCreate) return } // 使用统一的成功响应函数 - controller.SendResponse(ctx, controller.CodeCreated, "计划创建成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeCreated, "计划创建成功", resp, "创建计划", "计划创建成功", resp) } // GetPlan godoc @@ -175,7 +175,7 @@ func (c *Controller) GetPlan(ctx *gin.Context) { idStr := ctx.Param("id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的计划ID格式") + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", "获取计划详情", "计划ID格式错误", idStr) return } @@ -184,12 +184,12 @@ func (c *Controller) GetPlan(ctx *gin.Context) { if err != nil { // 判断是否为“未找到”错误 if errors.Is(err, gorm.ErrRecordNotFound) { - controller.SendErrorResponse(ctx, controller.CodeNotFound, "计划不存在") + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", "获取计划详情", "计划不存在", id) return } // 其他数据库错误视为内部错误 c.logger.Errorf("获取计划详情失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误", "获取计划详情", "数据库查询失败", id) return } @@ -197,12 +197,12 @@ func (c *Controller) GetPlan(ctx *gin.Context) { resp, err := PlanToResponse(plan) if err != nil { c.logger.Errorf("获取计划详情: 序列化响应失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划详情失败: 内部数据格式错误") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情失败: 内部数据格式错误", "获取计划详情", "响应序列化失败", plan) return } // 4. 发送成功响应 - controller.SendResponse(ctx, controller.CodeSuccess, "获取计划详情成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取计划详情成功", resp, "获取计划详情", "获取计划详情成功", resp) } // ListPlans godoc @@ -217,7 +217,7 @@ func (c *Controller) ListPlans(ctx *gin.Context) { plans, err := c.planRepo.ListBasicPlans() if err != nil { c.logger.Errorf("获取计划列表失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划列表时发生内部错误") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划列表时发生内部错误", "获取计划列表", "数据库查询失败", nil) return } @@ -227,7 +227,7 @@ func (c *Controller) ListPlans(ctx *gin.Context) { resp, err := PlanToResponse(&p) if err != nil { c.logger.Errorf("获取计划列表: 序列化响应失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划列表失败: 内部数据格式错误") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划列表失败: 内部数据格式错误", "获取计划列表", "响应序列化失败", p) return } planResponses = append(planResponses, *resp) @@ -238,7 +238,7 @@ func (c *Controller) ListPlans(ctx *gin.Context) { Plans: planResponses, Total: len(planResponses), } - controller.SendResponse(ctx, controller.CodeSuccess, "获取计划列表成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取计划列表成功", resp, "获取计划列表", "获取计划列表成功", resp) } // UpdatePlan godoc @@ -256,21 +256,21 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { idStr := ctx.Param("id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的计划ID格式") + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", "更新计划", "计划ID格式错误", idStr) return } // 2. 绑定请求体 var req UpdatePlanRequest if err := ctx.ShouldBindJSON(&req); err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error()) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), "更新计划", "请求体绑定失败", req) return } // 3. 将请求转换为模型(转换函数带校验) planToUpdate, err := PlanFromUpdateRequest(&req) if err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error()) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error(), "更新计划", "计划数据校验失败", req) return } planToUpdate.ID = uint(id) // 确保ID被设置 @@ -287,11 +287,11 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { _, err = c.planRepo.GetBasicPlanByID(uint(id)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - controller.SendErrorResponse(ctx, controller.CodeNotFound, "计划不存在") + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", "更新计划", "计划不存在", id) return } c.logger.Errorf("获取计划详情失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误", "更新计划", "数据库查询失败", id) return } @@ -301,7 +301,7 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { c.logger.Infof("计划 #%d 被更新,执行计数器已重置为 0。", planToUpdate.ID) if err := c.planRepo.UpdatePlan(planToUpdate); err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "更新计划失败: "+err.Error()) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "更新计划失败: "+err.Error(), "更新计划", "数据库更新计划失败", planToUpdate) return } @@ -315,7 +315,7 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { updatedPlan, err := c.planRepo.GetPlanByID(uint(id)) if err != nil { c.logger.Errorf("获取更新后的计划详情失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取更新后计划详情时发生内部错误") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取更新后计划详情时发生内部错误", "更新计划", "获取更新后计划详情失败", id) return } @@ -323,12 +323,12 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { resp, err := PlanToResponse(updatedPlan) if err != nil { c.logger.Errorf("更新计划: 序列化响应失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "计划更新成功,但响应生成失败") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划更新成功,但响应生成失败", "更新计划", "响应序列化失败", updatedPlan) return } // 8. 发送成功响应 - controller.SendResponse(ctx, controller.CodeSuccess, "计划更新成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划更新成功", resp, "更新计划", "计划更新成功", resp) } // DeletePlan godoc @@ -344,7 +344,7 @@ func (c *Controller) DeletePlan(ctx *gin.Context) { idStr := ctx.Param("id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的计划ID格式") + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", "删除计划", "计划ID格式错误", idStr) return } @@ -352,11 +352,11 @@ func (c *Controller) DeletePlan(ctx *gin.Context) { plan, err := c.planRepo.GetBasicPlanByID(uint(id)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - controller.SendErrorResponse(ctx, controller.CodeNotFound, "计划不存在") + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", "删除计划", "计划不存在", id) return } c.logger.Errorf("启动计划时获取计划信息失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", "删除计划", "数据库查询失败", id) return } @@ -364,20 +364,20 @@ func (c *Controller) DeletePlan(ctx *gin.Context) { if plan.Status == models.PlanStatusEnabled { if err := c.planRepo.StopPlanTransactionally(uint(id)); err != nil { c.logger.Errorf("停止计划 #%d 失败: %v", id, err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "停止计划时发生内部错误: "+err.Error()) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "停止计划时发生内部错误: "+err.Error(), "删除计划", "停止计划失败", id) return } } // 4. 调用仓库层删除计划 if err := c.planRepo.DeletePlan(uint(id)); err != nil { - c.logger.Errorf("删除计划失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "删除计划时发生内部错误") + c.logger.Errorf("删除计划: 数据库操作失败: %v", err) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除计划时发生内部错误", "删除计划", "数据库删除失败", id) return } // 5. 发送成功响应 - controller.SendResponse(ctx, controller.CodeSuccess, "计划删除成功", nil) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划删除成功", nil, "删除计划", "计划删除成功", id) } // StartPlan godoc @@ -393,7 +393,7 @@ func (c *Controller) StartPlan(ctx *gin.Context) { idStr := ctx.Param("id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的计划ID格式") + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", "启动计划", "计划ID格式错误", idStr) return } @@ -401,17 +401,17 @@ func (c *Controller) StartPlan(ctx *gin.Context) { plan, err := c.planRepo.GetBasicPlanByID(uint(id)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - controller.SendErrorResponse(ctx, controller.CodeNotFound, "计划不存在") + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", "启动计划", "计划不存在", id) return } c.logger.Errorf("启动计划时获取计划信息失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", "启动计划", "数据库查询失败", id) return } // 3. 检查计划当前状态 if plan.Status == models.PlanStatusEnabled { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "计划已处于启动状态,无需重复操作") + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划已处于启动状态,无需重复操作", "启动计划", "计划已启动", id) return } @@ -422,7 +422,7 @@ func (c *Controller) StartPlan(ctx *gin.Context) { if plan.ExecuteCount > 0 { if err := c.planRepo.UpdateExecuteCount(plan.ID, 0); err != nil { c.logger.Errorf("重置计划 #%d 执行计数失败: %v", plan.ID, err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "重置计划执行计数失败") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "重置计划执行计数失败", "启动计划", "重置执行计数失败", plan.ID) return } c.logger.Infof("计划 #%d 的执行计数器已重置为 0。", plan.ID) @@ -431,14 +431,14 @@ func (c *Controller) StartPlan(ctx *gin.Context) { // 更新计划状态为“已启动” if err := c.planRepo.UpdatePlanStatus(plan.ID, models.PlanStatusEnabled); err != nil { c.logger.Errorf("更新计划 #%d 状态失败: %v", plan.ID, err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "更新计划状态失败") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新计划状态失败", "启动计划", "更新计划状态失败", plan.ID) return } c.logger.Infof("已成功更新计划 #%d 的状态为 '已启动'。", plan.ID) } else { // 如果计划已经处于 Enabled 状态,则无需更新 c.logger.Infof("计划 #%d 已处于启动状态,无需重复操作。", plan.ID) - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "计划已处于启动状态,无需重复操作") + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划已处于启动状态,无需重复操作", "启动计划", "计划已处于启动状态", plan.ID) return } @@ -446,12 +446,12 @@ func (c *Controller) StartPlan(ctx *gin.Context) { if err := c.analysisPlanTaskManager.CreateOrUpdateTrigger(plan.ID); err != nil { // 此处错误不回滚状态,因为状态更新已成功,但需要明确告知用户触发器创建失败 c.logger.Errorf("为计划 #%d 创建或更新触发器失败: %v", plan.ID, err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "计划状态已更新,但创建执行触发器失败,请检查计划配置或稍后重试") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划状态已更新,但创建执行触发器失败,请检查计划配置或稍后重试", "启动计划", "创建执行触发器失败", plan.ID) return } // 6. 发送成功响应 - controller.SendResponse(ctx, controller.CodeSuccess, "计划已成功启动", nil) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划已成功启动", nil, "启动计划", "计划已成功启动", id) } // StopPlan godoc @@ -467,7 +467,7 @@ func (c *Controller) StopPlan(ctx *gin.Context) { idStr := ctx.Param("id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的计划ID格式") + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", "停止计划", "计划ID格式错误", idStr) return } @@ -475,27 +475,27 @@ func (c *Controller) StopPlan(ctx *gin.Context) { plan, err := c.planRepo.GetBasicPlanByID(uint(id)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - controller.SendErrorResponse(ctx, controller.CodeNotFound, "计划不存在") + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", "停止计划", "计划不存在", id) return } c.logger.Errorf("启动计划时获取计划信息失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误") + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", "停止计划", "数据库查询失败", id) return } // 3. 检查计划当前状态 if plan.Status != models.PlanStatusEnabled { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "计划当前不是启用状态") + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划当前不是启用状态", "停止计划", "计划未启用", id) return } // 4. 调用仓库层方法,该方法内部处理事务 if err := c.planRepo.StopPlanTransactionally(uint(id)); err != nil { c.logger.Errorf("停止计划 #%d 失败: %v", id, err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "停止计划时发生内部错误: "+err.Error()) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "停止计划时发生内部错误: "+err.Error(), "停止计划", "停止计划失败", id) return } // 5. 发送成功响应 - controller.SendResponse(ctx, controller.CodeSuccess, "计划已成功停止", nil) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划已成功停止", nil, "停止计划", "计划已成功停止", id) } From 72d8b45241878229da5b23140817ac917797610d Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Sun, 28 Sep 2025 01:28:54 +0800 Subject: [PATCH 11/13] =?UTF-8?q?=E8=B0=83=E6=95=B4=E5=AE=A1=E8=AE=A1?= =?UTF-8?q?=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/device/device_controller.go | 57 ++++++------ .../app/controller/plan/plan_controller.go | 93 ++++++++++--------- 2 files changed, 81 insertions(+), 69 deletions(-) diff --git a/internal/app/controller/device/device_controller.go b/internal/app/controller/device/device_controller.go index 95f10ba..92d6c6f 100644 --- a/internal/app/controller/device/device_controller.go +++ b/internal/app/controller/device/device_controller.go @@ -120,17 +120,18 @@ func newListDeviceResponse(devices []*models.Device) ([]*DeviceResponse, error) // @Success 200 {object} controller.Response{data=DeviceResponse} // @Router /api/v1/devices [post] func (c *Controller) CreateDevice(ctx *gin.Context) { + const actionType = "创建设备" var req CreateDeviceRequest if err := ctx.ShouldBindJSON(&req); err != nil { c.logger.Errorf("创建设备: 参数绑定失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), "创建设备", "请求体绑定失败", req) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req) return } propertiesJSON, err := json.Marshal(req.Properties) if err != nil { c.logger.Errorf("创建设备: 序列化属性失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "属性字段格式错误", "创建设备", "属性序列化失败", req.Properties) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "属性字段格式错误", actionType, "属性序列化失败", req.Properties) return } @@ -146,24 +147,24 @@ func (c *Controller) CreateDevice(ctx *gin.Context) { // 在创建设备前进行自检 if !device.SelfCheck() { c.logger.Errorf("创建设备: 设备属性自检失败: %v", device) - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "设备属性不符合要求", "创建设备", "设备属性自检失败", device) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "设备属性不符合要求", actionType, "设备属性自检失败", device) return } if err := c.repo.Create(device); err != nil { c.logger.Errorf("创建设备: 数据库操作失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "创建设备失败", "创建设备", "数据库创建失败", device) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "创建设备失败: "+err.Error(), actionType, "数据库创建失败", device) return } resp, err := newDeviceResponse(device) if err != nil { c.logger.Errorf("创建设备: 序列化响应失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备创建成功,但响应生成失败", "创建设备", "响应序列化失败", device) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备创建成功,但响应生成失败", actionType, "响应序列化失败", device) return } - controller.SendSuccessWithAudit(ctx, controller.CodeCreated, "设备创建成功", resp, "创建设备", "设备创建成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeCreated, "设备创建成功", resp, actionType, "设备创建成功", resp) } // GetDevice godoc @@ -175,31 +176,32 @@ func (c *Controller) CreateDevice(ctx *gin.Context) { // @Success 200 {object} controller.Response{data=DeviceResponse} // @Router /api/v1/devices/{id} [get] func (c *Controller) GetDevice(ctx *gin.Context) { + const actionType = "获取设备" deviceID := ctx.Param("id") device, err := c.repo.FindByIDString(deviceID) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", "获取设备", "设备不存在", deviceID) + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", actionType, "设备不存在", deviceID) return } if strings.Contains(err.Error(), "无效的设备ID格式") { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), "获取设备", "设备ID格式错误", deviceID) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), actionType, "设备ID格式错误", deviceID) return } c.logger.Errorf("获取设备: 数据库操作失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备信息失败", "获取设备", "数据库查询失败", deviceID) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备信息失败: "+err.Error(), actionType, "数据库查询失败", deviceID) return } resp, err := newDeviceResponse(device) if err != nil { c.logger.Errorf("获取设备: 序列化响应失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备信息失败: 内部数据格式错误", "获取设备", "响应序列化失败", device) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备信息失败: 内部数据格式错误", actionType, "响应序列化失败", device) return } - controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取设备信息成功", resp, "获取设备", "获取设备信息成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取设备信息成功", resp, actionType, "获取设备信息成功", resp) } // ListDevices godoc @@ -210,21 +212,22 @@ func (c *Controller) GetDevice(ctx *gin.Context) { // @Success 200 {object} controller.Response{data=[]DeviceResponse} // @Router /api/v1/devices [get] func (c *Controller) ListDevices(ctx *gin.Context) { + const actionType = "获取设备列表" devices, err := c.repo.ListAll() if err != nil { c.logger.Errorf("获取设备列表: 数据库操作失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备列表失败", "获取设备列表", "数据库查询失败", nil) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备列表失败: "+err.Error(), actionType, "数据库查询失败", nil) return } resp, err := newListDeviceResponse(devices) if err != nil { c.logger.Errorf("获取设备列表: 序列化响应失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备列表失败: 内部数据格式错误", "获取设备列表", "响应序列化失败", devices) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备列表失败: 内部数据格式错误", actionType, "响应序列化失败", devices) return } - controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取设备列表成功", resp, "获取设备列表", "获取设备列表成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取设备列表成功", resp, actionType, "获取设备列表成功", resp) } // UpdateDevice godoc @@ -238,21 +241,22 @@ func (c *Controller) ListDevices(ctx *gin.Context) { // @Success 200 {object} controller.Response{data=DeviceResponse} // @Router /api/v1/devices/{id} [put] func (c *Controller) UpdateDevice(ctx *gin.Context) { + const actionType = "更新设备" deviceID := ctx.Param("id") // 1. 检查设备是否存在 existingDevice, err := c.repo.FindByIDString(deviceID) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", "更新设备", "设备不存在", deviceID) + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", actionType, "设备不存在", deviceID) return } if strings.Contains(err.Error(), "无效的设备ID格式") { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), "更新设备", "设备ID格式错误", deviceID) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), actionType, "设备ID格式错误", deviceID) return } c.logger.Errorf("更新设备: 查找设备失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新设备失败", "更新设备", "数据库查询失败", deviceID) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新设备失败: "+err.Error(), actionType, "数据库查询失败", deviceID) return } @@ -260,14 +264,14 @@ func (c *Controller) UpdateDevice(ctx *gin.Context) { var req UpdateDeviceRequest if err := ctx.ShouldBindJSON(&req); err != nil { c.logger.Errorf("更新设备: 参数绑定失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), "更新设备", "请求体绑定失败", req) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req) return } propertiesJSON, err := json.Marshal(req.Properties) if err != nil { c.logger.Errorf("更新设备: 序列化属性失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "属性字段格式错误", "更新设备", "属性序列化失败", req.Properties) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "属性字段格式错误", actionType, "属性序列化失败", req.Properties) return } @@ -282,25 +286,25 @@ func (c *Controller) UpdateDevice(ctx *gin.Context) { // 在更新设备前进行自检 if !existingDevice.SelfCheck() { c.logger.Errorf("更新设备: 设备属性自检失败: %v", existingDevice) - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "设备属性不符合要求", "更新设备", "设备属性自检失败", existingDevice) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "设备属性不符合要求", actionType, "设备属性自检失败", existingDevice) return } // 4. 将修改后的 existingDevice 对象保存回数据库 if err := c.repo.Update(existingDevice); err != nil { c.logger.Errorf("更新设备: 数据库操作失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新设备失败", "更新设备", "数据库更新失败", existingDevice) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新设备失败: "+err.Error(), actionType, "数据库更新失败", existingDevice) return } resp, err := newDeviceResponse(existingDevice) if err != nil { c.logger.Errorf("更新设备: 序列化响应失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备更新成功,但响应生成失败", "更新设备", "响应序列化失败", existingDevice) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备更新成功,但响应生成失败", actionType, "响应序列化失败", existingDevice) return } - controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "设备更新成功", resp, "更新设备", "设备更新成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "设备更新成功", resp, actionType, "设备更新成功", resp) } // DeleteDevice godoc @@ -312,20 +316,21 @@ func (c *Controller) UpdateDevice(ctx *gin.Context) { // @Success 200 {object} controller.Response // @Router /api/v1/devices/{id} [delete] func (c *Controller) DeleteDevice(ctx *gin.Context) { + const actionType = "删除设备" deviceID := ctx.Param("id") // 我们需要先将字符串ID转换为uint,因为Delete方法需要uint类型 idUint, err := strconv.ParseUint(deviceID, 10, 64) if err != nil { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的设备ID格式", "删除设备", "设备ID格式错误", deviceID) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的设备ID格式", actionType, "设备ID格式错误", deviceID) return } if err := c.repo.Delete(uint(idUint)); err != nil { c.logger.Errorf("删除设备: 数据库操作失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除设备失败", "删除设备", "数据库删除失败", deviceID) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除设备失败: "+err.Error(), actionType, "数据库删除失败", deviceID) return } - controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "设备删除成功", nil, "删除设备", "设备删除成功", deviceID) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "设备删除成功", nil, actionType, "设备删除成功", deviceID) } diff --git a/internal/app/controller/plan/plan_controller.go b/internal/app/controller/plan/plan_controller.go index 1877417..63682ec 100644 --- a/internal/app/controller/plan/plan_controller.go +++ b/internal/app/controller/plan/plan_controller.go @@ -118,15 +118,16 @@ func NewController(logger *logs.Logger, planRepo repository.PlanRepository, anal // @Router /api/v1/plans [post] func (c *Controller) CreatePlan(ctx *gin.Context) { var req CreatePlanRequest + const actionType = "创建计划" if err := ctx.ShouldBindJSON(&req); err != nil { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), "创建计划", "请求体绑定失败", req) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req) return } // 使用已有的转换函数,它已经包含了验证和重排逻辑 planToCreate, err := PlanFromCreateRequest(&req) if err != nil { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error(), "创建计划", "计划数据校验失败", req) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error(), actionType, "计划数据校验失败", req) return } @@ -140,7 +141,7 @@ func (c *Controller) CreatePlan(ctx *gin.Context) { // 调用仓库方法创建计划 if err := c.planRepo.CreatePlan(planToCreate); err != nil { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "创建计划失败: "+err.Error(), "创建计划", "数据库创建计划失败", planToCreate) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "创建计划失败: "+err.Error(), actionType, "数据库创建计划失败", planToCreate) return } @@ -154,12 +155,12 @@ func (c *Controller) CreatePlan(ctx *gin.Context) { resp, err := PlanToResponse(planToCreate) if err != nil { c.logger.Errorf("创建计划: 序列化响应失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划创建成功,但响应生成失败", "创建计划", "响应序列化失败", planToCreate) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划创建成功,但响应生成失败", actionType, "响应序列化失败", planToCreate) return } // 使用统一的成功响应函数 - controller.SendSuccessWithAudit(ctx, controller.CodeCreated, "计划创建成功", resp, "创建计划", "计划创建成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeCreated, "计划创建成功", resp, actionType, "计划创建成功", resp) } // GetPlan godoc @@ -171,11 +172,12 @@ func (c *Controller) CreatePlan(ctx *gin.Context) { // @Success 200 {object} controller.Response{data=plan.PlanResponse} "业务码为200代表成功获取" // @Router /api/v1/plans/{id} [get] func (c *Controller) GetPlan(ctx *gin.Context) { + const actionType = "获取计划详情" // 1. 从 URL 路径中获取 ID idStr := ctx.Param("id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", "获取计划详情", "计划ID格式错误", idStr) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) return } @@ -184,12 +186,12 @@ func (c *Controller) GetPlan(ctx *gin.Context) { if err != nil { // 判断是否为“未找到”错误 if errors.Is(err, gorm.ErrRecordNotFound) { - controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", "获取计划详情", "计划不存在", id) + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id) return } // 其他数据库错误视为内部错误 c.logger.Errorf("获取计划详情失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误", "获取计划详情", "数据库查询失败", id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误", actionType, "数据库查询失败", id) return } @@ -197,12 +199,12 @@ func (c *Controller) GetPlan(ctx *gin.Context) { resp, err := PlanToResponse(plan) if err != nil { c.logger.Errorf("获取计划详情: 序列化响应失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情失败: 内部数据格式错误", "获取计划详情", "响应序列化失败", plan) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情失败: 内部数据格式错误", actionType, "响应序列化失败", plan) return } // 4. 发送成功响应 - controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取计划详情成功", resp, "获取计划详情", "获取计划详情成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取计划详情成功", resp, actionType, "获取计划详情成功", resp) } // ListPlans godoc @@ -213,11 +215,12 @@ func (c *Controller) GetPlan(ctx *gin.Context) { // @Success 200 {object} controller.Response{data=plan.ListPlansResponse} "业务码为200代表成功获取列表" // @Router /api/v1/plans [get] func (c *Controller) ListPlans(ctx *gin.Context) { + const actionType = "获取计划列表" // 1. 调用仓库层获取所有计划 plans, err := c.planRepo.ListBasicPlans() if err != nil { c.logger.Errorf("获取计划列表失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划列表时发生内部错误", "获取计划列表", "数据库查询失败", nil) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划列表时发生内部错误", actionType, "数据库查询失败", nil) return } @@ -227,7 +230,7 @@ func (c *Controller) ListPlans(ctx *gin.Context) { resp, err := PlanToResponse(&p) if err != nil { c.logger.Errorf("获取计划列表: 序列化响应失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划列表失败: 内部数据格式错误", "获取计划列表", "响应序列化失败", p) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划列表失败: 内部数据格式错误", actionType, "响应序列化失败", p) return } planResponses = append(planResponses, *resp) @@ -238,7 +241,7 @@ func (c *Controller) ListPlans(ctx *gin.Context) { Plans: planResponses, Total: len(planResponses), } - controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取计划列表成功", resp, "获取计划列表", "获取计划列表成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取计划列表成功", resp, actionType, "获取计划列表成功", resp) } // UpdatePlan godoc @@ -252,25 +255,26 @@ func (c *Controller) ListPlans(ctx *gin.Context) { // @Success 200 {object} controller.Response{data=plan.PlanResponse} "业务码为200代表更新成功" // @Router /api/v1/plans/{id} [put] func (c *Controller) UpdatePlan(ctx *gin.Context) { + const actionType = "更新计划" // 1. 从 URL 路径中获取 ID idStr := ctx.Param("id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", "更新计划", "计划ID格式错误", idStr) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) return } // 2. 绑定请求体 var req UpdatePlanRequest if err := ctx.ShouldBindJSON(&req); err != nil { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), "更新计划", "请求体绑定失败", req) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req) return } // 3. 将请求转换为模型(转换函数带校验) planToUpdate, err := PlanFromUpdateRequest(&req) if err != nil { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error(), "更新计划", "计划数据校验失败", req) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error(), actionType, "计划数据校验失败", req) return } planToUpdate.ID = uint(id) // 确保ID被设置 @@ -287,11 +291,11 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { _, err = c.planRepo.GetBasicPlanByID(uint(id)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", "更新计划", "计划不存在", id) + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id) return } c.logger.Errorf("获取计划详情失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误", "更新计划", "数据库查询失败", id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误", actionType, "数据库查询失败", id) return } @@ -301,7 +305,7 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { c.logger.Infof("计划 #%d 被更新,执行计数器已重置为 0。", planToUpdate.ID) if err := c.planRepo.UpdatePlan(planToUpdate); err != nil { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "更新计划失败: "+err.Error(), "更新计划", "数据库更新计划失败", planToUpdate) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新计划失败: "+err.Error(), actionType, "数据库更新计划失败", planToUpdate) return } @@ -315,7 +319,7 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { updatedPlan, err := c.planRepo.GetPlanByID(uint(id)) if err != nil { c.logger.Errorf("获取更新后的计划详情失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取更新后计划详情时发生内部错误", "更新计划", "获取更新后计划详情失败", id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取更新后计划详情时发生内部错误", actionType, "获取更新后计划详情失败", id) return } @@ -323,12 +327,12 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { resp, err := PlanToResponse(updatedPlan) if err != nil { c.logger.Errorf("更新计划: 序列化响应失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划更新成功,但响应生成失败", "更新计划", "响应序列化失败", updatedPlan) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划更新成功,但响应生成失败", actionType, "响应序列化失败", updatedPlan) return } // 8. 发送成功响应 - controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划更新成功", resp, "更新计划", "计划更新成功", resp) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划更新成功", resp, actionType, "计划更新成功", resp) } // DeletePlan godoc @@ -340,11 +344,12 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { // @Success 200 {object} controller.Response "业务码为200代表删除成功" // @Router /api/v1/plans/{id} [delete] func (c *Controller) DeletePlan(ctx *gin.Context) { + const actionType = "删除计划" // 1. 从 URL 路径中获取 ID idStr := ctx.Param("id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", "删除计划", "计划ID格式错误", idStr) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) return } @@ -352,11 +357,11 @@ func (c *Controller) DeletePlan(ctx *gin.Context) { plan, err := c.planRepo.GetBasicPlanByID(uint(id)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", "删除计划", "计划不存在", id) + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id) return } c.logger.Errorf("启动计划时获取计划信息失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", "删除计划", "数据库查询失败", id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", actionType, "数据库查询失败", id) return } @@ -364,7 +369,7 @@ func (c *Controller) DeletePlan(ctx *gin.Context) { if plan.Status == models.PlanStatusEnabled { if err := c.planRepo.StopPlanTransactionally(uint(id)); err != nil { c.logger.Errorf("停止计划 #%d 失败: %v", id, err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "停止计划时发生内部错误: "+err.Error(), "删除计划", "停止计划失败", id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "停止计划时发生内部错误: "+err.Error(), actionType, "停止计划失败", id) return } } @@ -372,12 +377,12 @@ func (c *Controller) DeletePlan(ctx *gin.Context) { // 4. 调用仓库层删除计划 if err := c.planRepo.DeletePlan(uint(id)); err != nil { c.logger.Errorf("删除计划: 数据库操作失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除计划时发生内部错误", "删除计划", "数据库删除失败", id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除计划时发生内部错误", actionType, "数据库删除失败", id) return } // 5. 发送成功响应 - controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划删除成功", nil, "删除计划", "计划删除成功", id) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划删除成功", nil, actionType, "计划删除成功", id) } // StartPlan godoc @@ -389,11 +394,12 @@ func (c *Controller) DeletePlan(ctx *gin.Context) { // @Success 200 {object} controller.Response "业务码为200代表成功启动计划" // @Router /api/v1/plans/{id}/start [post] func (c *Controller) StartPlan(ctx *gin.Context) { + const actionType = "启动计划" // 1. 从 URL 路径中获取 ID idStr := ctx.Param("id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", "启动计划", "计划ID格式错误", idStr) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) return } @@ -401,17 +407,17 @@ func (c *Controller) StartPlan(ctx *gin.Context) { plan, err := c.planRepo.GetBasicPlanByID(uint(id)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", "启动计划", "计划不存在", id) + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id) return } c.logger.Errorf("启动计划时获取计划信息失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", "启动计划", "数据库查询失败", id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", actionType, "数据库查询失败", id) return } // 3. 检查计划当前状态 if plan.Status == models.PlanStatusEnabled { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划已处于启动状态,无需重复操作", "启动计划", "计划已启动", id) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划已处于启动状态,无需重复操作", actionType, "计划已处于启动状态", id) return } @@ -422,7 +428,7 @@ func (c *Controller) StartPlan(ctx *gin.Context) { if plan.ExecuteCount > 0 { if err := c.planRepo.UpdateExecuteCount(plan.ID, 0); err != nil { c.logger.Errorf("重置计划 #%d 执行计数失败: %v", plan.ID, err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "重置计划执行计数失败", "启动计划", "重置执行计数失败", plan.ID) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "重置计划执行计数失败", actionType, "重置执行计数失败", plan.ID) return } c.logger.Infof("计划 #%d 的执行计数器已重置为 0。", plan.ID) @@ -431,14 +437,14 @@ func (c *Controller) StartPlan(ctx *gin.Context) { // 更新计划状态为“已启动” if err := c.planRepo.UpdatePlanStatus(plan.ID, models.PlanStatusEnabled); err != nil { c.logger.Errorf("更新计划 #%d 状态失败: %v", plan.ID, err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新计划状态失败", "启动计划", "更新计划状态失败", plan.ID) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新计划状态失败", actionType, "更新计划状态失败", plan.ID) return } c.logger.Infof("已成功更新计划 #%d 的状态为 '已启动'。", plan.ID) } else { // 如果计划已经处于 Enabled 状态,则无需更新 c.logger.Infof("计划 #%d 已处于启动状态,无需重复操作。", plan.ID) - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划已处于启动状态,无需重复操作", "启动计划", "计划已处于启动状态", plan.ID) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划已处于启动状态,无需重复操作", actionType, "计划已处于启动状态", plan.ID) return } @@ -446,12 +452,12 @@ func (c *Controller) StartPlan(ctx *gin.Context) { if err := c.analysisPlanTaskManager.CreateOrUpdateTrigger(plan.ID); err != nil { // 此处错误不回滚状态,因为状态更新已成功,但需要明确告知用户触发器创建失败 c.logger.Errorf("为计划 #%d 创建或更新触发器失败: %v", plan.ID, err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划状态已更新,但创建执行触发器失败,请检查计划配置或稍后重试", "启动计划", "创建执行触发器失败", plan.ID) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划状态已更新,但创建执行触发器失败,请检查计划配置或稍后重试", actionType, "创建执行触发器失败", plan.ID) return } // 6. 发送成功响应 - controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划已成功启动", nil, "启动计划", "计划已成功启动", id) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划已成功启动", nil, actionType, "计划已成功启动", id) } // StopPlan godoc @@ -463,11 +469,12 @@ func (c *Controller) StartPlan(ctx *gin.Context) { // @Success 200 {object} controller.Response "业务码为200代表成功停止计划" // @Router /api/v1/plans/{id}/stop [post] func (c *Controller) StopPlan(ctx *gin.Context) { + const actionType = "停止计划" // 1. 从 URL 路径中获取 ID idStr := ctx.Param("id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", "停止计划", "计划ID格式错误", idStr) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) return } @@ -475,27 +482,27 @@ func (c *Controller) StopPlan(ctx *gin.Context) { plan, err := c.planRepo.GetBasicPlanByID(uint(id)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", "停止计划", "计划不存在", id) + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id) return } c.logger.Errorf("启动计划时获取计划信息失败: %v", err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", "停止计划", "数据库查询失败", id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", actionType, "数据库查询失败", id) return } // 3. 检查计划当前状态 if plan.Status != models.PlanStatusEnabled { - controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划当前不是启用状态", "停止计划", "计划未启用", id) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划当前不是启用状态", actionType, "计划未启用", id) return } // 4. 调用仓库层方法,该方法内部处理事务 if err := c.planRepo.StopPlanTransactionally(uint(id)); err != nil { c.logger.Errorf("停止计划 #%d 失败: %v", id, err) - controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "停止计划时发生内部错误: "+err.Error(), "停止计划", "停止计划失败", id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "停止计划时发生内部错误: "+err.Error(), actionType, "停止计划失败", id) return } // 5. 发送成功响应 - controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划已成功停止", nil, "停止计划", "计划已成功停止", id) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划已成功停止", nil, actionType, "计划已成功停止", id) } From aaca5b17232591feb89396fb27f7a0d08d1fd8ae Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Sun, 28 Sep 2025 01:33:19 +0800 Subject: [PATCH 12/13] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/device/device_controller.go | 61 ++++++++++++++----- .../app/controller/plan/plan_controller.go | 61 +++++++++++++------ 2 files changed, 88 insertions(+), 34 deletions(-) diff --git a/internal/app/controller/device/device_controller.go b/internal/app/controller/device/device_controller.go index 92d6c6f..41ac035 100644 --- a/internal/app/controller/device/device_controller.go +++ b/internal/app/controller/device/device_controller.go @@ -123,14 +123,14 @@ func (c *Controller) CreateDevice(ctx *gin.Context) { const actionType = "创建设备" var req CreateDeviceRequest if err := ctx.ShouldBindJSON(&req); err != nil { - c.logger.Errorf("创建设备: 参数绑定失败: %v", err) + c.logger.Errorf("%s: 参数绑定失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req) return } propertiesJSON, err := json.Marshal(req.Properties) if err != nil { - c.logger.Errorf("创建设备: 序列化属性失败: %v", err) + c.logger.Errorf("%s: 序列化属性失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "属性字段格式错误", actionType, "属性序列化失败", req.Properties) return } @@ -146,24 +146,25 @@ func (c *Controller) CreateDevice(ctx *gin.Context) { // 在创建设备前进行自检 if !device.SelfCheck() { - c.logger.Errorf("创建设备: 设备属性自检失败: %v", device) + c.logger.Errorf("%s: 设备属性自检失败: %v", actionType, device) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "设备属性不符合要求", actionType, "设备属性自检失败", device) return } if err := c.repo.Create(device); err != nil { - c.logger.Errorf("创建设备: 数据库操作失败: %v", err) + c.logger.Errorf("%s: 数据库操作失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "创建设备失败: "+err.Error(), actionType, "数据库创建失败", device) return } resp, err := newDeviceResponse(device) if err != nil { - c.logger.Errorf("创建设备: 序列化响应失败: %v", err) + c.logger.Errorf("%s: 序列化响应失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备创建成功,但响应生成失败", actionType, "响应序列化失败", device) return } + c.logger.Infof("%s: 设备创建成功, ID: %d", actionType, device.ID) controller.SendSuccessWithAudit(ctx, controller.CodeCreated, "设备创建成功", resp, actionType, "设备创建成功", resp) } @@ -179,28 +180,37 @@ func (c *Controller) GetDevice(ctx *gin.Context) { const actionType = "获取设备" deviceID := ctx.Param("id") + if deviceID == "" { + c.logger.Errorf("%s: 设备ID为空", actionType) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "设备ID不能为空", actionType, "设备ID为空", nil) + return + } + device, err := c.repo.FindByIDString(deviceID) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { + c.logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", actionType, "设备不存在", deviceID) return } if strings.Contains(err.Error(), "无效的设备ID格式") { + c.logger.Errorf("%s: 设备ID格式错误: %v, ID: %s", actionType, err, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), actionType, "设备ID格式错误", deviceID) return } - c.logger.Errorf("获取设备: 数据库操作失败: %v", err) + c.logger.Errorf("%s: 数据库查询失败: %v, ID: %s", actionType, err, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备信息失败: "+err.Error(), actionType, "数据库查询失败", deviceID) return } resp, err := newDeviceResponse(device) if err != nil { - c.logger.Errorf("获取设备: 序列化响应失败: %v", err) + c.logger.Errorf("%s: 序列化响应失败: %v, Device: %+v", actionType, err, device) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备信息失败: 内部数据格式错误", actionType, "响应序列化失败", device) return } + c.logger.Infof("%s: 获取设备信息成功, ID: %d", actionType, device.ID) controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取设备信息成功", resp, actionType, "获取设备信息成功", resp) } @@ -215,18 +225,19 @@ func (c *Controller) ListDevices(ctx *gin.Context) { const actionType = "获取设备列表" devices, err := c.repo.ListAll() if err != nil { - c.logger.Errorf("获取设备列表: 数据库操作失败: %v", err) + c.logger.Errorf("%s: 数据库查询失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备列表失败: "+err.Error(), actionType, "数据库查询失败", nil) return } resp, err := newListDeviceResponse(devices) if err != nil { - c.logger.Errorf("获取设备列表: 序列化响应失败: %v", err) + c.logger.Errorf("%s: 序列化响应失败: %v, Devices: %+v", actionType, err, devices) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备列表失败: 内部数据格式错误", actionType, "响应序列化失败", devices) return } + c.logger.Infof("%s: 获取设备列表成功, 数量: %d", actionType, len(devices)) controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取设备列表成功", resp, actionType, "获取设备列表成功", resp) } @@ -248,14 +259,16 @@ func (c *Controller) UpdateDevice(ctx *gin.Context) { existingDevice, err := c.repo.FindByIDString(deviceID) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { + c.logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", actionType, "设备不存在", deviceID) return } if strings.Contains(err.Error(), "无效的设备ID格式") { + c.logger.Errorf("%s: 设备ID格式错误: %v, ID: %s", actionType, err, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), actionType, "设备ID格式错误", deviceID) return } - c.logger.Errorf("更新设备: 查找设备失败: %v", err) + c.logger.Errorf("%s: 数据库查询失败: %v, ID: %s", actionType, err, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新设备失败: "+err.Error(), actionType, "数据库查询失败", deviceID) return } @@ -263,14 +276,14 @@ func (c *Controller) UpdateDevice(ctx *gin.Context) { // 2. 绑定请求参数 var req UpdateDeviceRequest if err := ctx.ShouldBindJSON(&req); err != nil { - c.logger.Errorf("更新设备: 参数绑定失败: %v", err) + c.logger.Errorf("%s: 参数绑定失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req) return } propertiesJSON, err := json.Marshal(req.Properties) if err != nil { - c.logger.Errorf("更新设备: 序列化属性失败: %v", err) + c.logger.Errorf("%s: 序列化属性失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "属性字段格式错误", actionType, "属性序列化失败", req.Properties) return } @@ -285,25 +298,26 @@ func (c *Controller) UpdateDevice(ctx *gin.Context) { // 在更新设备前进行自检 if !existingDevice.SelfCheck() { - c.logger.Errorf("更新设备: 设备属性自检失败: %v", existingDevice) + c.logger.Errorf("%s: 设备属性自检失败: %v", actionType, existingDevice) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "设备属性不符合要求", actionType, "设备属性自检失败", existingDevice) return } // 4. 将修改后的 existingDevice 对象保存回数据库 if err := c.repo.Update(existingDevice); err != nil { - c.logger.Errorf("更新设备: 数据库操作失败: %v", err) + c.logger.Errorf("%s: 数据库更新失败: %v, Device: %+v", actionType, err, existingDevice) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新设备失败: "+err.Error(), actionType, "数据库更新失败", existingDevice) return } resp, err := newDeviceResponse(existingDevice) if err != nil { - c.logger.Errorf("更新设备: 序列化响应失败: %v", err) + c.logger.Errorf("%s: 序列化响应失败: %v, Device: %+v", actionType, err, existingDevice) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备更新成功,但响应生成失败", actionType, "响应序列化失败", existingDevice) return } + c.logger.Infof("%s: 设备更新成功, ID: %d", actionType, existingDevice.ID) controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "设备更新成功", resp, actionType, "设备更新成功", resp) } @@ -322,15 +336,30 @@ func (c *Controller) DeleteDevice(ctx *gin.Context) { // 我们需要先将字符串ID转换为uint,因为Delete方法需要uint类型 idUint, err := strconv.ParseUint(deviceID, 10, 64) if err != nil { + c.logger.Errorf("%s: 设备ID格式错误: %v, ID: %s", actionType, err, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的设备ID格式", actionType, "设备ID格式错误", deviceID) return } + // 检查设备是否存在(可选,但通常在删除前会检查) + _, err = c.repo.FindByIDString(deviceID) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + c.logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备不存在", actionType, "设备不存在", deviceID) + return + } + c.logger.Errorf("%s: 查找设备失败: %v, ID: %s", actionType, err, deviceID) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除设备失败: 查找设备时发生内部错误", actionType, "数据库查询失败", deviceID) + return + } + if err := c.repo.Delete(uint(idUint)); err != nil { - c.logger.Errorf("删除设备: 数据库操作失败: %v", err) + c.logger.Errorf("%s: 数据库删除失败: %v, ID: %d", actionType, err, idUint) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除设备失败: "+err.Error(), actionType, "数据库删除失败", deviceID) return } + c.logger.Infof("%s: 设备删除成功, ID: %d", actionType, idUint) controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "设备删除成功", nil, actionType, "设备删除成功", deviceID) } diff --git a/internal/app/controller/plan/plan_controller.go b/internal/app/controller/plan/plan_controller.go index 63682ec..6956e6a 100644 --- a/internal/app/controller/plan/plan_controller.go +++ b/internal/app/controller/plan/plan_controller.go @@ -120,6 +120,7 @@ func (c *Controller) CreatePlan(ctx *gin.Context) { var req CreatePlanRequest const actionType = "创建计划" if err := ctx.ShouldBindJSON(&req); err != nil { + c.logger.Errorf("%s: 参数绑定失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req) return } @@ -127,6 +128,7 @@ func (c *Controller) CreatePlan(ctx *gin.Context) { // 使用已有的转换函数,它已经包含了验证和重排逻辑 planToCreate, err := PlanFromCreateRequest(&req) if err != nil { + c.logger.Errorf("%s: 计划数据校验失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error(), actionType, "计划数据校验失败", req) return } @@ -141,6 +143,7 @@ func (c *Controller) CreatePlan(ctx *gin.Context) { // 调用仓库方法创建计划 if err := c.planRepo.CreatePlan(planToCreate); err != nil { + c.logger.Errorf("%s: 数据库创建计划失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "创建计划失败: "+err.Error(), actionType, "数据库创建计划失败", planToCreate) return } @@ -154,12 +157,13 @@ func (c *Controller) CreatePlan(ctx *gin.Context) { // 使用已有的转换函数将创建后的模型转换为响应对象 resp, err := PlanToResponse(planToCreate) if err != nil { - c.logger.Errorf("创建计划: 序列化响应失败: %v", err) + c.logger.Errorf("%s: 序列化响应失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划创建成功,但响应生成失败", actionType, "响应序列化失败", planToCreate) return } // 使用统一的成功响应函数 + c.logger.Infof("%s: 计划创建成功, ID: %d", actionType, planToCreate.ID) controller.SendSuccessWithAudit(ctx, controller.CodeCreated, "计划创建成功", resp, actionType, "计划创建成功", resp) } @@ -177,6 +181,7 @@ func (c *Controller) GetPlan(ctx *gin.Context) { idStr := ctx.Param("id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { + c.logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) return } @@ -186,11 +191,12 @@ func (c *Controller) GetPlan(ctx *gin.Context) { if err != nil { // 判断是否为“未找到”错误 if errors.Is(err, gorm.ErrRecordNotFound) { + c.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id) controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id) return } // 其他数据库错误视为内部错误 - c.logger.Errorf("获取计划详情失败: %v", err) + c.logger.Errorf("%s: 数据库查询失败: %v, ID: %d", actionType, err, id) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误", actionType, "数据库查询失败", id) return } @@ -198,12 +204,13 @@ func (c *Controller) GetPlan(ctx *gin.Context) { // 3. 将模型转换为响应 DTO resp, err := PlanToResponse(plan) if err != nil { - c.logger.Errorf("获取计划详情: 序列化响应失败: %v", err) + c.logger.Errorf("%s: 序列化响应失败: %v, Plan: %+v", actionType, err, plan) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情失败: 内部数据格式错误", actionType, "响应序列化失败", plan) return } // 4. 发送成功响应 + c.logger.Infof("%s: 获取计划详情成功, ID: %d", actionType, id) controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取计划详情成功", resp, actionType, "获取计划详情成功", resp) } @@ -219,7 +226,7 @@ func (c *Controller) ListPlans(ctx *gin.Context) { // 1. 调用仓库层获取所有计划 plans, err := c.planRepo.ListBasicPlans() if err != nil { - c.logger.Errorf("获取计划列表失败: %v", err) + c.logger.Errorf("%s: 数据库查询失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划列表时发生内部错误", actionType, "数据库查询失败", nil) return } @@ -229,7 +236,7 @@ func (c *Controller) ListPlans(ctx *gin.Context) { for _, p := range plans { resp, err := PlanToResponse(&p) if err != nil { - c.logger.Errorf("获取计划列表: 序列化响应失败: %v", err) + c.logger.Errorf("%s: 序列化响应失败: %v, Plan: %+v", actionType, err, p) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划列表失败: 内部数据格式错误", actionType, "响应序列化失败", p) return } @@ -241,6 +248,7 @@ func (c *Controller) ListPlans(ctx *gin.Context) { Plans: planResponses, Total: len(planResponses), } + c.logger.Infof("%s: 获取计划列表成功, 数量: %d", actionType, len(planResponses)) controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取计划列表成功", resp, actionType, "获取计划列表成功", resp) } @@ -260,6 +268,7 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { idStr := ctx.Param("id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { + c.logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) return } @@ -267,6 +276,7 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { // 2. 绑定请求体 var req UpdatePlanRequest if err := ctx.ShouldBindJSON(&req); err != nil { + c.logger.Errorf("%s: 参数绑定失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req) return } @@ -274,6 +284,7 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { // 3. 将请求转换为模型(转换函数带校验) planToUpdate, err := PlanFromUpdateRequest(&req) if err != nil { + c.logger.Errorf("%s: 计划数据校验失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error(), actionType, "计划数据校验失败", req) return } @@ -291,10 +302,11 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { _, err = c.planRepo.GetBasicPlanByID(uint(id)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { + c.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id) controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id) return } - c.logger.Errorf("获取计划详情失败: %v", err) + c.logger.Errorf("%s: 获取计划详情失败: %v, ID: %d", actionType, err, id) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误", actionType, "数据库查询失败", id) return } @@ -305,6 +317,7 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { c.logger.Infof("计划 #%d 被更新,执行计数器已重置为 0。", planToUpdate.ID) if err := c.planRepo.UpdatePlan(planToUpdate); err != nil { + c.logger.Errorf("%s: 数据库更新计划失败: %v, Plan: %+v", actionType, err, planToUpdate) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新计划失败: "+err.Error(), actionType, "数据库更新计划失败", planToUpdate) return } @@ -318,7 +331,7 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { // 6. 获取更新后的完整计划用于响应 updatedPlan, err := c.planRepo.GetPlanByID(uint(id)) if err != nil { - c.logger.Errorf("获取更新后的计划详情失败: %v", err) + c.logger.Errorf("%s: 获取更新后计划详情失败: %v, ID: %d", actionType, err, id) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取更新后计划详情时发生内部错误", actionType, "获取更新后计划详情失败", id) return } @@ -326,18 +339,19 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { // 7. 将模型转换为响应 DTO resp, err := PlanToResponse(updatedPlan) if err != nil { - c.logger.Errorf("更新计划: 序列化响应失败: %v", err) + c.logger.Errorf("%s: 序列化响应失败: %v, Updated Plan: %+v", actionType, err, updatedPlan) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划更新成功,但响应生成失败", actionType, "响应序列化失败", updatedPlan) return } // 8. 发送成功响应 + c.logger.Infof("%s: 计划更新成功, ID: %d", actionType, updatedPlan.ID) controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划更新成功", resp, actionType, "计划更新成功", resp) } // DeletePlan godoc // @Summary 删除计划 -// @Description 根据计划ID删除计划。 +// @Description 根据计划ID删除计划。(软删除) // @Tags 计划管理 // @Produce json // @Param id path int true "计划ID" @@ -349,6 +363,7 @@ func (c *Controller) DeletePlan(ctx *gin.Context) { idStr := ctx.Param("id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { + c.logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) return } @@ -357,10 +372,11 @@ func (c *Controller) DeletePlan(ctx *gin.Context) { plan, err := c.planRepo.GetBasicPlanByID(uint(id)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { + c.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id) controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id) return } - c.logger.Errorf("启动计划时获取计划信息失败: %v", err) + c.logger.Errorf("%s: 获取计划信息失败: %v, ID: %d", actionType, err, id) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", actionType, "数据库查询失败", id) return } @@ -368,7 +384,7 @@ func (c *Controller) DeletePlan(ctx *gin.Context) { // 3. 停止这个计划 if plan.Status == models.PlanStatusEnabled { if err := c.planRepo.StopPlanTransactionally(uint(id)); err != nil { - c.logger.Errorf("停止计划 #%d 失败: %v", id, err) + c.logger.Errorf("%s: 停止计划失败: %v, ID: %d", actionType, err, id) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "停止计划时发生内部错误: "+err.Error(), actionType, "停止计划失败", id) return } @@ -376,12 +392,13 @@ func (c *Controller) DeletePlan(ctx *gin.Context) { // 4. 调用仓库层删除计划 if err := c.planRepo.DeletePlan(uint(id)); err != nil { - c.logger.Errorf("删除计划: 数据库操作失败: %v", err) + c.logger.Errorf("%s: 数据库删除失败: %v, ID: %d", actionType, err, id) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除计划时发生内部错误", actionType, "数据库删除失败", id) return } // 5. 发送成功响应 + c.logger.Infof("%s: 计划删除成功, ID: %d", actionType, id) controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划删除成功", nil, actionType, "计划删除成功", id) } @@ -399,6 +416,7 @@ func (c *Controller) StartPlan(ctx *gin.Context) { idStr := ctx.Param("id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { + c.logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) return } @@ -407,16 +425,18 @@ func (c *Controller) StartPlan(ctx *gin.Context) { plan, err := c.planRepo.GetBasicPlanByID(uint(id)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { + c.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id) controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id) return } - c.logger.Errorf("启动计划时获取计划信息失败: %v", err) + c.logger.Errorf("%s: 获取计划信息失败: %v, ID: %d", actionType, err, id) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", actionType, "数据库查询失败", id) return } // 3. 检查计划当前状态 if plan.Status == models.PlanStatusEnabled { + c.logger.Warnf("%s: 计划已处于启动状态,无需重复操作, ID: %d", actionType, id) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划已处于启动状态,无需重复操作", actionType, "计划已处于启动状态", id) return } @@ -427,7 +447,7 @@ func (c *Controller) StartPlan(ctx *gin.Context) { // 如果计划是从停止或失败状态重新启动,且计数器不为0,则重置执行计数 if plan.ExecuteCount > 0 { if err := c.planRepo.UpdateExecuteCount(plan.ID, 0); err != nil { - c.logger.Errorf("重置计划 #%d 执行计数失败: %v", plan.ID, err) + c.logger.Errorf("%s: 重置计划执行计数失败: %v, ID: %d", actionType, err, plan.ID) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "重置计划执行计数失败", actionType, "重置执行计数失败", plan.ID) return } @@ -436,7 +456,7 @@ func (c *Controller) StartPlan(ctx *gin.Context) { // 更新计划状态为“已启动” if err := c.planRepo.UpdatePlanStatus(plan.ID, models.PlanStatusEnabled); err != nil { - c.logger.Errorf("更新计划 #%d 状态失败: %v", plan.ID, err) + c.logger.Errorf("%s: 更新计划状态失败: %v, ID: %d", actionType, err, plan.ID) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新计划状态失败", actionType, "更新计划状态失败", plan.ID) return } @@ -451,12 +471,13 @@ func (c *Controller) StartPlan(ctx *gin.Context) { // 5. 为计划创建或更新触发器 if err := c.analysisPlanTaskManager.CreateOrUpdateTrigger(plan.ID); err != nil { // 此处错误不回滚状态,因为状态更新已成功,但需要明确告知用户触发器创建失败 - c.logger.Errorf("为计划 #%d 创建或更新触发器失败: %v", plan.ID, err) + c.logger.Errorf("%s: 创建或更新触发器失败: %v, ID: %d", actionType, err, plan.ID) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划状态已更新,但创建执行触发器失败,请检查计划配置或稍后重试", actionType, "创建执行触发器失败", plan.ID) return } // 6. 发送成功响应 + c.logger.Infof("%s: 计划已成功启动, ID: %d", actionType, id) controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划已成功启动", nil, actionType, "计划已成功启动", id) } @@ -474,6 +495,7 @@ func (c *Controller) StopPlan(ctx *gin.Context) { idStr := ctx.Param("id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { + c.logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) return } @@ -482,27 +504,30 @@ func (c *Controller) StopPlan(ctx *gin.Context) { plan, err := c.planRepo.GetBasicPlanByID(uint(id)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { + c.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id) controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id) return } - c.logger.Errorf("启动计划时获取计划信息失败: %v", err) + c.logger.Errorf("%s: 获取计划信息失败: %v, ID: %d", actionType, err, id) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", actionType, "数据库查询失败", id) return } // 3. 检查计划当前状态 if plan.Status != models.PlanStatusEnabled { + c.logger.Warnf("%s: 计划当前不是启用状态, ID: %d, Status: %s", actionType, id, plan.Status) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划当前不是启用状态", actionType, "计划未启用", id) return } // 4. 调用仓库层方法,该方法内部处理事务 if err := c.planRepo.StopPlanTransactionally(uint(id)); err != nil { - c.logger.Errorf("停止计划 #%d 失败: %v", id, err) + c.logger.Errorf("%s: 停止计划失败: %v, ID: %d", actionType, err, id) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "停止计划时发生内部错误: "+err.Error(), actionType, "停止计划失败", id) return } // 5. 发送成功响应 + c.logger.Infof("%s: 计划已成功停止, ID: %d", actionType, id) controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划已成功停止", nil, actionType, "计划已成功停止", id) } From b483415a9a1de117aa1bd72d6e0761a4c9b358c0 Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Sun, 28 Sep 2025 01:48:15 +0800 Subject: [PATCH 13/13] =?UTF-8?q?ListUserHistory=20=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/app/api/api.go | 10 +- .../app/controller/user/user_controller.go | 100 +++++++++++++++++- internal/core/application.go | 1 + .../repository/user_action_log_repository.go | 45 +++++++- 4 files changed, 153 insertions(+), 3 deletions(-) diff --git a/internal/app/api/api.go b/internal/app/api/api.go index 3fea745..a9e994a 100644 --- a/internal/app/api/api.go +++ b/internal/app/api/api.go @@ -56,6 +56,7 @@ func NewAPI(cfg config.ServerConfig, userRepo repository.UserRepository, deviceRepository repository.DeviceRepository, planRepository repository.PlanRepository, + userActionLogRepository repository.UserActionLogRepository, tokenService token.TokenService, auditService audit.Service, // 注入审计服务 listenHandler transport.ListenHandler, @@ -82,7 +83,7 @@ func NewAPI(cfg config.ServerConfig, config: cfg, listenHandler: listenHandler, // 在 NewAPI 中初始化用户控制器,并将其作为 API 结构体的成员 - userController: user.NewController(userRepo, logger, tokenService), + userController: user.NewController(userRepo, userActionLogRepository, logger, tokenService), // 在 NewAPI 中初始化设备控制器,并将其作为 API 结构体的成员 deviceController: device.NewController(deviceRepository, logger), // 在 NewAPI 中初始化计划控制器,并将其作为 API 结构体的成员 @@ -140,6 +141,13 @@ func (a *API) setupRoutes() { authGroup.Use(middleware.AuthMiddleware(a.tokenService, a.userRepo)) // 1. 身份认证 authGroup.Use(middleware.AuditLogMiddleware(a.auditService)) // 2. 审计日志 { + // 用户相关路由组 + userGroup := authGroup.Group("/users") + { + userGroup.GET("/:id/history", a.userController.ListUserHistory) + } + a.logger.Info("用户相关接口注册成功 (需要认证和审计)") + // 设备相关路由组 deviceGroup := authGroup.Group("/devices") { diff --git a/internal/app/controller/user/user_controller.go b/internal/app/controller/user/user_controller.go index 9e13a17..2fcaebb 100644 --- a/internal/app/controller/user/user_controller.go +++ b/internal/app/controller/user/user_controller.go @@ -1,6 +1,9 @@ package user import ( + "strconv" + "time" + "git.huangwc.com/pig/pig-farm-controller/internal/app/controller" "git.huangwc.com/pig/pig-farm-controller/internal/app/service/token" "git.huangwc.com/pig/pig-farm-controller/internal/infra/logs" @@ -13,19 +16,23 @@ import ( // Controller 用户控制器 type Controller struct { userRepo repository.UserRepository + auditRepo repository.UserActionLogRepository logger *logs.Logger tokenService token.TokenService // 注入 token 服务 } // NewController 创建用户控制器实例 -func NewController(userRepo repository.UserRepository, logger *logs.Logger, tokenService token.TokenService) *Controller { +func NewController(userRepo repository.UserRepository, auditRepo repository.UserActionLogRepository, logger *logs.Logger, tokenService token.TokenService) *Controller { return &Controller{ userRepo: userRepo, + auditRepo: auditRepo, logger: logger, tokenService: tokenService, } } +// --- DTOs --- + // CreateUserRequest 定义创建用户请求的结构体 type CreateUserRequest struct { Username string `json:"username" binding:"required" example:"newuser"` @@ -52,6 +59,24 @@ type LoginResponse struct { Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."` } +// HistoryResponse 定义单条操作历史的响应结构体 +type HistoryResponse struct { + UserID uint `json:"user_id" example:"101"` + Username string `json:"username" example:"testuser"` + ActionType string `json:"action_type" example:"更新设备"` + Description string `json:"description" example:"设备更新成功"` + TargetResource interface{} `json:"target_resource"` + Time string `json:"time"` +} + +// ListHistoryResponse 定义操作历史列表的响应结构体 +type ListHistoryResponse struct { + History []HistoryResponse `json:"history"` + Total int64 `json:"total" example:"100"` +} + +// --- Controller Methods --- + // CreateUser godoc // @Summary 创建新用户 // @Description 根据用户名和密码创建一个新的系统用户。 @@ -143,3 +168,76 @@ func (c *Controller) Login(ctx *gin.Context) { Token: tokenString, }) } + +// ListUserHistory godoc +// @Summary 获取指定用户的操作历史 +// @Description 根据用户ID,分页获取该用户的操作审计日志。 +// @Tags 用户管理 +// @Produce json +// @Param id path int true "用户ID" +// @Param page query int false "页码" default(1) +// @Param page_size query int false "每页大小" default(10) +// @Param action_type query string false "按操作类型过滤" +// @Success 200 {object} controller.Response{data=user.ListHistoryResponse} "业务码为200代表成功获取" +// @Router /api/v1/users/{id}/history [get] +func (c *Controller) ListUserHistory(ctx *gin.Context) { + const actionType = "获取用户操作历史" + + // 1. 解析路径中的用户ID + userIDStr := ctx.Param("id") + userID, err := strconv.ParseUint(userIDStr, 10, 64) + if err != nil { + c.logger.Errorf("%s: 无效的用户ID格式: %v, ID: %s", actionType, err, userIDStr) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的用户ID格式", actionType, "无效的用户ID格式", userIDStr) + return + } + + // 2. 解析分页和过滤参数 + page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1")) + pageSize, _ := strconv.Atoi(ctx.DefaultQuery("page_size", "10")) + actionTypeFilter := ctx.Query("action_type") + + // 确保分页参数有效 + if page <= 0 { + page = 1 + } + if pageSize <= 0 || pageSize > 100 { + pageSize = 10 + } + + // 3. 调用审计仓库层获取历史数据 + id := uint(userID) + findOptions := repository.FindAuditLogOptions{ + UserID: &id, + ActionType: actionTypeFilter, + Page: page, + PageSize: pageSize, + } + logs, total, err := c.auditRepo.List(findOptions) + if err != nil { + c.logger.Errorf("%s: 查询历史记录失败: %v, Options: %+v", actionType, err, findOptions) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "查询历史记录失败", actionType, "查询历史记录失败", findOptions) + return + } + + // 4. 将数据库模型转换为响应 DTO + historyResponses := make([]HistoryResponse, 0, len(logs)) + for _, log := range logs { + historyResponses = append(historyResponses, HistoryResponse{ + UserID: log.UserID, + Username: log.Username, + ActionType: log.ActionType, + Description: log.Description, + TargetResource: log.TargetResource, + Time: log.Time.Format(time.RFC3339), + }) + } + + // 5. 发送成功响应 + resp := ListHistoryResponse{ + History: historyResponses, + Total: total, + } + c.logger.Infof("%s: 成功获取用户 %d 的操作历史, 数量: %d", actionType, userID, len(historyResponses)) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取用户操作历史成功", resp, actionType, "获取用户操作历史成功", resp) +} diff --git a/internal/core/application.go b/internal/core/application.go index 7fed25f..7244a69 100644 --- a/internal/core/application.go +++ b/internal/core/application.go @@ -127,6 +127,7 @@ func NewApplication(configPath string) (*Application, error) { userRepo, deviceRepo, planRepo, + userActionLogRepo, tokenService, auditService, listenHandler, diff --git a/internal/infra/repository/user_action_log_repository.go b/internal/infra/repository/user_action_log_repository.go index cfaac10..1456c9b 100644 --- a/internal/infra/repository/user_action_log_repository.go +++ b/internal/infra/repository/user_action_log_repository.go @@ -1,4 +1,3 @@ -// Package repository 提供了数据访问的仓库实现 package repository import ( @@ -6,9 +5,18 @@ import ( "gorm.io/gorm" ) +// FindAuditLogOptions 定义了查询审计日志的选项 +type FindAuditLogOptions struct { + UserID *uint // 根据用户ID过滤 + ActionType string // 根据操作类型过滤 + Page int // 页码 + PageSize int // 每页大小 +} + // UserActionLogRepository 定义了与用户操作日志相关的数据库操作接口 type UserActionLogRepository interface { Create(log *models.UserActionLog) error + List(options FindAuditLogOptions) ([]*models.UserActionLog, int64, error) } // gormUserActionLogRepository 是 UserActionLogRepository 的 GORM 实现 @@ -25,3 +33,38 @@ func NewGormUserActionLogRepository(db *gorm.DB) UserActionLogRepository { func (r *gormUserActionLogRepository) Create(log *models.UserActionLog) error { return r.db.Create(log).Error } + +// List 根据选项查询用户操作日志,并返回总数 +func (r *gormUserActionLogRepository) List(options FindAuditLogOptions) ([]*models.UserActionLog, int64, error) { + var logs []*models.UserActionLog + var total int64 + + query := r.db.Model(&models.UserActionLog{}) + + if options.UserID != nil { + query = query.Where("user_id = ?", *options.UserID) + } + if options.ActionType != "" { + query = query.Where("action_type = ?", options.ActionType) + } + + // 统计总数 + if err := query.Count(&total).Error; err != nil { + return nil, 0, err + } + + // 分页查询 + if options.Page > 0 && options.PageSize > 0 { + offset := (options.Page - 1) * options.PageSize + query = query.Offset(offset).Limit(options.PageSize) + } + + // 默认按创建时间倒序 + query = query.Order("created_at DESC") + + if err := query.Find(&logs).Error; err != nil { + return nil, 0, err + } + + return logs, total, nil +}