Changeset 0.9.0 (#50)

This commit is contained in:
2026-02-23 01:57:28 +00:00
parent 15be26c516
commit 8264aa6016
94 changed files with 9812 additions and 8574 deletions

View File

@@ -0,0 +1,82 @@
package postgres
import (
"context"
"database/sql"
"encoding/json"
"git.gobha.me/xcaliber/chat-switchboard/models"
"git.gobha.me/xcaliber/chat-switchboard/store"
)
type AuditStore struct{}
func NewAuditStore() *AuditStore { return &AuditStore{} }
func (s *AuditStore) Log(ctx context.Context, entry *models.AuditEntry) error {
metadataJSON := ToJSON(entry.Metadata)
return DB.QueryRowContext(ctx, `
INSERT INTO audit_log (actor_id, action, resource_type, resource_id, metadata, ip_address, user_agent)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id, created_at`,
models.NullString(entry.ActorID), entry.Action, entry.ResourceType,
entry.ResourceID, metadataJSON, entry.IPAddress, entry.UserAgent,
).Scan(&entry.ID, &entry.CreatedAt)
}
func (s *AuditStore) List(ctx context.Context, opts store.AuditListOptions) ([]models.AuditEntry, int, error) {
b := NewSelect("id, actor_id, action, resource_type, resource_id, metadata, ip_address, user_agent, created_at", "audit_log")
if opts.ActorID != "" {
b.Where("actor_id = ?", opts.ActorID)
}
if opts.Action != "" {
b.Where("action = ?", opts.Action)
}
if opts.ResourceType != "" {
b.Where("resource_type = ?", opts.ResourceType)
}
if opts.ResourceID != "" {
b.Where("resource_id = ?", opts.ResourceID)
}
if opts.Since != nil {
b.Where("created_at >= ?", *opts.Since)
}
if opts.Until != nil {
b.Where("created_at <= ?", *opts.Until)
}
// Count
countQ, countArgs := b.CountBuild()
var total int
DB.QueryRowContext(ctx, countQ, countArgs...).Scan(&total)
// Results
if opts.Sort == "" {
b.OrderBy("created_at", "DESC")
}
b.Paginate(opts.ListOptions)
q, args := b.Build()
rows, err := DB.QueryContext(ctx, q, args...)
if err != nil {
return nil, 0, err
}
defer rows.Close()
var result []models.AuditEntry
for rows.Next() {
var e models.AuditEntry
var actorID sql.NullString
var metadataJSON []byte
err := rows.Scan(&e.ID, &actorID, &e.Action, &e.ResourceType, &e.ResourceID,
&metadataJSON, &e.IPAddress, &e.UserAgent, &e.CreatedAt)
if err != nil {
return nil, 0, err
}
e.ActorID = NullableStringPtr(actorID)
json.Unmarshal(metadataJSON, &e.Metadata)
result = append(result, e)
}
return result, total, rows.Err()
}