RezinaLMS-BackEnd/internal/web_server/handlers/activity_log_helper.go
2026-10-19 17:59:34 +03:00

43 lines
1.7 KiB
Go

package handlers
import (
"context"
"encoding/json"
"Rezina-Backend/internal/domain"
"github.com/gofiber/fiber/v2"
)
func activityActorFromCtx(c *fiber.Ctx) (actorID *int64, actorRole *string, ip *string, ua *string) {
ipStr := c.IP()
uaStr := c.Get("User-Agent")
ip = &ipStr
ua = &uaStr
if uid, ok := c.Locals("user_id").(int64); ok && uid > 0 {
actorID = &uid
}
if role, ok := c.Locals("role").(domain.Role); ok {
roleStr := string(role)
actorRole = &roleStr
}
return actorID, actorRole, ip, ua
}
func (h *Handler) recordActivity(c *fiber.Ctx, action domain.ActivityAction, resourceType domain.ResourceType, resourceID *int64, message string, metadata json.RawMessage) {
actorID, actorRole, ip, ua := activityActorFromCtx(c)
go h.activityLogSvc.RecordAction(context.Background(), actorID, actorRole, action, resourceType, resourceID, message, metadata, ip, ua)
}
// recordActivityAs records an activity for a known actor (e.g. login/register before JWT is in context).
func (h *Handler) recordActivityAs(c *fiber.Ctx, actorID int64, actorRole domain.Role, action domain.ActivityAction, resourceType domain.ResourceType, resourceID *int64, message string, metadata json.RawMessage) {
_, _, ip, ua := activityActorFromCtx(c)
id := actorID
roleStr := string(actorRole)
h.recordActivityWithActor(&id, &roleStr, ip, ua, action, resourceType, resourceID, message, metadata)
}
func (h *Handler) recordActivityWithActor(actorID *int64, actorRole *string, ip, ua *string, action domain.ActivityAction, resourceType domain.ResourceType, resourceID *int64, message string, metadata json.RawMessage) {
go h.activityLogSvc.RecordAction(context.Background(), actorID, actorRole, action, resourceType, resourceID, message, metadata, ip, ua)
}