98 lines
2.7 KiB
Go
98 lines
2.7 KiB
Go
package models
|
|
|
|
import (
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// AuditLog represents an audit log entry
|
|
type AuditLog struct {
|
|
ID uint `gorm:"primaryKey" json:"id"`
|
|
UserID *uint `json:"user_id"` // Nullable for system actions
|
|
User *User `gorm:"foreignKey:UserID" json:"user,omitempty"`
|
|
Action string `gorm:"type:varchar(50);not null" json:"action"` // create, update, delete, verify, login, etc.
|
|
EntityType string `gorm:"type:varchar(50)" json:"entity_type"` // item, claim, user, etc.
|
|
EntityID *uint `json:"entity_id"`
|
|
Details string `gorm:"type:text" json:"details"`
|
|
IPAddress string `gorm:"type:varchar(50)" json:"ip_address"`
|
|
UserAgent string `gorm:"type:varchar(255)" json:"user_agent"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
|
}
|
|
|
|
// TableName specifies the table name for AuditLog model
|
|
func (AuditLog) TableName() string {
|
|
return "audit_logs"
|
|
}
|
|
|
|
// Action constants
|
|
const (
|
|
ActionCreate = "create"
|
|
ActionUpdate = "update"
|
|
ActionDelete = "delete"
|
|
ActionVerify = "verify"
|
|
ActionLogin = "login"
|
|
ActionLogout = "logout"
|
|
ActionBlock = "block"
|
|
ActionUnblock = "unblock"
|
|
ActionApprove = "approve"
|
|
ActionReject = "reject"
|
|
ActionExport = "export"
|
|
)
|
|
|
|
// Entity type constants
|
|
const (
|
|
EntityItem = "item"
|
|
EntityLostItem = "lost_item"
|
|
EntityClaim = "claim"
|
|
EntityUser = "user"
|
|
EntityCategory = "category"
|
|
EntityArchive = "archive"
|
|
)
|
|
|
|
// AuditLogResponse represents audit log data for API responses
|
|
type AuditLogResponse struct {
|
|
ID uint `json:"id"`
|
|
UserName string `json:"user_name,omitempty"`
|
|
Action string `json:"action"`
|
|
EntityType string `json:"entity_type"`
|
|
EntityID *uint `json:"entity_id"`
|
|
Details string `json:"details"`
|
|
IPAddress string `json:"ip_address"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
}
|
|
|
|
// ToResponse converts AuditLog to AuditLogResponse
|
|
func (a *AuditLog) ToResponse() AuditLogResponse {
|
|
userName := "System"
|
|
if a.User != nil && a.User.ID != 0 {
|
|
userName = a.User.Name
|
|
}
|
|
|
|
return AuditLogResponse{
|
|
ID: a.ID,
|
|
UserName: userName,
|
|
Action: a.Action,
|
|
EntityType: a.EntityType,
|
|
EntityID: a.EntityID,
|
|
Details: a.Details,
|
|
IPAddress: a.IPAddress,
|
|
CreatedAt: a.CreatedAt,
|
|
}
|
|
}
|
|
|
|
// CreateAuditLog creates a new audit log entry
|
|
func CreateAuditLog(db *gorm.DB, userID *uint, action, entityType string, entityID *uint, details, ipAddress, userAgent string) error {
|
|
log := &AuditLog{
|
|
UserID: userID,
|
|
Action: action,
|
|
EntityType: entityType,
|
|
EntityID: entityID,
|
|
Details: details,
|
|
IPAddress: ipAddress,
|
|
UserAgent: userAgent,
|
|
}
|
|
|
|
return db.Create(log).Error
|
|
} |