Private
Public Access
funcionalidad de logs andando
This commit is contained in:
1 parent
06ed4a518b
commit
aac88856ac
21 files changed
+627
-31
No files matched your search
+2
-2
@@ -6,8 +6,8 @@ COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o server .
|
||||
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -o server .
|
||||
# -ldflags="-s -w"
|
||||
# ---
|
||||
FROM scratch
|
||||
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
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{
|
||||
{
|
||||
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{
|
||||
{
|
||||
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{
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package logs
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ObtenerLog(c *gin.Context) {
|
||||
pag, err := strconv.ParseUint(c.Param("p"), 10, 64)
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
logs, err := r.ObtenerRepositorios().Logs.ObtenerPorPaginas(uint(pag))
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, logs)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package logs
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ObtenerLogs(c *gin.Context) {
|
||||
pag, err := strconv.ParseUint(c.Param("p"), 10, 64)
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
repo := r.ObtenerRepositorios().Logs
|
||||
|
||||
logs, err := repo.ObtenerPorPaginas(uint(pag))
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
cantpags, err := repo.CantPaginas()
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"logs": logs,
|
||||
"maxlenght": cantpags,
|
||||
})
|
||||
}
|
||||
@@ -46,7 +46,8 @@ func ActualizarRepuesto(c *gin.Context){
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios().Repuesto.Actualizar(entity, &repuesto); err != nil {
|
||||
uid, _ := c.Get("userID")
|
||||
if err := r.ObtenerRepositorios().Repuesto.Actualizar(entity, &repuesto, uid.(uint)); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -32,7 +32,8 @@ func CrearRepuesto(c *gin.Context){
|
||||
ConMarca(marca.ID).
|
||||
Build()
|
||||
|
||||
if err := r.ObtenerRepositorios().Repuesto.Crear(&repuesto); err != nil {
|
||||
uid, _ := c.Get("userID")
|
||||
if err := r.ObtenerRepositorios().Repuesto.Crear(&repuesto, uid.(uint)); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -20,7 +20,9 @@ func EliminarRepuesto(c *gin.Context){
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios().Repuesto.Eliminar(uint(id)); err != nil {
|
||||
|
||||
uid, _ := c.Get("userID")
|
||||
if err := r.ObtenerRepositorios().Repuesto.Eliminar(uint(id), uid.(uint)); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package logs
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
func DBConAuditoria(db *gorm.DB, usuarioID uint) *gorm.DB {
|
||||
return db.Set("auditoria:usuario_id", usuarioID)
|
||||
}
|
||||
+8
-15
@@ -4,24 +4,17 @@ import (
|
||||
"time"
|
||||
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
)
|
||||
|
||||
type LogDetalle struct {
|
||||
NombreTabla string `json:"nombreTabla"`
|
||||
Columna string `json:"columna"`
|
||||
ValorAnterior string `json:"valorAnterior,omitempty"`
|
||||
ValorNuevo string `json:"valorNuevo,omitempty"`
|
||||
}
|
||||
|
||||
type Log struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
EmpresaID string `gorm:"type:varchar(3);index;not null" json:"empresaId"`
|
||||
UsuarioID uint `gorm:"index;not null" json:"usuarioId"`
|
||||
Accion string `gorm:"type:varchar(50);not null" json:"accion"`
|
||||
Detalles []LogDetalle `gorm:"type:json" json:"detalles,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// Empresa models_seguridad.Empresa `gorm:"foreignKey:EmpresaID" json:"empresa,omitempty"`
|
||||
Usuario models_seguridad.Usuario `gorm:"foreignKey:UsuarioID" json:"usuario,omitempty"`
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
UsuarioID uint `gorm:"index;not null" json:"usuarioId"`
|
||||
Accion string `gorm:"type:varchar(50);not null" json:"accion"`
|
||||
Detalles datatypes.JSONSlice[LogDetalle] `gorm:"type:json" json:"detalles,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Usuario models_seguridad.Usuario `gorm:"foreignKey:UsuarioID" json:"usuario,omitempty"`
|
||||
}
|
||||
|
||||
func (Log) TableName() string {
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package logs
|
||||
|
||||
type LogDetalle struct {
|
||||
NombreTabla string `json:"nombreTabla"`
|
||||
Columna string `json:"columna"`
|
||||
ValorAnterior string `json:"valorAnterior,omitempty"`
|
||||
ValorNuevo string `json:"valorNuevo,omitempty"`
|
||||
}
|
||||
@@ -12,6 +12,7 @@ type Repositorios struct {
|
||||
Grupo RepositorioGrupo
|
||||
Repuesto RepositorioRepuesto
|
||||
Marca RepositorioMarcas
|
||||
Logs RepositorioLogs
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -28,6 +29,7 @@ func InicializarRepositorios(db *gorm.DB) {
|
||||
Grupo: &repositorioGrupo{db: db},
|
||||
Repuesto: NuevoRepositorioRepuesto(db),
|
||||
Marca: NuevoRepositorioMarcas(db),
|
||||
Logs: NuevoRepositorioLogs(db),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package repositorios
|
||||
|
||||
import (
|
||||
"repuestera_back/logs"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -8,9 +10,9 @@ type IRepositorio[T any] interface {
|
||||
Guardar(entidad *T) error
|
||||
ObtenerTodos() ([]T, error)
|
||||
ObtenerPorID(id uint) (*T, error)
|
||||
Crear(entidad T) error
|
||||
Actualizar(entidad *T, input T) error
|
||||
Eliminar(id uint) error
|
||||
Crear(entidad T, usuarioID uint) error
|
||||
Actualizar(entidad *T, input T, usuarioID uint) error
|
||||
Eliminar(id uint, usuarioID uint) error
|
||||
}
|
||||
|
||||
type RepositorioBase[T any] struct {
|
||||
@@ -21,6 +23,10 @@ func NewRepositorioBase[T any](db *gorm.DB) *RepositorioBase[T] {
|
||||
return &RepositorioBase[T]{db: db}
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) dbConAuditoria(usuarioID uint) *gorm.DB {
|
||||
return logs.DBConAuditoria(r.db, usuarioID)
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) Guardar(entidad *T) error {
|
||||
return r.db.Save(entidad).Error
|
||||
}
|
||||
@@ -41,15 +47,15 @@ func (r *RepositorioBase[T]) ObtenerPorID(id uint) (*T, error) {
|
||||
return &entidad, nil
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) Crear(entidad T) error {
|
||||
return r.db.Create(&entidad).Error
|
||||
func (r *RepositorioBase[T]) Crear(entidad T, usuarioID uint) error {
|
||||
return r.dbConAuditoria(usuarioID).Create(&entidad).Error
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) Actualizar(entidad *T, input T) error {
|
||||
return r.db.Model(entidad).Updates(input).Error
|
||||
func (r *RepositorioBase[T]) Actualizar(entidad *T, input T, usuarioID uint) error {
|
||||
return r.dbConAuditoria(usuarioID).Model(entidad).Updates(input).Error
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) Eliminar(id uint) error {
|
||||
func (r *RepositorioBase[T]) Eliminar(id uint, usuarioID uint) error {
|
||||
var entidad T
|
||||
return r.db.Delete(&entidad, id).Error
|
||||
return r.dbConAuditoria(usuarioID).Delete(&entidad, id).Error
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package repositorios
|
||||
|
||||
import (
|
||||
"repuestera_back/models/logs"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type RepositorioLogs interface {
|
||||
IRepositorio[*logs.Log]
|
||||
ObtenerPorPaginas(pag uint) ([]logs.Log, error)
|
||||
CantPaginas() (int64, error)
|
||||
}
|
||||
|
||||
type repositorioLogs struct {
|
||||
*RepositorioBase[*logs.Log]
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NuevoRepositorioLogs(db *gorm.DB) RepositorioLogs {
|
||||
baseRepo := NewRepositorioBase[*logs.Log](db)
|
||||
return &repositorioLogs{
|
||||
RepositorioBase: baseRepo,
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repositorioLogs) ObtenerPorPaginas(pag uint) ([]logs.Log, error) {
|
||||
var logs []logs.Log
|
||||
if err := r.db.Limit(10).Offset(int(pag) * 10).Find(&logs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return logs, nil
|
||||
}
|
||||
|
||||
func (r *repositorioLogs) CantPaginas() (int64, error) {
|
||||
var pags int64
|
||||
err := r.db.Model(&logs.Log{}).Count(&pags).Error
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return pags, nil
|
||||
}
|
||||
@@ -39,9 +39,12 @@ func main() {
|
||||
|
||||
fmt.Println("Database connected and migrated successfully")
|
||||
|
||||
config.SetupAuditoria(config.DB)
|
||||
|
||||
repositorios.InicializarRepositorios(config.DB)
|
||||
config.InitPermisos()
|
||||
|
||||
|
||||
r := gin.Default()
|
||||
|
||||
routes.AuthRoute(r)
|
||||
@@ -49,6 +52,9 @@ func main() {
|
||||
routes.GroupRoute(r)
|
||||
routes.UserRoute(r)
|
||||
routes.RepuestoRoute(r)
|
||||
routes.LogsRoute(r)
|
||||
|
||||
fmt.Println("callback registrado:", config.DB.Callback().Create().Get("auditoria:log_create") != nil)
|
||||
|
||||
r.Run(":8080")
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"repuestera_back/controllers/logs"
|
||||
"repuestera_back/middleware"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func LogsRoute(r *gin.Engine) {
|
||||
repuestoGrupo := r.Group("/logs")
|
||||
repuestoGrupo.Use(middleware.AuthMiddleware(), middleware.PermisoMiddleware(5))
|
||||
{
|
||||
repuestoGrupo.GET("/:p/", logs.ObtenerLogs)
|
||||
|
||||
repuestoGrupo.GET("/:p/log", logs.ObtenerLog)
|
||||
// repuestoGrupo.GET("/:id", repuestos.ObtenerRepuesto)
|
||||
// repuestoGrupo.POST("/", repuestos.CrearRepuesto)
|
||||
// repuestoGrupo.PUT("/:id", repuestos.ActualizarRepuesto)
|
||||
// repuestoGrupo.DELETE("/:id", repuestos.EliminarRepuesto)
|
||||
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user