2024-01-30 09:57:23 +00:00
|
|
|
package services
|
|
|
|
|
|
|
|
import (
|
2024-06-17 14:21:34 +00:00
|
|
|
"git.solsynth.dev/hydrogen/passport/pkg/internal/database"
|
|
|
|
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
|
2024-07-03 14:57:17 +00:00
|
|
|
"github.com/rs/zerolog/log"
|
2024-01-30 09:57:23 +00:00
|
|
|
)
|
|
|
|
|
2024-07-03 14:57:17 +00:00
|
|
|
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{
|
2024-01-30 09:57:23 +00:00
|
|
|
Type: event,
|
|
|
|
Target: target,
|
|
|
|
IpAddress: ip,
|
|
|
|
UserAgent: ua,
|
|
|
|
AccountID: user.ID,
|
2024-07-03 14:57:17 +00:00
|
|
|
})
|
|
|
|
}
|
2024-01-30 09:57:23 +00:00
|
|
|
|
2024-07-03 14:57:17 +00:00
|
|
|
// 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,
|
|
|
|
})
|
|
|
|
}
|
2024-01-30 09:57:23 +00:00
|
|
|
|
2024-07-03 14:57:17 +00:00
|
|
|
// 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)
|
|
|
|
}
|
2024-01-30 09:57:23 +00:00
|
|
|
}
|