Passport/pkg/internal/services/events.go
LittleSheep 8c89d89382 Optimized audit, event logging system
 Audit logs
 Admin edit user permissions
2024-07-03 22:57:17 +08:00

49 lines
1.5 KiB
Go

package services
import (
"git.solsynth.dev/hydrogen/passport/pkg/internal/database"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"github.com/rs/zerolog/log"
)
var writeEventQueue []models.ActionEvent
var writeAuditQueue []models.AuditRecord
// AddEvent to keep operation logs by user themselves clear to query
func AddEvent(user models.Account, event, target, ip, ua string) {
writeEventQueue = append(writeEventQueue, models.ActionEvent{
Type: event,
Target: target,
IpAddress: ip,
UserAgent: ua,
AccountID: user.ID,
})
}
// AddAuditRecord to keep logs to make administrators' operations clear to query
func AddAuditRecord(operator models.Account, act, ip, ua string, metadata map[string]any) {
writeAuditQueue = append(writeAuditQueue, models.AuditRecord{
Action: act,
Metadata: metadata,
IpAddress: ip,
UserAgent: ua,
AccountID: operator.ID,
})
}
// SaveEventChanges runs every 60 seconds to save events / audits changes into database
func SaveEventChanges() {
if len(writeEventQueue) > 0 {
count := len(writeEventQueue)
database.C.CreateInBatches(writeEventQueue, min(count, 1000))
log.Info().Int("count", count).Msg("Saved action events changes into database...")
clear(writeEventQueue)
}
if len(writeAuditQueue) > 0 {
count := len(writeAuditQueue)
database.C.CreateInBatches(writeAuditQueue, min(count, 1000))
log.Info().Int("count", count).Msg("Saved audit records changes into database...")
clear(writeAuditQueue)
}
}