Files
online-backend/internal/identity/activitylog/middleware.go
GuwandykA 8795ae2195 Put the user's role and branch on GET /profile, upsert role_user and branch_user on POST, and drop their list endpoints.
Also accept flexible card-order form values, move mock seed under db/mock, and regenerate Swagger.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-22 17:56:07 +05:00

215 lines
4.7 KiB
Go

package activitylog
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"strconv"
"strings"
"time"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
)
var sensitiveFieldSubstrings = []string{"password", "token", "secret"}
const (
writeTimeout = 5 * time.Second
queueSize = 1024
workers = 2
)
type recorder struct {
repository Repository
logger *logging.Logger
queue chan CreateActivityLogDTO
}
// Record returns a global gin middleware that persists every mutating
// (POST/PUT/PATCH/DELETE) request made by an authenticated user into
// activity_logs - e.g. creating a card or attaching a user to a branch.
// Read-only (GET) requests are not recorded. After the handler finishes
// the entry is queued (the client is not blocked) and a small worker
// pool writes it. JwtTokenCheck sets "id" during c.Next(), which is why
// the user is read afterwards.
func Record(repository Repository, logger *logging.Logger) gin.HandlerFunc {
return newRecorder(repository, logger).handle
}
func newRecorder(repository Repository, logger *logging.Logger) *recorder {
r := &recorder{
repository: repository,
logger: logger,
queue: make(chan CreateActivityLogDTO, queueSize),
}
for i := 0; i < workers; i++ {
go r.worker()
}
return r
}
func (r *recorder) handle(c *gin.Context) {
if !shouldRecord(c.Request.Method) {
c.Next()
return
}
body := readAndRestoreBody(c)
c.Next()
userID := currentUserID(c)
if userID == nil {
return
}
id := *userID
module, action := describeRoute(c)
r.enqueue(CreateActivityLogDTO{
UserId: &id,
Method: c.Request.Method,
Path: c.Request.URL.Path,
Module: module,
Action: action,
StatusCode: c.Writer.Status(),
RequestBody: redact(body),
Ip: c.ClientIP(),
})
}
func (r *recorder) enqueue(entry CreateActivityLogDTO) {
select {
case r.queue <- entry:
default:
r.logger.Errorf("activity log queue full, dropping %s %s", entry.Method, entry.Path)
}
}
func (r *recorder) worker() {
for entry := range r.queue {
ctx, cancel := context.WithTimeout(context.Background(), writeTimeout)
if _, err := r.repository.Create(ctx, entry); err != nil {
r.logger.Errorf("record activity log failed: %v", err)
}
cancel()
}
}
func shouldRecord(method string) bool {
switch method {
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
return true
default:
return false
}
}
func readAndRestoreBody(c *gin.Context) []byte {
if c.Request.Body == nil {
return nil
}
data, err := io.ReadAll(c.Request.Body)
if err != nil {
c.Request.Body = io.NopCloser(bytes.NewReader(nil))
return nil
}
// Restore Body for ShouldBindJSON and cache it so ShouldBindBodyWithJSON
// still works after this middleware has already consumed the stream.
c.Request.Body = io.NopCloser(bytes.NewReader(data))
c.Set(gin.BodyBytesKey, data)
return data
}
func currentUserID(c *gin.Context) *int64 {
raw, exists := c.Get("id")
if !exists {
return nil
}
switch v := raw.(type) {
case int64:
return &v
case int:
id := int64(v)
return &id
case string:
id, err := strconv.ParseInt(v, 10, 64)
if err != nil {
return nil
}
return &id
default:
return nil
}
}
// describeRoute derives a module (e.g. "cards", "branch-users") and an
// action (create/update/delete) from the matched route so entries stay
// meaningful even though logging is wired generically for every module.
func describeRoute(c *gin.Context) (module, action string) {
action = actionFromMethod(c.Request.Method)
route := c.FullPath()
if route == "" {
route = c.Request.URL.Path
}
segments := strings.Split(strings.Trim(route, "/"), "/")
for i, segment := range segments {
if segment == "admin" && i+1 < len(segments) {
return segments[i+1], action
}
}
if len(segments) > 0 {
return segments[0], action
}
return "", action
}
func actionFromMethod(method string) string {
switch method {
case http.MethodPost:
return "create"
case http.MethodPut, http.MethodPatch:
return "update"
case http.MethodDelete:
return "delete"
default:
return strings.ToLower(method)
}
}
// redact blanks out sensitive fields (passwords, tokens, secrets) before a
// request body is stored. Bodies that aren't a JSON object are dropped
// entirely rather than risk leaking something unparsed.
func redact(body []byte) []byte {
if len(body) == 0 {
return nil
}
var payload map[string]interface{}
if err := json.Unmarshal(body, &payload); err != nil {
return nil
}
for key := range payload {
lower := strings.ToLower(key)
for _, needle := range sensitiveFieldSubstrings {
if strings.Contains(lower, needle) {
payload[key] = "***"
break
}
}
}
redacted, err := json.Marshal(payload)
if err != nil {
return nil
}
return redacted
}