diff --git a/internal/app/api/api.go b/internal/app/api/api.go index 6d2dbf9..a9e994a 100644 --- a/internal/app/api/api.go +++ b/internal/app/api/api.go @@ -15,18 +15,20 @@ 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/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" "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" ) @@ -37,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 // 用户控制器实例 @@ -53,7 +56,9 @@ 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, analysisTaskManager *task.AnalysisPlanTaskManager) *API { // 设置 Gin 模式,例如 gin.ReleaseMode (生产模式) 或 gin.DebugMode (开发模式) @@ -74,10 +79,11 @@ func NewAPI(cfg config.ServerConfig, logger: logger, userRepo: userRepo, tokenService: tokenService, + auditService: auditService, 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 结构体的成员 @@ -91,41 +97,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 +135,43 @@ 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, 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") + { + 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/controller/device/device_controller.go b/internal/app/controller/device/device_controller.go index 97d5d10..41ac035 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.SendErrorResponse(ctx, controller.CodeBadRequest, err.Error()) + 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) - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "属性字段格式错误") + c.logger.Errorf("%s: 序列化属性失败: %v", actionType, err) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "属性字段格式错误", actionType, "属性序列化失败", req.Properties) return } @@ -145,25 +146,26 @@ func (c *Controller) CreateDevice(ctx *gin.Context) { // 在创建设备前进行自检 if !device.SelfCheck() { - c.logger.Errorf("创建设备: 设备属性自检失败: %v", device) - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "设备属性不符合要求") + 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) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "创建设备失败") + 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) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "设备创建成功,但响应生成失败") + c.logger.Errorf("%s: 序列化响应失败: %v", actionType, err) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备创建成功,但响应生成失败", actionType, "响应序列化失败", device) return } - controller.SendResponse(ctx, controller.CodeCreated, "设备创建成功", resp) + c.logger.Infof("%s: 设备创建成功, ID: %d", actionType, device.ID) + controller.SendSuccessWithAudit(ctx, controller.CodeCreated, "设备创建成功", resp, actionType, "设备创建成功", resp) } // GetDevice godoc @@ -175,31 +177,41 @@ 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") + 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) { - controller.SendErrorResponse(ctx, controller.CodeNotFound, "设备未找到") + c.logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", actionType, "设备不存在", deviceID) return } if strings.Contains(err.Error(), "无效的设备ID格式") { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, err.Error()) + 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) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取设备信息失败") + 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) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取设备信息失败: 内部数据格式错误") + c.logger.Errorf("%s: 序列化响应失败: %v, Device: %+v", actionType, err, device) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备信息失败: 内部数据格式错误", actionType, "响应序列化失败", device) return } - controller.SendResponse(ctx, controller.CodeSuccess, "获取设备信息成功", resp) + c.logger.Infof("%s: 获取设备信息成功, ID: %d", actionType, device.ID) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取设备信息成功", resp, actionType, "获取设备信息成功", resp) } // ListDevices godoc @@ -210,21 +222,23 @@ 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.SendErrorResponse(ctx, controller.CodeInternalError, "获取设备列表失败") + 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) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取设备列表失败: 内部数据格式错误") + c.logger.Errorf("%s: 序列化响应失败: %v, Devices: %+v", actionType, err, devices) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备列表失败: 内部数据格式错误", actionType, "响应序列化失败", devices) return } - controller.SendResponse(ctx, controller.CodeSuccess, "获取设备列表成功", resp) + c.logger.Infof("%s: 获取设备列表成功, 数量: %d", actionType, len(devices)) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取设备列表成功", resp, actionType, "获取设备列表成功", resp) } // UpdateDevice godoc @@ -238,36 +252,39 @@ 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.SendErrorResponse(ctx, controller.CodeNotFound, "设备未找到") + c.logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", actionType, "设备不存在", deviceID) return } if strings.Contains(err.Error(), "无效的设备ID格式") { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, err.Error()) + 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) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "更新设备失败") + c.logger.Errorf("%s: 数据库查询失败: %v, ID: %s", actionType, err, deviceID) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新设备失败: "+err.Error(), actionType, "数据库查询失败", deviceID) return } // 2. 绑定请求参数 var req UpdateDeviceRequest if err := ctx.ShouldBindJSON(&req); err != nil { - c.logger.Errorf("更新设备: 参数绑定失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeBadRequest, err.Error()) + 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) - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "属性字段格式错误") + c.logger.Errorf("%s: 序列化属性失败: %v", actionType, err) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "属性字段格式错误", actionType, "属性序列化失败", req.Properties) return } @@ -281,26 +298,27 @@ func (c *Controller) UpdateDevice(ctx *gin.Context) { // 在更新设备前进行自检 if !existingDevice.SelfCheck() { - c.logger.Errorf("更新设备: 设备属性自检失败: %v", existingDevice) - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "设备属性不符合要求") + 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) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "更新设备失败") + 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) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "设备更新成功,但响应生成失败") + c.logger.Errorf("%s: 序列化响应失败: %v, Device: %+v", actionType, err, existingDevice) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备更新成功,但响应生成失败", actionType, "响应序列化失败", existingDevice) return } - controller.SendResponse(ctx, controller.CodeSuccess, "设备更新成功", resp) + c.logger.Infof("%s: 设备更新成功, ID: %d", actionType, existingDevice.ID) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "设备更新成功", resp, actionType, "设备更新成功", resp) } // DeleteDevice godoc @@ -312,20 +330,36 @@ 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.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的设备ID格式") + 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) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "删除设备失败") + c.logger.Errorf("%s: 数据库删除失败: %v, ID: %d", actionType, err, idUint) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除设备失败: "+err.Error(), actionType, "数据库删除失败", deviceID) return } - controller.SendResponse(ctx, controller.CodeSuccess, "设备删除成功", nil) + 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 746f0df..6956e6a 100644 --- a/internal/app/controller/plan/plan_controller.go +++ b/internal/app/controller/plan/plan_controller.go @@ -118,15 +118,18 @@ 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.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error()) + c.logger.Errorf("%s: 参数绑定失败: %v", actionType, err) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req) return } // 使用已有的转换函数,它已经包含了验证和重排逻辑 planToCreate, err := PlanFromCreateRequest(&req) if err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error()) + c.logger.Errorf("%s: 计划数据校验失败: %v", actionType, err) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error(), actionType, "计划数据校验失败", req) return } @@ -140,7 +143,8 @@ func (c *Controller) CreatePlan(ctx *gin.Context) { // 调用仓库方法创建计划 if err := c.planRepo.CreatePlan(planToCreate); err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "创建计划失败: "+err.Error()) + c.logger.Errorf("%s: 数据库创建计划失败: %v", actionType, err) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "创建计划失败: "+err.Error(), actionType, "数据库创建计划失败", planToCreate) return } @@ -153,13 +157,14 @@ func (c *Controller) CreatePlan(ctx *gin.Context) { // 使用已有的转换函数将创建后的模型转换为响应对象 resp, err := PlanToResponse(planToCreate) if err != nil { - c.logger.Errorf("创建计划: 序列化响应失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "计划创建成功,但响应生成失败") + c.logger.Errorf("%s: 序列化响应失败: %v", actionType, err) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划创建成功,但响应生成失败", actionType, "响应序列化失败", planToCreate) return } // 使用统一的成功响应函数 - controller.SendResponse(ctx, controller.CodeCreated, "计划创建成功", resp) + c.logger.Infof("%s: 计划创建成功, ID: %d", actionType, planToCreate.ID) + controller.SendSuccessWithAudit(ctx, controller.CodeCreated, "计划创建成功", resp, actionType, "计划创建成功", resp) } // GetPlan godoc @@ -171,11 +176,13 @@ 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.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的计划ID格式") + c.logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) return } @@ -184,25 +191,27 @@ func (c *Controller) GetPlan(ctx *gin.Context) { if err != nil { // 判断是否为“未找到”错误 if errors.Is(err, gorm.ErrRecordNotFound) { - controller.SendErrorResponse(ctx, controller.CodeNotFound, "计划不存在") + c.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id) + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id) return } // 其他数据库错误视为内部错误 - c.logger.Errorf("获取计划详情失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误") + c.logger.Errorf("%s: 数据库查询失败: %v, ID: %d", actionType, err, id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误", actionType, "数据库查询失败", id) return } // 3. 将模型转换为响应 DTO resp, err := PlanToResponse(plan) if err != nil { - c.logger.Errorf("获取计划详情: 序列化响应失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划详情失败: 内部数据格式错误") + c.logger.Errorf("%s: 序列化响应失败: %v, Plan: %+v", actionType, err, plan) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情失败: 内部数据格式错误", actionType, "响应序列化失败", plan) return } // 4. 发送成功响应 - controller.SendResponse(ctx, controller.CodeSuccess, "获取计划详情成功", resp) + c.logger.Infof("%s: 获取计划详情成功, ID: %d", actionType, id) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取计划详情成功", resp, actionType, "获取计划详情成功", resp) } // ListPlans godoc @@ -213,11 +222,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.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划列表时发生内部错误") + c.logger.Errorf("%s: 数据库查询失败: %v", actionType, err) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划列表时发生内部错误", actionType, "数据库查询失败", nil) return } @@ -226,8 +236,8 @@ func (c *Controller) ListPlans(ctx *gin.Context) { for _, p := range plans { resp, err := PlanToResponse(&p) if err != nil { - c.logger.Errorf("获取计划列表: 序列化响应失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划列表失败: 内部数据格式错误") + c.logger.Errorf("%s: 序列化响应失败: %v, Plan: %+v", actionType, err, p) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划列表失败: 内部数据格式错误", actionType, "响应序列化失败", p) return } planResponses = append(planResponses, *resp) @@ -238,7 +248,8 @@ func (c *Controller) ListPlans(ctx *gin.Context) { Plans: planResponses, Total: len(planResponses), } - controller.SendResponse(ctx, controller.CodeSuccess, "获取计划列表成功", resp) + c.logger.Infof("%s: 获取计划列表成功, 数量: %d", actionType, len(planResponses)) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取计划列表成功", resp, actionType, "获取计划列表成功", resp) } // UpdatePlan godoc @@ -252,25 +263,29 @@ 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.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的计划ID格式") + c.logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) return } // 2. 绑定请求体 var req UpdatePlanRequest if err := ctx.ShouldBindJSON(&req); err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error()) + c.logger.Errorf("%s: 参数绑定失败: %v", actionType, err) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req) return } // 3. 将请求转换为模型(转换函数带校验) planToUpdate, err := PlanFromUpdateRequest(&req) if err != nil { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error()) + c.logger.Errorf("%s: 计划数据校验失败: %v", actionType, err) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error(), actionType, "计划数据校验失败", req) return } planToUpdate.ID = uint(id) // 确保ID被设置 @@ -287,11 +302,12 @@ 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, "计划不存在") + c.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id) + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id) return } - c.logger.Errorf("获取计划详情失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误") + c.logger.Errorf("%s: 获取计划详情失败: %v, ID: %d", actionType, err, id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误", actionType, "数据库查询失败", id) return } @@ -301,7 +317,8 @@ 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()) + c.logger.Errorf("%s: 数据库更新计划失败: %v, Plan: %+v", actionType, err, planToUpdate) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新计划失败: "+err.Error(), actionType, "数据库更新计划失败", planToUpdate) return } @@ -314,37 +331,40 @@ func (c *Controller) UpdatePlan(ctx *gin.Context) { // 6. 获取更新后的完整计划用于响应 updatedPlan, err := c.planRepo.GetPlanByID(uint(id)) if err != nil { - c.logger.Errorf("获取更新后的计划详情失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取更新后计划详情时发生内部错误") + c.logger.Errorf("%s: 获取更新后计划详情失败: %v, ID: %d", actionType, err, id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取更新后计划详情时发生内部错误", actionType, "获取更新后计划详情失败", id) return } // 7. 将模型转换为响应 DTO resp, err := PlanToResponse(updatedPlan) if err != nil { - c.logger.Errorf("更新计划: 序列化响应失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "计划更新成功,但响应生成失败") + c.logger.Errorf("%s: 序列化响应失败: %v, Updated Plan: %+v", actionType, err, updatedPlan) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划更新成功,但响应生成失败", actionType, "响应序列化失败", updatedPlan) return } // 8. 发送成功响应 - controller.SendResponse(ctx, controller.CodeSuccess, "计划更新成功", resp) + 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" // @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.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的计划ID格式") + c.logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) return } @@ -352,32 +372,34 @@ 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, "计划不存在") + c.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id) + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id) return } - c.logger.Errorf("启动计划时获取计划信息失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误") + c.logger.Errorf("%s: 获取计划信息失败: %v, ID: %d", actionType, err, id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", actionType, "数据库查询失败", id) return } // 3. 停止这个计划 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()) + c.logger.Errorf("%s: 停止计划失败: %v, ID: %d", actionType, err, id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "停止计划时发生内部错误: "+err.Error(), actionType, "停止计划失败", 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("%s: 数据库删除失败: %v, ID: %d", actionType, err, id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除计划时发生内部错误", actionType, "数据库删除失败", id) return } // 5. 发送成功响应 - controller.SendResponse(ctx, controller.CodeSuccess, "计划删除成功", nil) + c.logger.Infof("%s: 计划删除成功, ID: %d", actionType, id) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划删除成功", nil, actionType, "计划删除成功", id) } // StartPlan godoc @@ -389,11 +411,13 @@ 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.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的计划ID格式") + c.logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) return } @@ -401,17 +425,19 @@ 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, "计划不存在") + c.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id) + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id) return } - c.logger.Errorf("启动计划时获取计划信息失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误") + c.logger.Errorf("%s: 获取计划信息失败: %v, ID: %d", actionType, err, id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", actionType, "数据库查询失败", id) return } // 3. 检查计划当前状态 if plan.Status == models.PlanStatusEnabled { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "计划已处于启动状态,无需重复操作") + c.logger.Warnf("%s: 计划已处于启动状态,无需重复操作, ID: %d", actionType, id) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划已处于启动状态,无需重复操作", actionType, "计划已处于启动状态", id) return } @@ -421,8 +447,8 @@ 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) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "重置计划执行计数失败") + c.logger.Errorf("%s: 重置计划执行计数失败: %v, ID: %d", actionType, err, plan.ID) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "重置计划执行计数失败", actionType, "重置执行计数失败", plan.ID) return } c.logger.Infof("计划 #%d 的执行计数器已重置为 0。", plan.ID) @@ -430,28 +456,29 @@ 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, "更新计划状态失败") + c.logger.Errorf("%s: 更新计划状态失败: %v, ID: %d", actionType, err, 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.SendErrorResponse(ctx, controller.CodeBadRequest, "计划已处于启动状态,无需重复操作") + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "计划已处于启动状态,无需重复操作", actionType, "计划已处于启动状态", plan.ID) return } // 5. 为计划创建或更新触发器 if err := c.analysisPlanTaskManager.CreateOrUpdateTrigger(plan.ID); err != nil { // 此处错误不回滚状态,因为状态更新已成功,但需要明确告知用户触发器创建失败 - c.logger.Errorf("为计划 #%d 创建或更新触发器失败: %v", plan.ID, err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "计划状态已更新,但创建执行触发器失败,请检查计划配置或稍后重试") + c.logger.Errorf("%s: 创建或更新触发器失败: %v, ID: %d", actionType, err, plan.ID) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "计划状态已更新,但创建执行触发器失败,请检查计划配置或稍后重试", actionType, "创建执行触发器失败", plan.ID) return } // 6. 发送成功响应 - controller.SendResponse(ctx, controller.CodeSuccess, "计划已成功启动", nil) + c.logger.Infof("%s: 计划已成功启动, ID: %d", actionType, id) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划已成功启动", nil, actionType, "计划已成功启动", id) } // StopPlan godoc @@ -463,11 +490,13 @@ 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.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的计划ID格式") + c.logger.Errorf("%s: 计划ID格式错误: %v, ID: %s", actionType, err, idStr) + controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的计划ID格式", actionType, "计划ID格式错误", idStr) return } @@ -475,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) { - controller.SendErrorResponse(ctx, controller.CodeNotFound, "计划不存在") + c.logger.Warnf("%s: 计划不存在, ID: %d", actionType, id) + controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "计划不存在", actionType, "计划不存在", id) return } - c.logger.Errorf("启动计划时获取计划信息失败: %v", err) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误") + c.logger.Errorf("%s: 获取计划信息失败: %v, ID: %d", actionType, err, id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取计划信息时发生内部错误", actionType, "数据库查询失败", id) return } // 3. 检查计划当前状态 if plan.Status != models.PlanStatusEnabled { - controller.SendErrorResponse(ctx, controller.CodeBadRequest, "计划当前不是启用状态") + 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) - controller.SendErrorResponse(ctx, controller.CodeInternalError, "停止计划时发生内部错误: "+err.Error()) + c.logger.Errorf("%s: 停止计划失败: %v, ID: %d", actionType, err, id) + controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "停止计划时发生内部错误: "+err.Error(), actionType, "停止计划失败", id) return } // 5. 发送成功响应 - controller.SendResponse(ctx, controller.CodeSuccess, "计划已成功停止", nil) + c.logger.Infof("%s: 计划已成功停止, ID: %d", actionType, id) + controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "计划已成功停止", nil, actionType, "计划已成功停止", id) } diff --git a/internal/app/controller/response.go b/internal/app/controller/response.go index 136356c..7f180c7 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/infra/models" "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,52 @@ 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(models.ContextAuditActionType.String(), actionType) + c.Set(models.ContextAuditDescription.String(), description) + c.Set(models.ContextAuditTargetResource.String(), targetResource) + } +} + +// SendSuccessWithAudit 发送成功的响应,并设置审计日志所需的信息。 +// 这是控制器中用于记录成功操作并返回响应的首选函数。 +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. 发送响应 + SendResponse(ctx, code, message, data) +} + +// SendErrorWithAudit 发送失败的响应,并设置审计日志所需的信息。 +// 这是控制器中用于记录失败操作并返回响应的首选函数。 +func SendErrorWithAudit( + ctx *gin.Context, // Gin上下文,用于处理HTTP请求和响应 + code ResponseCode, // 业务状态码,表示操作结果 + message string, // 提示信息,向用户展示操作结果的文本描述 + actionType string, // 审计操作类型,例如"登录失败", "删除失败" + description string, // 审计描述,对操作的详细说明 + targetResource interface{}, // 审计目标资源,被操作的资源对象或其标识 +) { + // 1. 设置审计信息 + setAuditDetails(ctx, actionType, description, targetResource) + // 2. 发送响应 + SendErrorResponse(ctx, code, message) +} diff --git a/internal/app/controller/user/user_controller.go b/internal/app/controller/user/user_controller.go index 14579b5..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"` @@ -34,8 +41,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 定义创建用户成功响应的结构体 @@ -51,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 根据用户名和密码创建一个新的系统用户。 @@ -96,7 +122,7 @@ func (c *Controller) CreateUser(ctx *gin.Context) { // Login godoc // @Summary 用户登录 -// @Description 用户使用用户名和密码登录,成功后返回 JWT 令牌。 +// @Description 用户可以使用用户名、邮箱、手机号、微信号或飞书账号进行登录,成功后返回 JWT 令牌。 // @Tags 用户管理 // @Accept json // @Produce json @@ -111,10 +137,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 +150,7 @@ func (c *Controller) Login(ctx *gin.Context) { } if !user.CheckPassword(req.Password) { - controller.SendErrorResponse(ctx, controller.CodeUnauthorized, "用户名或密码不正确") + controller.SendErrorResponse(ctx, controller.CodeUnauthorized, "登录凭证不正确") return } @@ -141,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/app/middleware/audit.go b/internal/app/middleware/audit.go new file mode 100644 index 0000000..db2a8b2 --- /dev/null +++ b/internal/app/middleware/audit.go @@ -0,0 +1,117 @@ +package middleware + +import ( + "bytes" + "encoding/json" + "io" + "strconv" + + "git.huangwc.com/pig/pig-farm-controller/internal/app/service/audit" + "git.huangwc.com/pig/pig-farm-controller/internal/infra/models" + "github.com/gin-gonic/gin" +) + +type auditResponse struct { + Code int `json:"code"` + Message string `json:"message"` +} + +// 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(models.ContextAuditActionType.String()) + if !exists { + // 如果上下文中没有 actionType,说明此接口无需记录审计日志,直接返回 + return + } + + // 从 Gin Context 中获取用户对象 + userCtx, userExists := c.Get(models.ContextUserKey.String()) + 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(models.ContextAuditDescription.String()) + targetResource, _ := c.Get(models.ContextAuditTargetResource.String()) + + // 默认操作状态为成功 + status := models.AuditStatusSuccess + resultDetails := "" + + // 尝试从捕获的响应体中解析平台响应 + var platformResponse auditResponse + if err := json.Unmarshal(blw.body.Bytes(), &platformResponse); err == nil { + // 如果解析成功,根据平台状态码判断操作是否失败 + // 成功状态码范围是 2000-2999 + if platformResponse.Code < 2000 || platformResponse.Code >= 3000 { + status = models.AuditStatusFailed + resultDetails = platformResponse.Message + } + } else { + // 如果响应体不是预期的平台响应格式,或者解析失败,则记录原始HTTP状态码作为详情 + // 并且如果HTTP状态码不是2xx,则标记为失败 + if c.Writer.Status() < 200 || c.Writer.Status() >= 300 { + status = models.AuditStatusFailed + } + resultDetails = "HTTP Status: " + strconv.Itoa(c.Writer.Status()) + ", Body Parse Error: " + err.Error() + } + + // 调用审计服务记录日志(异步) + auditService.LogAction( + user, + reqCtx, + 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 new file mode 100644 index 0000000..8684acb --- /dev/null +++ b/internal/app/middleware/auth.go @@ -0,0 +1,61 @@ +// Package middleware 存放 gin 中间件 +package middleware + +import ( + "net/http" + "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" +) + +// AuthMiddleware 创建一个Gin中间件,用于JWT身份验证 +// 它依赖于 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") + 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 + } + + // 根据 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(models.ContextUserKey.String(), 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..6f72396 --- /dev/null +++ b/internal/app/service/audit/service.go @@ -0,0 +1,69 @@ +// Package audit 提供了用户操作审计相关的功能 +package audit + +import ( + "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" 的直接依赖 +) + +// RequestContext 封装了审计日志所需的请求上下文信息 +type RequestContext struct { + ClientIP string + HTTPPath string + HTTPMethod string +} + +// Service 定义了审计服务的接口 +type Service interface { + LogAction(user *models.User, reqCtx RequestContext, actionType, description string, targetResource interface{}, status models.AuditStatus, 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(user *models.User, reqCtx RequestContext, actionType, description string, targetResource interface{}, status models.AuditStatus, resultDetails string) { + // 不再从 context 中获取用户信息,直接使用传入的 user 对象 + if user == nil { + s.logger.Warnw("无法记录审计日志:传入的用户对象为 nil") + return + } + + log := &models.UserActionLog{ + Time: time.Now(), + UserID: user.ID, + Username: user.Username, // 用户名快照 + SourceIP: reqCtx.ClientIP, + ActionType: actionType, + Description: description, + Status: status, + HTTPPath: reqCtx.HTTPPath, + HTTPMethod: reqCtx.HTTPMethod, + ResultDetails: resultDetails, + } + + // 使用模型提供的方法来设置 TargetResource + if err := log.SetTargetResource(targetResource); err != nil { + s.logger.Errorw("无法记录审计日志:序列化 targetResource 失败", "error", err) + // 即使序列化失败,我们可能仍然希望记录操作本身,所以不在此处 return + } + + // 异步写入数据库,不阻塞当前请求 + 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..7244a69 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) @@ -120,7 +127,9 @@ func NewApplication(configPath string) (*Application, error) { userRepo, deviceRepo, planRepo, + userActionLogRepo, 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..392187a 100644 --- a/internal/infra/models/execution.go +++ b/internal/infra/models/execution.go @@ -1,8 +1,11 @@ package models import ( + "encoding/json" + "errors" "time" + "gorm.io/datatypes" "gorm.io/gorm" ) @@ -140,3 +143,78 @@ type PendingCollection struct { func (PendingCollection) TableName() string { return "pending_collections" } + +// --- 用户审计日志 --- +// 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 { + // 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 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"` // 结果详情,如失败时的错误信息 +} + +// TableName 自定义 GORM 使用的数据库表名 +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 +} 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 模型对应的数据库表名 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..1456c9b --- /dev/null +++ b/internal/infra/repository/user_action_log_repository.go @@ -0,0 +1,70 @@ +package repository + +import ( + "git.huangwc.com/pig/pig-farm-controller/internal/infra/models" + "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 实现 +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 +} + +// 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 +} 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