Private
Public Access
202 lines
4.7 KiB
Go
202 lines
4.7 KiB
Go
package config
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"reflect"
|
|
"repuestera_back/models/logs"
|
|
|
|
"gorm.io/datatypes"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func SetupAuditoria(db *gorm.DB) {
|
|
if err := db.Callback().Update().Before("gorm:update").Register("auditoria:capturar_anterior", capturarEstadoAnterior); err != nil {
|
|
log.Println("ERROR registrando capturar_anterior:", err)
|
|
}
|
|
if err := db.Callback().Update().After("gorm:update").Register("auditoria:log_update", generarLogUpdate); err != nil {
|
|
log.Println("ERROR registrando log_update:", err)
|
|
}
|
|
if err := db.Callback().Create().After("gorm:create").Register("auditoria:log_create", generarLogCreate); err != nil {
|
|
log.Println("ERROR registrando log_create:", err)
|
|
}
|
|
if err := db.Callback().Delete().Before("gorm:delete").Register("auditoria:log_delete", generarLogDelete); err != nil {
|
|
log.Println("ERROR registrando log_delete:", err)
|
|
}
|
|
}
|
|
|
|
func capturarEstadoAnterior(tx *gorm.DB) {
|
|
if tx.Statement.Schema == nil || auditoriaDeshabilitada(tx) {
|
|
return
|
|
}
|
|
|
|
pkField := tx.Statement.Schema.PrioritizedPrimaryField
|
|
if pkField == nil {
|
|
return
|
|
}
|
|
|
|
reflectValue := tx.Statement.ReflectValue
|
|
if !reflectValue.IsValid() {
|
|
return
|
|
}
|
|
|
|
pkValue, isZero := pkField.ValueOf(context.Background(), reflectValue)
|
|
if isZero {
|
|
return
|
|
}
|
|
|
|
modeloAnterior := reflect.New(tx.Statement.Schema.ModelType).Interface()
|
|
|
|
if err := tx.Session(&gorm.Session{NewDB: true}).
|
|
Model(modeloAnterior).
|
|
First(modeloAnterior, pkValue).Error; err != nil {
|
|
return
|
|
}
|
|
|
|
tx.Set("auditoria:anterior", modeloAnterior)
|
|
}
|
|
|
|
func generarLogUpdate(tx *gorm.DB) {
|
|
if tx.Statement.Schema == nil || auditoriaDeshabilitada(tx) {
|
|
return
|
|
}
|
|
|
|
anteriorVal, ok := tx.Get("auditoria:anterior")
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
nuevo := tx.Statement.Dest
|
|
detalles := generarDetalles(tx.Statement.Table, anteriorVal, nuevo)
|
|
|
|
if len(detalles) == 0 {
|
|
return
|
|
}
|
|
|
|
guardarLog(tx, "ACTUALIZAR", detalles)
|
|
}
|
|
|
|
func generarLogCreate(tx *gorm.DB) {
|
|
if tx.Statement.Schema == nil || auditoriaDeshabilitada(tx) {
|
|
return
|
|
}
|
|
|
|
detalles := []logs.LogDetalle{
|
|
{
|
|
ID: 0,
|
|
NombreTabla: tx.Statement.Table,
|
|
Columna: "*",
|
|
ValorNuevo: fmt.Sprintf("Registro creado (ID: %v)", obtenerID(tx.Statement.Dest)),
|
|
},
|
|
}
|
|
|
|
guardarLog(tx, "CREAR", detalles)
|
|
}
|
|
|
|
func generarLogDelete(tx *gorm.DB) {
|
|
if tx.Statement.Schema == nil || auditoriaDeshabilitada(tx) {
|
|
return
|
|
}
|
|
|
|
detalles := []logs.LogDetalle{
|
|
{
|
|
ID: 0,
|
|
NombreTabla: tx.Statement.Table,
|
|
Columna: "*",
|
|
ValorAnterior: fmt.Sprintf("Registro eliminado (ID: %v)", obtenerID(tx.Statement.Dest)),
|
|
},
|
|
}
|
|
|
|
guardarLog(tx, "ELIMINAR", detalles)
|
|
}
|
|
|
|
func generarDetalles(tabla string, anterior, nuevo interface{}) []logs.LogDetalle {
|
|
var detalles []logs.LogDetalle
|
|
|
|
valAnterior := reflect.ValueOf(anterior)
|
|
valNuevo := reflect.ValueOf(nuevo)
|
|
|
|
for valAnterior.Kind() == reflect.Ptr {
|
|
valAnterior = valAnterior.Elem()
|
|
}
|
|
for valNuevo.Kind() == reflect.Ptr {
|
|
valNuevo = valNuevo.Elem()
|
|
}
|
|
|
|
if valAnterior.Kind() != reflect.Struct || valNuevo.Kind() != reflect.Struct {
|
|
return detalles
|
|
}
|
|
|
|
tipo := valAnterior.Type()
|
|
|
|
for i := 0; i < tipo.NumField(); i++ {
|
|
campo := tipo.Field(i)
|
|
|
|
if campo.PkgPath != "" { // campo no exportado
|
|
continue
|
|
}
|
|
if campo.Name == "CreatedAt" || campo.Name == "UpdatedAt" || campo.Name == "DeletedAt" {
|
|
continue
|
|
}
|
|
|
|
campoNuevo := valNuevo.FieldByName(campo.Name)
|
|
if !campoNuevo.IsValid() {
|
|
continue
|
|
}
|
|
|
|
vAnt := fmt.Sprintf("%v", valAnterior.Field(i).Interface())
|
|
vNue := fmt.Sprintf("%v", campoNuevo.Interface())
|
|
|
|
if vAnt != vNue {
|
|
detalles = append(detalles, logs.LogDetalle{
|
|
ID: uint(i),
|
|
NombreTabla: tabla,
|
|
Columna: campo.Name,
|
|
ValorAnterior: vAnt,
|
|
ValorNuevo: vNue,
|
|
})
|
|
}
|
|
}
|
|
|
|
return detalles
|
|
}
|
|
|
|
func guardarLog(tx *gorm.DB, accion string, detalles []logs.LogDetalle) {
|
|
usuarioID, okUsuario := tx.Get("auditoria:usuario_id")
|
|
|
|
if !okUsuario {
|
|
log.Printf("ADVERTENCIA: Operación '%s' en tabla '%s' no auditada: falta 'auditoria:usuario_id' en contexto GORM", accion, tx.Statement.Table)
|
|
return
|
|
}
|
|
|
|
logEntry := logs.Log{
|
|
UsuarioID: usuarioID.(uint),
|
|
Accion: accion,
|
|
Detalles: datatypes.JSONSlice[logs.LogDetalle](detalles),
|
|
}
|
|
|
|
if err := DB.Create(&logEntry).Error; err != nil {
|
|
log.Printf("ERROR guardarLog: falló al crear entrada de log: %v", err)
|
|
}
|
|
}
|
|
|
|
func auditoriaDeshabilitada(tx *gorm.DB) bool {
|
|
return tx.Statement.Table == "logs"
|
|
}
|
|
|
|
func obtenerID(dest interface{}) interface{} {
|
|
val := reflect.ValueOf(dest)
|
|
for val.Kind() == reflect.Ptr {
|
|
val = val.Elem()
|
|
}
|
|
if val.Kind() != reflect.Struct {
|
|
return nil
|
|
}
|
|
campoID := val.FieldByName("ID")
|
|
if campoID.IsValid() {
|
|
return campoID.Interface()
|
|
}
|
|
return nil
|
|
}
|