feat: migrar backend unificado a Go 1.27 + SPA Vite embebido
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"cotizador/internal/db"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Entry struct {
|
||||
ActorTipo string
|
||||
ActorID string
|
||||
ActorNombre string
|
||||
Accion string
|
||||
RecursoTipo string
|
||||
RecursoID string
|
||||
IP string
|
||||
RequestID string
|
||||
Exito bool
|
||||
Detalle any
|
||||
}
|
||||
|
||||
func ClientIP(r *http.Request) string {
|
||||
if r == nil {
|
||||
return ""
|
||||
}
|
||||
if xff := strings.TrimSpace(r.Header.Get("X-Forwarded-For")); xff != "" {
|
||||
parts := strings.Split(xff, ",")
|
||||
if len(parts) > 0 && strings.TrimSpace(parts[0]) != "" {
|
||||
return strings.TrimSpace(parts[0])
|
||||
}
|
||||
}
|
||||
if xri := strings.TrimSpace(r.Header.Get("X-Real-IP")); xri != "" {
|
||||
return xri
|
||||
}
|
||||
return r.RemoteAddr
|
||||
}
|
||||
|
||||
func RequestID(r *http.Request) string {
|
||||
if r == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(r.Header.Get("X-Request-Id"))
|
||||
}
|
||||
|
||||
// Registrar writes an AuditLog row best-effort (never fails caller flow).
|
||||
func Registrar(ctx context.Context, pool *pgxpool.Pool, e Entry) {
|
||||
if pool == nil {
|
||||
return
|
||||
}
|
||||
var detalleBytes []byte
|
||||
if e.Detalle != nil {
|
||||
if b, err := json.Marshal(e.Detalle); err == nil {
|
||||
detalleBytes = b
|
||||
}
|
||||
}
|
||||
var actorID, recursoID, ip, reqID *string
|
||||
if e.ActorID != "" {
|
||||
v := e.ActorID
|
||||
actorID = &v
|
||||
}
|
||||
if e.RecursoID != "" {
|
||||
v := e.RecursoID
|
||||
recursoID = &v
|
||||
}
|
||||
if e.IP != "" {
|
||||
v := e.IP
|
||||
ip = &v
|
||||
}
|
||||
if e.RequestID != "" {
|
||||
v := e.RequestID
|
||||
reqID = &v
|
||||
}
|
||||
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "AuditLog" ("id", "actorTipo", "actorId", "actorNombre", "accion", "recursoTipo", "recursoId", "ip", "requestId", "exito", "detalle")
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
|
||||
`, db.NewID(), e.ActorTipo, actorID, e.ActorNombre, e.Accion, e.RecursoTipo, recursoID, ip, reqID, e.Exito, detalleBytes)
|
||||
if err != nil {
|
||||
log.Printf("[audit] error escribiendo AuditLog (%s): %v", e.Accion, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user