Files
online-backend/internal/identity/activitylog/middleware.go
2026-07-16 17:53:45 +05:00

177 lines
3.9 KiB
Go

package activitylog
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"strconv"
"strings"
"time"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
)
// sensitiveFieldSubstrings marks request body keys that must never be
// persisted verbatim (login passwords, branch billing credentials, etc).
var sensitiveFieldSubstrings = []string{"password", "token", "secret"}
const writeTimeout = 5 * time.Second
// 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. It must run after
// appresult.JwtTokenCheck has set "id" in the context, which happens
// naturally here since c.Next() runs the rest of the chain first.
func Record(repository Repository, logger *logging.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
if !shouldRecord(c.Request.Method) {
c.Next()
return
}
body := readAndRestoreBody(c)
c.Next()
userID := currentUserID(c)
if userID == nil {
return
}
module, action := describeRoute(c)
entry := CreateActivityLogDTO{
UserId: userID,
Method: c.Request.Method,
Path: c.Request.URL.Path,
Module: module,
Action: action,
StatusCode: c.Writer.Status(),
RequestBody: redact(body),
Ip: c.ClientIP(),
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), writeTimeout)
defer cancel()
if _, err := repository.Create(ctx, entry); err != nil {
logger.Errorf("record activity log failed: %v", err)
}
}()
}
}
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 {
return nil
}
c.Request.Body = io.NopCloser(bytes.NewReader(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
}