Implement audit logging functionality across services and middleware
- 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.
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
package auditlog
|
||||
|
||||
// Entry represents an audit log record returned by the API.
|
||||
type Entry struct {
|
||||
ActorID string `json:"actor_id"`
|
||||
ActorType string `json:"actor_type"`
|
||||
Action string `json:"action"`
|
||||
TargetType string `json:"target_type"`
|
||||
TargetID string `json:"target_id"`
|
||||
At int64 `json:"at"`
|
||||
IP string `json:"ip,omitempty"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
UserAgent string `json:"user_agent,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
Metadata map[string]string `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// ListResponse is the paginated audit log list response.
|
||||
type ListResponse struct {
|
||||
Logs []*Entry `json:"logs"`
|
||||
Meta *ListMeta `json:"meta,omitempty"`
|
||||
}
|
||||
|
||||
// ListMeta contains pagination metadata.
|
||||
type ListMeta struct {
|
||||
Total int64 `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
Page int `json:"page"`
|
||||
Pages int `json:"pages"`
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package auditlog
|
||||
|
||||
// SearchForm defines query parameters for audit log search.
|
||||
type SearchForm struct {
|
||||
ActorID string `query:"actor_id" valid:"optional"`
|
||||
ActorType string `query:"actor_type" valid:"optional,in(admin|customer|system)"`
|
||||
Action string `query:"action" valid:"optional"`
|
||||
TargetType string `query:"target_type" valid:"optional"`
|
||||
TargetID string `query:"target_id" valid:"optional"`
|
||||
From int64 `query:"from" valid:"optional"`
|
||||
To int64 `query:"to" valid:"optional"`
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package auditlog
|
||||
|
||||
import (
|
||||
"tm/pkg/response"
|
||||
|
||||
"github.com/asaskevich/govalidator"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
// Handler handles HTTP requests for audit log operations.
|
||||
type Handler struct {
|
||||
service Service
|
||||
}
|
||||
|
||||
// NewHandler creates an audit log handler.
|
||||
func NewHandler(service Service) *Handler {
|
||||
return &Handler{service: service}
|
||||
}
|
||||
|
||||
// Search returns paginated audit logs with optional filters.
|
||||
// @Summary Search audit logs
|
||||
// @Description Retrieve paginated user action audit logs with optional filtering by actor, action, target, and time range
|
||||
// @Tags Admin-AuditLogs
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param actor_id query string false "Filter by actor ID"
|
||||
// @Param actor_type query string false "Filter by actor type" Enums(admin,customer,system)
|
||||
// @Param action query string false "Filter by action (e.g. auth.login.success)"
|
||||
// @Param target_type query string false "Filter by target type"
|
||||
// @Param target_id query string false "Filter by target ID"
|
||||
// @Param from query int64 false "Filter by timestamp from (Unix seconds)"
|
||||
// @Param to query int64 false "Filter by timestamp to (Unix seconds)"
|
||||
// @Param limit query int false "Number of items per page (default: 10, max: 100)"
|
||||
// @Param offset query int false "Number of items to skip (default: 0)"
|
||||
// @Success 200 {object} response.APIResponse{data=ListResponse} "Audit logs retrieved successfully"
|
||||
// @Failure 400 {object} response.APIResponse "Bad request"
|
||||
// @Failure 401 {object} response.APIResponse "Unauthorized"
|
||||
// @Failure 403 {object} response.APIResponse "Forbidden"
|
||||
// @Failure 500 {object} response.APIResponse "Internal server error"
|
||||
// @Router /admin/v1/audit-logs [get]
|
||||
func (h *Handler) Search(c echo.Context) error {
|
||||
form, err := response.Parse[SearchForm](c)
|
||||
if err != nil {
|
||||
return response.ValidationError(c, "Invalid request data", err.Error())
|
||||
}
|
||||
|
||||
if _, err := govalidator.ValidateStruct(form); err != nil {
|
||||
return response.ValidationError(c, "Validation failed", err.Error())
|
||||
}
|
||||
|
||||
pagination, err := response.NewPagination(c)
|
||||
if err != nil {
|
||||
return response.PaginationBadRequest(c, err)
|
||||
}
|
||||
|
||||
result, err := h.service.Search(c.Request().Context(), *form, pagination)
|
||||
if err != nil {
|
||||
return response.InternalServerError(c, "Failed to retrieve audit logs")
|
||||
}
|
||||
|
||||
return response.SuccessWithMeta(c, result, &response.Meta{
|
||||
Total: int(result.Meta.Total),
|
||||
Limit: result.Meta.Limit,
|
||||
Offset: result.Meta.Offset,
|
||||
Page: result.Meta.Page,
|
||||
Pages: result.Meta.Pages,
|
||||
}, "audit logs retrieved successfully")
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package auditlog
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"tm/pkg/audit"
|
||||
)
|
||||
|
||||
// Repository defines audit log data access.
|
||||
type Repository interface {
|
||||
Search(ctx context.Context, filter audit.SearchFilter) (*audit.SearchResult, error)
|
||||
}
|
||||
|
||||
type repository struct {
|
||||
store audit.Store
|
||||
}
|
||||
|
||||
// NewRepository creates an audit log repository.
|
||||
func NewRepository(store audit.Store) Repository {
|
||||
return &repository{store: store}
|
||||
}
|
||||
|
||||
func (r *repository) Search(ctx context.Context, filter audit.SearchFilter) (*audit.SearchResult, error) {
|
||||
return r.store.Search(ctx, filter)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package auditlog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
|
||||
"tm/pkg/audit"
|
||||
"tm/pkg/logger"
|
||||
"tm/pkg/response"
|
||||
)
|
||||
|
||||
// Service defines audit log query operations.
|
||||
type Service interface {
|
||||
Search(ctx context.Context, form SearchForm, pagination *response.Pagination) (*ListResponse, error)
|
||||
}
|
||||
|
||||
type service struct {
|
||||
repository Repository
|
||||
logger logger.Logger
|
||||
}
|
||||
|
||||
// NewService creates an audit log service.
|
||||
func NewService(repository Repository, log logger.Logger) Service {
|
||||
return &service{
|
||||
repository: repository,
|
||||
logger: log,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *service) Search(ctx context.Context, form SearchForm, pagination *response.Pagination) (*ListResponse, error) {
|
||||
filter := audit.SearchFilter{
|
||||
ActorID: form.ActorID,
|
||||
ActorType: form.ActorType,
|
||||
Action: form.Action,
|
||||
TargetType: form.TargetType,
|
||||
TargetID: form.TargetID,
|
||||
From: form.From,
|
||||
To: form.To,
|
||||
Limit: pagination.Limit,
|
||||
Offset: pagination.Offset,
|
||||
}
|
||||
|
||||
result, err := s.repository.Search(ctx, filter)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to search audit logs", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entries := make([]*Entry, 0, len(result.Items))
|
||||
for _, item := range result.Items {
|
||||
entries = append(entries, &Entry{
|
||||
ActorID: item.ActorID,
|
||||
ActorType: item.ActorType,
|
||||
Action: item.Action,
|
||||
TargetType: item.TargetType,
|
||||
TargetID: item.TargetID,
|
||||
At: item.At,
|
||||
IP: item.IP,
|
||||
RequestID: item.RequestID,
|
||||
UserAgent: item.UserAgent,
|
||||
Success: item.Success,
|
||||
Metadata: item.Metadata,
|
||||
})
|
||||
}
|
||||
|
||||
total := result.TotalCount
|
||||
pages := 0
|
||||
if pagination.Limit > 0 {
|
||||
pages = int(math.Ceil(float64(total) / float64(pagination.Limit)))
|
||||
}
|
||||
page := 1
|
||||
if pagination.Limit > 0 {
|
||||
page = (pagination.Offset / pagination.Limit) + 1
|
||||
}
|
||||
|
||||
return &ListResponse{
|
||||
Logs: entries,
|
||||
Meta: &ListMeta{
|
||||
Total: total,
|
||||
Limit: pagination.Limit,
|
||||
Offset: pagination.Offset,
|
||||
Page: page,
|
||||
Pages: pages,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user