From eec1a136756e817ca22fb2e719dc0e50e5c3ddea Mon Sep 17 00:00:00 2001
From: jano3 <jano@uafrica.com>
Date: Wed, 22 Jun 2022 11:28:39 +0200
Subject: [PATCH] Fixed bug with audit events for arrays and added object index
 to array events

---
 audit/audit.go | 21 +++++++++++++++++++--
 1 file changed, 19 insertions(+), 2 deletions(-)

diff --git a/audit/audit.go b/audit/audit.go
index 1ff39ab..2b46667 100644
--- a/audit/audit.go
+++ b/audit/audit.go
@@ -63,9 +63,10 @@ func GetChanges(original interface{}, new interface{}) (map[string]interface{},
 			arrayObject, present := changes[objectKey]
 			if present {
 				if arrayOfObjects, ok := arrayObject.([]map[string]interface{}); ok {
-					if len(arrayOfObjects) > int(index) {
+					arrayIndex := ArrayIndexForObjectIndex(arrayOfObjects, index)
+					if arrayIndex != -1 {
 						// Add field to existing object in array
-						object := arrayOfObjects[index]
+						object := arrayOfObjects[arrayIndex]
 						object[field] = FieldChange{
 							From: change.From,
 							To:   change.To,
@@ -73,6 +74,7 @@ func GetChanges(original interface{}, new interface{}) (map[string]interface{},
 					} else {
 						// new object, append to existing array
 						fieldChange := map[string]interface{}{
+							"index": index,
 							field: FieldChange{
 								From: change.From,
 								To:   change.To,
@@ -85,6 +87,7 @@ func GetChanges(original interface{}, new interface{}) (map[string]interface{},
 			} else {
 				// Create array of objects
 				fieldChange := map[string]interface{}{
+					"index": index,
 					field: FieldChange{
 						From: change.From,
 						To:   change.To,
@@ -124,6 +127,20 @@ func ChildObjectChanges(changes map[string]interface{}, objectPath string, field
 	}
 }
 
+// ArrayIndexForObjectIndex gets the index of arrayOfObjects where the object's index field is equal to objectIndex.
+func ArrayIndexForObjectIndex(arrayOfObjects []map[string]interface{}, objectIndex int64) int {
+	for arrayIndex, object := range arrayOfObjects {
+		index, present := object["index"]
+		if present {
+			if index == objectIndex {
+				return arrayIndex
+			}
+		}
+	}
+
+	return -1
+}
+
 // GetAllChanges Returns the diff, structured in json, recursively
 // Be warned, here be dragons. Debug this first to understand how it works
 func GetAllChanges(original interface{}, new interface{}) (map[string]interface{}, error) {
-- 
GitLab