241e3b5f2d
- Introduced a new `auditlog` package to handle audit logging for user actions, including creation, updates, deletions, and authentication events. - Enhanced existing services (customer, user) to log relevant actions using the new audit logger, capturing details such as actor ID, action type, target type, and success status. - Added middleware to enrich request context with metadata for audit logging, ensuring comprehensive tracking of user interactions. - Integrated Elasticsearch for persistent storage of audit logs, with fallback to file-only logging if Elasticsearch is unavailable. - Updated API documentation to include new audit log endpoints for administrative access. This update significantly improves the system's ability to track and audit user actions, enhancing security and accountability within the application.
48 lines
1.2 KiB
Go
48 lines
1.2 KiB
Go
package audit
|
|
|
|
import (
|
|
"github.com/labstack/echo/v4"
|
|
)
|
|
|
|
// RequestMetaMiddleware injects request metadata into the request context for audit logging.
|
|
func RequestMetaMiddleware() echo.MiddlewareFunc {
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
requestID := c.Response().Header().Get(echo.HeaderXRequestID)
|
|
if requestID == "" {
|
|
requestID = c.Request().Header.Get(echo.HeaderXRequestID)
|
|
}
|
|
|
|
ctx := WithRequestMeta(c.Request().Context(), RequestMeta{
|
|
IP: c.RealIP(),
|
|
RequestID: requestID,
|
|
UserAgent: c.Request().UserAgent(),
|
|
})
|
|
c.SetRequest(c.Request().WithContext(ctx))
|
|
|
|
return next(c)
|
|
}
|
|
}
|
|
}
|
|
|
|
// EnrichEchoContext copies Echo actor values into the Go context when present.
|
|
func EnrichEchoContext(c echo.Context, actorType string) {
|
|
actorID := ""
|
|
if actorType == ActorTypeAdmin {
|
|
if id, ok := c.Get("user_id").(string); ok {
|
|
actorID = id
|
|
}
|
|
}
|
|
if actorType == ActorTypeCustomer {
|
|
if id, ok := c.Get("customer_id").(string); ok {
|
|
actorID = id
|
|
}
|
|
}
|
|
|
|
ctx := c.Request().Context()
|
|
if actorID != "" {
|
|
ctx = WithActor(ctx, Actor{ID: actorID, Type: actorType})
|
|
}
|
|
c.SetRequest(c.Request().WithContext(ctx))
|
|
}
|