From 515851f7089819520eea8aa3e85f36874c680aa2 Mon Sep 17 00:00:00 2001 From: cedrok Date: Fri, 2 Aug 2024 11:38:56 +0200 Subject: [PATCH 01/13] refactor(api) AsteriskLine constant --- API/controllers/auth.go | 44 ++++++++++---------- API/controllers/auth_test.go | 4 +- API/controllers/entity.go | 78 ++++++++++++++++++------------------ API/controllers/event.go | 4 +- API/controllers/image.go | 4 +- API/controllers/schema.go | 4 +- API/controllers/web.go | 12 +++--- API/utils/util.go | 2 + 8 files changed, 78 insertions(+), 74 deletions(-) diff --git a/API/controllers/auth.go b/API/controllers/auth.go index b8aa80886..75a0f72fc 100644 --- a/API/controllers/auth.go +++ b/API/controllers/auth.go @@ -13,6 +13,8 @@ import ( "go.mongodb.org/mongo-driver/bson/primitive" ) +const invalidRequestMsg = "invalid request" + func init() { rand.Seed(time.Now().UnixNano()) } @@ -47,9 +49,9 @@ func init() { // description: Internal server error func CreateAccount(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: CreateAccount ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) if r.Method == "OPTIONS" { @@ -105,16 +107,16 @@ func CreateAccount(w http.ResponseWriter, r *http.Request) { // description: Internal server error func CreateBulkAccount(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: CreateBulkAccount ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) var accounts []models.Account err := json.NewDecoder(r.Body).Decode(&accounts) if err != nil { w.WriteHeader(http.StatusBadRequest) - u.Respond(w, u.Message("Invalid request")) + u.Respond(w, u.Message(invalidRequestMsg)) return } @@ -178,9 +180,9 @@ func randStringBytes(n int) string { // description: Internal server error func Authenticate(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: Authenticate ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) if r.Method == "OPTIONS" { @@ -190,7 +192,7 @@ func Authenticate(w http.ResponseWriter, r *http.Request) { err := json.NewDecoder(r.Body).Decode(&account) if err != nil { w.WriteHeader(http.StatusBadRequest) - u.Respond(w, u.Message("Invalid request")) + u.Respond(w, u.Message(invalidRequestMsg)) return } @@ -221,9 +223,9 @@ func Authenticate(w http.ResponseWriter, r *http.Request) { // description: Internal server error func VerifyToken(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: Verify ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) if r.Method == "OPTIONS" { @@ -247,9 +249,9 @@ func VerifyToken(w http.ResponseWriter, r *http.Request) { // description: Internal server error func GetAllAccounts(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: GetAllAccount ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) if r.Method == "OPTIONS" { @@ -300,9 +302,9 @@ func GetAllAccounts(w http.ResponseWriter, r *http.Request) { // description: Internal server error func RemoveAccount(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: RemoveAccount ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) if r.Method == "OPTIONS" { @@ -378,9 +380,9 @@ func RemoveAccount(w http.ResponseWriter, r *http.Request) { // description: Internal server error func ModifyUserRoles(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: ModifyUserRoles ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) if r.Method == "OPTIONS" { @@ -502,9 +504,9 @@ func getUserRolesFromBody(r *http.Request) (map[string]models.Role, error) { // description: Internal server error func ModifyUserPassword(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: ModifyUserPassword ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) if r.Method == "OPTIONS" { @@ -606,9 +608,9 @@ func getModifyPassDataFromBody(r *http.Request, userEmail string) (string, strin // description: Internal server error func UserForgotPassword(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: UserForgotPassword ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) if r.Method == "OPTIONS" { @@ -619,7 +621,7 @@ func UserForgotPassword(w http.ResponseWriter, r *http.Request) { err := json.NewDecoder(r.Body).Decode(&data) if err != nil { w.WriteHeader(http.StatusBadRequest) - u.Respond(w, u.Message("Invalid request")) + u.Respond(w, u.Message(invalidRequestMsg)) return } userEmail, hasEmail := data["email"].(string) diff --git a/API/controllers/auth_test.go b/API/controllers/auth_test.go index bbaef28fe..7ce3fbf1d 100644 --- a/API/controllers/auth_test.go +++ b/API/controllers/auth_test.go @@ -258,8 +258,8 @@ func TestRequestsWithInvalidBody(t *testing.T) { message string }{ {"CreateUser", "POST", test_utils.GetEndpoint("users"), "Invalid request: wrong format body"}, - {"CreateBulkUsers", "POST", test_utils.GetEndpoint("usersBulk"), "Invalid request"}, - {"Login", "POST", test_utils.GetEndpoint("login"), "Invalid request"}, + {"CreateBulkUsers", "POST", test_utils.GetEndpoint("usersBulk"), "invalid request"}, + {"Login", "POST", test_utils.GetEndpoint("login"), "invalid request"}, {"ModifyUser", "PATCH", test_utils.GetEndpoint("usersInstance", userId), "invalid request"}, {"ModifyPassword", "POST", test_utils.GetEndpoint("changePassword"), "invalid request"}, } diff --git a/API/controllers/entity.go b/API/controllers/entity.go index 7806f74f2..c7afea3fd 100644 --- a/API/controllers/entity.go +++ b/API/controllers/entity.go @@ -116,9 +116,9 @@ func getUserFromToken(w http.ResponseWriter, r *http.Request) *models.Account { // message will be returned.' func CreateEntity(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: CreateEntity ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) // Get entity entStr := mux.Vars(r)["entity"] @@ -203,9 +203,9 @@ func CreateEntity(w http.ResponseWriter, r *http.Request) { // description: 'Bad format: body is not a valid list of domains.' func CreateBulkDomain(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: CreateBulkDomain ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) // Get user roles for permissions user := getUserFromToken(w, r) @@ -292,7 +292,7 @@ func setDomainAttributes(parent string, domain map[string]any) (map[string]any, // Name is the only required attribute name, ok := domain["name"].(string) if !ok { - return nil, errors.New("Invalid format: Name is required for all domains") + return nil, errors.New("invalid format: Name is required for all domains") } domainObj["name"] = name @@ -447,9 +447,9 @@ func listAnyTolistMap(data []any) []map[string]interface{} { // description: Not found. An error message will be returned func HandleGenericObjects(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: HandleGenericObjects ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) matchingObjects := []map[string]interface{}{} @@ -639,9 +639,9 @@ func HandleGenericObjects(w http.ResponseWriter, r *http.Request) { // description: Not found. An error message will be returned func HandleComplexFilters(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: HandleComplexFilters ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) var complexFilters map[string]interface{} var complexFilterExp string @@ -767,9 +767,9 @@ func HandleComplexFilters(w http.ResponseWriter, r *http.Request) { // description: Not Found. An error message will be returned. func GetEntity(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: GetEntity ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) var data map[string]interface{} var id string @@ -845,9 +845,9 @@ func GetEntity(w http.ResponseWriter, r *http.Request) { // description: Not Found. An error message will be returned. func GetLayerObjects(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: GetLayerObjects ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) var data map[string]interface{} var id string @@ -957,9 +957,9 @@ func GetLayerObjects(w http.ResponseWriter, r *http.Request) { // description: Nothing Found. An error message will be returned. func GetAllEntities(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: GetAllEntities ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) var entStr string @@ -1064,9 +1064,9 @@ func getVirtualRootObjects(data []map[string]any) []map[string]any { // description: Not found. An error message will be returned func DeleteEntity(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: DeleteEntity ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) // Get user roles for permissions @@ -1200,9 +1200,9 @@ func DeleteEntity(w http.ResponseWriter, r *http.Request) { // description: Not Found. An error message will be returned. func UpdateEntity(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: UpdateEntity ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) var data map[string]interface{} var modelErr *u.Error @@ -1314,9 +1314,9 @@ func UpdateEntity(w http.ResponseWriter, r *http.Request) { // description: Not found. An error message will be returned. func GetEntityByQuery(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: GetEntityByQuery ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) var data []map[string]interface{} var entStr string @@ -1413,9 +1413,9 @@ func GetEntityByQuery(w http.ResponseWriter, r *http.Request) { // description: 'Nothing Found. An error message will be returned.' func GetSiteAttr(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: GetSiteAttr ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) // Check id id := mux.Vars(r)["id"] @@ -1483,9 +1483,9 @@ func GetSiteAttr(w http.ResponseWriter, r *http.Request) { // description: Nothing Found. An error message will be returned. func GetEntitiesOfAncestor(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: GetEntitiesOfAncestor ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) var id string var e bool @@ -1588,9 +1588,9 @@ func GetEntitiesOfAncestor(w http.ResponseWriter, r *http.Request) { // description: Nothing Found. An error message will be returned. func GetHierarchyByName(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: GetHierarchyByName ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) var limit int @@ -1692,9 +1692,9 @@ func GetHierarchyByName(w http.ResponseWriter, r *http.Request) { // description: Server error. func GetCompleteHierarchy(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: GetCompleteHierarchy ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) // Get user roles for permissions @@ -1734,9 +1734,9 @@ func GetCompleteHierarchy(w http.ResponseWriter, r *http.Request) { // description: Server error. func GetCompleteHierarchyAttributes(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: GetCompleteHierarchyAttributes ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) // Get user roles for permissions @@ -1824,9 +1824,9 @@ func GetCompleteHierarchyAttributes(w http.ResponseWriter, r *http.Request) { // description: 'Internal error. Unable to remove object from stray and create it in an entity.' func LinkEntity(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: LinkEntity ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) var data map[string]interface{} var id string @@ -1934,9 +1934,9 @@ func LinkEntity(w http.ResponseWriter, r *http.Request) { } func BaseOption(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: BaseOption ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) entity, e1 := mux.Vars(r)["entity"] if !e1 || u.EntityStrToInt(entity) == -1 { @@ -1960,9 +1960,9 @@ func BaseOption(w http.ResponseWriter, r *http.Request) { // description: Server error. func GetStats(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: GetStats ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) if r.Method == "OPTIONS" { w.Header().Add("Allow", "GET, HEAD, OPTIONS") @@ -2004,9 +2004,9 @@ func GetStats(w http.ResponseWriter, r *http.Request) { // description: Not Found. An error message will be returned. func ValidateEntity(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: ValidateEntity ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) var obj map[string]interface{} entity, e1 := mux.Vars(r)["entity"] diff --git a/API/controllers/event.go b/API/controllers/event.go index 1d2c1bd17..ec2520481 100644 --- a/API/controllers/event.go +++ b/API/controllers/event.go @@ -32,9 +32,9 @@ func init() { // description: 'Successfully established stream, keep it open.' func CreateEventStream(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: CreateEventStream ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) // Configure SSE stream w.Header().Set("Access-Control-Expose-Headers", "Content-Type") w.Header().Set("Content-Type", "text/event-stream") diff --git a/API/controllers/image.go b/API/controllers/image.go index cfe321e2e..5c75b76a8 100644 --- a/API/controllers/image.go +++ b/API/controllers/image.go @@ -50,9 +50,9 @@ func imageIDToUrl(entity int, object map[string]any) map[string]any { // description: Not Found. An error message will be returned. func GetImage(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: GetImage ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) image, err := models.GetImage(mux.Vars(r)["id"]) diff --git a/API/controllers/schema.go b/API/controllers/schema.go index 4f33aa392..c6ca49874 100644 --- a/API/controllers/schema.go +++ b/API/controllers/schema.go @@ -31,9 +31,9 @@ import ( // description: Not Found. An error message will be returned. func GetSchemaJSON(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: GetSchemaJSON ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) DispRequestMetaData(r) file, err := models.GetSchemaFile(mux.Vars(r)["id"]) diff --git a/API/controllers/web.go b/API/controllers/web.go index 209b3d898..6e98ea5fc 100644 --- a/API/controllers/web.go +++ b/API/controllers/web.go @@ -35,9 +35,9 @@ import ( // description: 'Internal server error.' func GetProjects(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: GetProjects ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) query, _ := url.ParseQuery(r.URL.RawQuery) @@ -121,9 +121,9 @@ func GetProjects(w http.ResponseWriter, r *http.Request) { // description: Internal server error func CreateOrUpdateProject(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: CreateOrUpdateProject ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) project := &models.Project{} err := json.NewDecoder(r.Body).Decode(project) @@ -178,9 +178,9 @@ func CreateOrUpdateProject(w http.ResponseWriter, r *http.Request) { // description: Internal server error func DeleteProject(w http.ResponseWriter, r *http.Request) { - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) fmt.Println("FUNCTION CALL: DeleteProject ") - fmt.Println("******************************************************") + fmt.Println(u.AsteriskLine) err := models.DeleteProject(mux.Vars(r)["id"]) diff --git a/API/utils/util.go b/API/utils/util.go index 61d6b009a..09e439628 100644 --- a/API/utils/util.go +++ b/API/utils/util.go @@ -28,6 +28,8 @@ var BuildTree string var BuildTime string var GitCommitDate string +const AsteriskLine = "******************************************************" + const ( DOMAIN = iota // hierarchical root entities From 222d4c0147f540d031e3fcd29a668b482a184c63 Mon Sep 17 00:00:00 2001 From: cedrok Date: Fri, 2 Aug 2024 11:43:07 +0200 Subject: [PATCH 02/13] refactor(api) fix duplicate strings --- API/controllers/auth.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/API/controllers/auth.go b/API/controllers/auth.go index 75a0f72fc..1f36cb4b5 100644 --- a/API/controllers/auth.go +++ b/API/controllers/auth.go @@ -437,7 +437,7 @@ func getUserRolesFromBody(r *http.Request) (map[string]models.Role, error) { var data map[string]interface{} err := json.NewDecoder(r.Body).Decode(&data) if err != nil { - return nil, fmt.Errorf("invalid request") + return nil, fmt.Errorf(invalidRequestMsg) } roles, ok := data["roles"].(map[string]interface{}) @@ -568,7 +568,7 @@ func getModifyPassDataFromBody(r *http.Request, userEmail string) (string, strin var data map[string]interface{} err := json.NewDecoder(r.Body).Decode(&data) if err != nil { - return currentPassword, "", isReset, fmt.Errorf("invalid request") + return currentPassword, "", isReset, fmt.Errorf(invalidRequestMsg) } if userEmail == u.RESET_TAG { // it's not change, it's reset (no need for current password) From 7749d6a5ffed6e8b4485d2e68ea1ad63fafab171 Mon Sep 17 00:00:00 2001 From: cedrok Date: Mon, 5 Aug 2024 18:30:05 +0200 Subject: [PATCH 03/13] refactor(cli) variable for asterisk lines in shell.go --- CLI/controllers/shell.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/CLI/controllers/shell.go b/CLI/controllers/shell.go index 4ec40f06a..7693fb31d 100644 --- a/CLI/controllers/shell.go +++ b/CLI/controllers/shell.go @@ -50,6 +50,8 @@ type ShellState struct { DryRunErrors []error } +const asteriskLine = "********************************************" + func Clear() { switch runtime.GOOS { case "windows": @@ -213,9 +215,9 @@ func SetEnv(arg string, val interface{}) { } func LSOG() error { - fmt.Println("********************************************") + fmt.Println(asteriskLine) fmt.Println("OGREE Shell Information") - fmt.Println("********************************************") + fmt.Println(asteriskLine) fmt.Println("USER EMAIL:", State.User.Email) fmt.Println("API URL:", State.APIURL+"/api/") @@ -231,9 +233,9 @@ func LSOG() error { fmt.Println("DEBUG LEVEL: ", State.DebugLvl) fmt.Printf("\n\n") - fmt.Println("********************************************") + fmt.Println(asteriskLine) fmt.Println("API Information") - fmt.Println("********************************************") + fmt.Println(asteriskLine) //Get API Information here resp, err := API.Request("GET", "/api/version", nil, http.StatusOK) From 31ea22492249884601bc2f98ddaab8c1428fe136 Mon Sep 17 00:00:00 2001 From: cedrok Date: Mon, 5 Aug 2024 18:31:09 +0200 Subject: [PATCH 04/13] refactor(api) new function for entity check in CreateEntity() --- API/controllers/entity.go | 41 ++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/API/controllers/entity.go b/API/controllers/entity.go index c7afea3fd..7c6f6a81c 100644 --- a/API/controllers/entity.go +++ b/API/controllers/entity.go @@ -145,24 +145,8 @@ func CreateEntity(w http.ResponseWriter, r *http.Request) { return } - if entStr == u.HIERARCHYOBJS_ENT { - // Get entity from object's category - entStr = object["category"].(string) - entInt = u.EntityStrToInt(entStr) - if entInt < u.SITE || entInt > u.GROUP { - w.WriteHeader(http.StatusBadRequest) - u.Respond(w, u.Message("Invalid category for a hierarchy object")) - u.ErrLog("Cannot create invalid hierarchy object", "CREATE "+mux.Vars(r)["entity"], "", r) - return - } - } else if u.IsEntityHierarchical(entInt) && entInt != u.STRAYOBJ { - // Check if category and endpoint match, except for non hierarchal entities and strays - if object["category"] != entStr { - w.WriteHeader(http.StatusBadRequest) - u.Respond(w, u.Message("Category in request body does not correspond with desired object in endpoint")) - u.ErrLog("Cannot create invalid object", "CREATE "+mux.Vars(r)["entity"], "", r) - return - } + if ok := checkEntity(w, r, entStr, entInt, object); !ok { + return } // Clean the data of 'id' attribute if present @@ -182,6 +166,27 @@ func CreateEntity(w http.ResponseWriter, r *http.Request) { } } +func checkEntity(w http.ResponseWriter, r *http.Request, entStr string, entInt int, object map[string]interface{}) bool { + if entStr == u.HIERARCHYOBJS_ENT { + // Get entity from object's category + entStr = object["category"].(string) + entInt = u.EntityStrToInt(entStr) + if entInt < u.SITE || entInt > u.GROUP { + w.WriteHeader(http.StatusBadRequest) + u.Respond(w, u.Message("Invalid category for a hierarchy object")) + u.ErrLog("Cannot create invalid hierarchy object", "CREATE "+mux.Vars(r)["entity"], "", r) + return false + } + // Check if category and endpoint match, except for non hierarchal entities and strays + } else if u.IsEntityHierarchical(entInt) && entInt != u.STRAYOBJ && object["category"] != entStr { + w.WriteHeader(http.StatusBadRequest) + u.Respond(w, u.Message("Category in request body does not correspond with desired object in endpoint")) + u.ErrLog("Cannot create invalid object", "CREATE "+mux.Vars(r)["entity"], "", r) + return false + } + return true +} + // swagger:operation POST /api/domains/bulk Organization CreateBulkDomain // Create multiple domains in a single request. // An array of domains should be provided in the body. From 17def7da1f9ebb703eb5658b9bdf67e19f3a9112 Mon Sep 17 00:00:00 2001 From: cedrok Date: Tue, 6 Aug 2024 15:13:29 +0200 Subject: [PATCH 05/13] refactor(api) simplify getBulkDomainsRecursively() --- API/controllers/entity.go | 37 +++++++++++++++++++------------------ 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/API/controllers/entity.go b/API/controllers/entity.go index 7c6f6a81c..accdb8f43 100644 --- a/API/controllers/entity.go +++ b/API/controllers/entity.go @@ -267,31 +267,32 @@ func getBulkDomainsRecursively(parent string, listDomains []map[string]interface domainsToCreate = append(domainsToCreate, domainObj) // Add children domain, if any - if children, ok := domain["domains"].([]interface{}); ok { - if len(children) > 0 { - // Convert from interface to map - dChildren := listAnyTolistMap(children) - - // Set parentId for children - var parentId string - if parent == "" { - parentId = domain["name"].(string) - } else { - parentId = parent + "." + domain["name"].(string) - } + if children, ok := domain["domains"].([]interface{}); ok && len(children) > 0 { + // Convert from interface to map + dChildren := listAnyTolistMap(children) - // Add children - childDomains, e := getBulkDomainsRecursively(parentId, dChildren) - if e != nil { - return nil, e - } - domainsToCreate = append(domainsToCreate, childDomains...) + parentId := setParentId(parent, domain) + + // Add children + childDomains, e := getBulkDomainsRecursively(parentId, dChildren) + if e != nil { + return nil, e } + domainsToCreate = append(domainsToCreate, childDomains...) } } return domainsToCreate, nil } +// Set parentId from parent & domain name +func setParentId(parent string, domain map[string]interface{}) string { + if parent == "" { + return domain["name"].(string) + } else { + return parent + "." + domain["name"].(string) + } +} + func setDomainAttributes(parent string, domain map[string]any) (map[string]any, error) { domainObj := map[string]any{} // Name is the only required attribute From c3a9bd8ce886072e14fe4cbfa2caa720704b1b9a Mon Sep 17 00:00:00 2001 From: cedrok Date: Wed, 7 Aug 2024 11:45:02 +0200 Subject: [PATCH 06/13] refactor(api) simplify HandleGenericObjects() --- API/controllers/entity.go | 70 ++++++++++++++++++++++----------------- 1 file changed, 40 insertions(+), 30 deletions(-) diff --git a/API/controllers/entity.go b/API/controllers/entity.go index accdb8f43..a4ca169dc 100644 --- a/API/controllers/entity.go +++ b/API/controllers/entity.go @@ -457,7 +457,6 @@ func HandleGenericObjects(w http.ResponseWriter, r *http.Request) { fmt.Println("FUNCTION CALL: HandleGenericObjects ") fmt.Println(u.AsteriskLine) DispRequestMetaData(r) - matchingObjects := []map[string]interface{}{} // Get user roles for permissions user := getUserFromToken(w, r) @@ -466,35 +465,9 @@ func HandleGenericObjects(w http.ResponseWriter, r *http.Request) { } // Get objects - filters := getFiltersFromQueryParams(r) - req := u.FilteredReqFromQueryParams(r.URL) - entities := u.GetEntitiesById(filters.Namespace, filters.Id) - - for _, entStr := range entities { - // Get objects - entData, err := models.GetManyObjects(entStr, req, filters, "", user.Roles) - if err != nil { - u.ErrLog("Error while looking for objects at "+entStr, "HandleGenericObjects", err.Message, r) - u.RespondWithError(w, err) - return - } - - // Save entity to help delete and respond - for _, obj := range entData { - obj["entity"] = entStr - } - - if nLimit, e := strconv.Atoi(filters.Limit); e == nil && nLimit > 0 && req["id"] != nil { - // Get children until limit level (only for GET) - for _, obj := range entData { - obj["children"], err = models.GetHierarchyByName(entStr, obj["id"].(string), nLimit, filters) - if err != nil { - u.ErrLog("Error while getting "+entStr, "GET "+entStr, err.Message, r) - u.RespondWithError(w, err) - } - } - } - matchingObjects = append(matchingObjects, entData...) + matchingObjects, ok := getGenericObjects(w, r, user) + if !ok { + return } // Respond @@ -532,6 +505,43 @@ func HandleGenericObjects(w http.ResponseWriter, r *http.Request) { } } +func getGenericObjects(w http.ResponseWriter, r *http.Request, user *models.Account) ([]map[string]interface{}, bool) { + matchingObjects := []map[string]interface{}{} + + filters := getFiltersFromQueryParams(r) + req := u.FilteredReqFromQueryParams(r.URL) + entities := u.GetEntitiesById(filters.Namespace, filters.Id) + + for _, entStr := range entities { + // Get objects + entData, err := models.GetManyObjects(entStr, req, filters, "", user.Roles) + if err != nil { + u.ErrLog("Error while looking for objects at "+entStr, "HandleGenericObjects", err.Message, r) + u.RespondWithError(w, err) + return nil, false + } + + // Save entity to help delete and respond + for _, obj := range entData { + obj["entity"] = entStr + } + + if nLimit, e := strconv.Atoi(filters.Limit); e == nil && nLimit > 0 && req["id"] != nil { + // Get children until limit level (only for GET) + for _, obj := range entData { + obj["children"], err = models.GetHierarchyByName(entStr, obj["id"].(string), nLimit, filters) + if err != nil { + u.ErrLog("Error while getting "+entStr, "GET "+entStr, err.Message, r) + u.RespondWithError(w, err) + } + } + } + matchingObjects = append(matchingObjects, entData...) + } + + return matchingObjects, true +} + // swagger:operation POST /api/objects/search Objects HandleComplexFilters // Get all objects from any entity that match the complex filter. Return as a list. // Wildcards can be used on any of the parameters present in query with equality and inequality operations. From a38fe64adcb2d8f43f32e7c63daf540eb4a2c21a Mon Sep 17 00:00:00 2001 From: cedrok Date: Thu, 8 Aug 2024 15:27:53 +0200 Subject: [PATCH 07/13] refactor(api) simplify HandleComplexFilters() --- API/controllers/entity.go | 39 +++++++++++---------------------------- 1 file changed, 11 insertions(+), 28 deletions(-) diff --git a/API/controllers/entity.go b/API/controllers/entity.go index a4ca169dc..2fc733ce4 100644 --- a/API/controllers/entity.go +++ b/API/controllers/entity.go @@ -465,7 +465,7 @@ func HandleGenericObjects(w http.ResponseWriter, r *http.Request) { } // Get objects - matchingObjects, ok := getGenericObjects(w, r, user) + matchingObjects, ok := getGenericObjects(w, r, user, "", "HandleGenericObjects") if !ok { return } @@ -505,7 +505,7 @@ func HandleGenericObjects(w http.ResponseWriter, r *http.Request) { } } -func getGenericObjects(w http.ResponseWriter, r *http.Request, user *models.Account) ([]map[string]interface{}, bool) { +func getGenericObjects(w http.ResponseWriter, r *http.Request, user *models.Account, complexFilterExp, funcName string) ([]map[string]interface{}, bool) { matchingObjects := []map[string]interface{}{} filters := getFiltersFromQueryParams(r) @@ -514,9 +514,9 @@ func getGenericObjects(w http.ResponseWriter, r *http.Request, user *models.Acco for _, entStr := range entities { // Get objects - entData, err := models.GetManyObjects(entStr, req, filters, "", user.Roles) + entData, err := models.GetManyObjects(entStr, req, filters, complexFilterExp, user.Roles) if err != nil { - u.ErrLog("Error while looking for objects at "+entStr, "HandleGenericObjects", err.Message, r) + u.ErrLog("Error while looking for objects at "+entStr, funcName, err.Message, r) u.RespondWithError(w, err) return nil, false } @@ -524,6 +524,10 @@ func getGenericObjects(w http.ResponseWriter, r *http.Request, user *models.Acco // Save entity to help delete and respond for _, obj := range entData { obj["entity"] = entStr + if entStr == "device" && strings.Contains(complexFilterExp, "virtual_config.type=node") { + // add namespace prefix to device nodes + obj["id"] = "Physical." + obj["id"].(string) + } } if nLimit, e := strconv.Atoi(filters.Limit); e == nil && nLimit > 0 && req["id"] != nil { @@ -662,7 +666,6 @@ func HandleComplexFilters(w http.ResponseWriter, r *http.Request) { var complexFilters map[string]interface{} var complexFilterExp string var ok bool - matchingObjects := []map[string]interface{}{} // Get user roles for permissions user := getUserFromToken(w, r) @@ -683,29 +686,9 @@ func HandleComplexFilters(w http.ResponseWriter, r *http.Request) { println(complexFilterExp) // Get objects - filters := getFiltersFromQueryParams(r) - req := u.FilteredReqFromQueryParams(r.URL) - entities := u.GetEntitiesById(filters.Namespace, filters.Id) - - for _, entStr := range entities { - // Get objects - entData, err := models.GetManyObjects(entStr, req, filters, complexFilterExp, user.Roles) - if err != nil { - u.ErrLog("Error while looking for objects at "+entStr, "HandleComplexFilters", err.Message, r) - u.RespondWithError(w, err) - return - } - - // Save entity to help delete and respond - for _, obj := range entData { - obj["entity"] = entStr - if entStr == "device" && strings.Contains(complexFilterExp, "virtual_config.type=node") { - // add namespace prefix to device nodes - obj["id"] = "Physical." + obj["id"].(string) - } - } - - matchingObjects = append(matchingObjects, entData...) + matchingObjects, ok := getGenericObjects(w, r, user, complexFilterExp, "HandleComplexFilters") + if !ok { + return } if r.Method == "DELETE" { From 0bdd43d58c7f9b5f9fa44a7e0e8804bd7f696242 Mon Sep 17 00:00:00 2001 From: cedrok Date: Thu, 8 Aug 2024 15:31:05 +0200 Subject: [PATCH 08/13] fix(api) missing DELETE option header --- API/controllers/entity.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/API/controllers/entity.go b/API/controllers/entity.go index 2fc733ce4..071beec15 100644 --- a/API/controllers/entity.go +++ b/API/controllers/entity.go @@ -493,7 +493,7 @@ func HandleGenericObjects(w http.ResponseWriter, r *http.Request) { } u.Respond(w, u.RespDataWrapper("successfully deleted objects", matchingObjects)) } else if r.Method == "OPTIONS" { - u.WriteOptionsHeader(w, "GET") + u.WriteOptionsHeader(w, "GET, DELETE") } else { matchingObjects = pie.Map(matchingObjects, func(object map[string]any) map[string]any { entityStr := object["entity"].(string) @@ -712,7 +712,7 @@ func HandleComplexFilters(w http.ResponseWriter, r *http.Request) { } u.Respond(w, u.RespDataWrapper("successfully deleted objects", matchingObjects)) } else if r.Method == "OPTIONS" { - u.WriteOptionsHeader(w, "POST") + u.WriteOptionsHeader(w, "POST, DELETE") } else { u.Respond(w, u.RespDataWrapper("successfully processed request", matchingObjects)) } From 2c3df86fee71732fec1fad97c9043bee8cc3c721 Mon Sep 17 00:00:00 2001 From: cedrok Date: Fri, 9 Aug 2024 14:09:48 +0200 Subject: [PATCH 09/13] refactor(api) reduce complexity of getGenericObjects() --- API/controllers/entity.go | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/API/controllers/entity.go b/API/controllers/entity.go index 071beec15..12aab159e 100644 --- a/API/controllers/entity.go +++ b/API/controllers/entity.go @@ -521,6 +521,8 @@ func getGenericObjects(w http.ResponseWriter, r *http.Request, user *models.Acco return nil, false } + nLimit, e := strconv.Atoi(filters.Limit) + // Save entity to help delete and respond for _, obj := range entData { obj["entity"] = entStr @@ -528,11 +530,8 @@ func getGenericObjects(w http.ResponseWriter, r *http.Request, user *models.Acco // add namespace prefix to device nodes obj["id"] = "Physical." + obj["id"].(string) } - } - if nLimit, e := strconv.Atoi(filters.Limit); e == nil && nLimit > 0 && req["id"] != nil { - // Get children until limit level (only for GET) - for _, obj := range entData { + if e == nil && nLimit > 0 && req["id"] != nil { obj["children"], err = models.GetHierarchyByName(entStr, obj["id"].(string), nLimit, filters) if err != nil { u.ErrLog("Error while getting "+entStr, "GET "+entStr, err.Message, r) @@ -540,6 +539,17 @@ func getGenericObjects(w http.ResponseWriter, r *http.Request, user *models.Acco } } } + + // if nLimit, e := strconv.Atoi(filters.Limit); e == nil && nLimit > 0 && req["id"] != nil { + // // Get children until limit level (only for GET) + // for _, obj := range entData { + // obj["children"], err = models.GetHierarchyByName(entStr, obj["id"].(string), nLimit, filters) + // if err != nil { + // u.ErrLog("Error while getting "+entStr, "GET "+entStr, err.Message, r) + // u.RespondWithError(w, err) + // } + // } + // } matchingObjects = append(matchingObjects, entData...) } From d43033ccc16f809be205c2e02eb3a943acdb2bee Mon Sep 17 00:00:00 2001 From: cedrok Date: Fri, 9 Aug 2024 15:57:11 +0200 Subject: [PATCH 10/13] refactor(api) reduce complexity of getGenericObjects() --- API/controllers/entity.go | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/API/controllers/entity.go b/API/controllers/entity.go index 12aab159e..8a2e0cdfe 100644 --- a/API/controllers/entity.go +++ b/API/controllers/entity.go @@ -521,8 +521,6 @@ func getGenericObjects(w http.ResponseWriter, r *http.Request, user *models.Acco return nil, false } - nLimit, e := strconv.Atoi(filters.Limit) - // Save entity to help delete and respond for _, obj := range entData { obj["entity"] = entStr @@ -530,32 +528,34 @@ func getGenericObjects(w http.ResponseWriter, r *http.Request, user *models.Acco // add namespace prefix to device nodes obj["id"] = "Physical." + obj["id"].(string) } + } - if e == nil && nLimit > 0 && req["id"] != nil { - obj["children"], err = models.GetHierarchyByName(entStr, obj["id"].(string), nLimit, filters) - if err != nil { - u.ErrLog("Error while getting "+entStr, "GET "+entStr, err.Message, r) - u.RespondWithError(w, err) - } - } + ok, err := checkChildrenLimit(entData, entStr, filters, req) + if !ok { + u.ErrLog("Error while getting "+entStr, "GET "+entStr, err.Message, r) + u.RespondWithError(w, err) } - // if nLimit, e := strconv.Atoi(filters.Limit); e == nil && nLimit > 0 && req["id"] != nil { - // // Get children until limit level (only for GET) - // for _, obj := range entData { - // obj["children"], err = models.GetHierarchyByName(entStr, obj["id"].(string), nLimit, filters) - // if err != nil { - // u.ErrLog("Error while getting "+entStr, "GET "+entStr, err.Message, r) - // u.RespondWithError(w, err) - // } - // } - // } matchingObjects = append(matchingObjects, entData...) } return matchingObjects, true } +func checkChildrenLimit(entData []map[string]interface{}, entStr string, filters u.RequestFilters, req primitive.M) (bool, *u.Error) { + if nLimit, e := strconv.Atoi(filters.Limit); e == nil && nLimit > 0 && req["id"] != nil { + // Get children until limit level (only for GET) + for _, obj := range entData { + var err *u.Error + obj["children"], err = models.GetHierarchyByName(entStr, obj["id"].(string), nLimit, filters) + if err != nil { + return false, err + } + } + } + return true, nil +} + // swagger:operation POST /api/objects/search Objects HandleComplexFilters // Get all objects from any entity that match the complex filter. Return as a list. // Wildcards can be used on any of the parameters present in query with equality and inequality operations. From edaaa82892eccf0264f983e7f85ecd73fc863db9 Mon Sep 17 00:00:00 2001 From: cedrok Date: Fri, 9 Aug 2024 17:00:54 +0200 Subject: [PATCH 11/13] refactor(api) remove duplicated lines --- API/controllers/entity.go | 64 +++++++++++++++------------------------ 1 file changed, 25 insertions(+), 39 deletions(-) diff --git a/API/controllers/entity.go b/API/controllers/entity.go index 8a2e0cdfe..8d821e81e 100644 --- a/API/controllers/entity.go +++ b/API/controllers/entity.go @@ -472,26 +472,7 @@ func HandleGenericObjects(w http.ResponseWriter, r *http.Request) { // Respond if r.Method == "DELETE" { - for _, obj := range matchingObjects { - entStr := obj["entity"].(string) - - var objStr string - - if u.IsEntityNonHierarchical(u.EntityStrToInt(entStr)) { - objStr = obj["slug"].(string) - } else { - objStr = obj["id"].(string) - } - - modelErr := models.DeleteObject(entStr, objStr, user.Roles) - if modelErr != nil { - u.ErrLog("Error while deleting object: "+objStr, "DELETE GetGenericObjectById", modelErr.Message, r) - u.RespondWithError(w, modelErr) - return - } - eventNotifier <- u.FormatNotifyData("delete", entStr, objStr) - } - u.Respond(w, u.RespDataWrapper("successfully deleted objects", matchingObjects)) + deleteGenericObjects(w, r, user, matchingObjects) } else if r.Method == "OPTIONS" { u.WriteOptionsHeader(w, "GET, DELETE") } else { @@ -556,6 +537,28 @@ func checkChildrenLimit(entData []map[string]interface{}, entStr string, filters return true, nil } +func deleteGenericObjects(w http.ResponseWriter, r *http.Request, user *models.Account, matchingObjects []map[string]interface{}) { + for _, obj := range matchingObjects { + entStr := obj["entity"].(string) + + var objStr string + if u.IsEntityNonHierarchical(u.EntityStrToInt(entStr)) { + objStr = obj["slug"].(string) + } else { + objStr = obj["id"].(string) + } + + modelErr := models.DeleteObject(entStr, objStr, user.Roles) + if modelErr != nil { + u.ErrLog("Error while deleting object: "+objStr, "DELETE GetGenericObjectById", modelErr.Message, r) + u.RespondWithError(w, modelErr) + return + } + eventNotifier <- u.FormatNotifyData("delete", entStr, objStr) + } + u.Respond(w, u.RespDataWrapper("successfully deleted objects", matchingObjects)) +} + // swagger:operation POST /api/objects/search Objects HandleComplexFilters // Get all objects from any entity that match the complex filter. Return as a list. // Wildcards can be used on any of the parameters present in query with equality and inequality operations. @@ -701,26 +704,9 @@ func HandleComplexFilters(w http.ResponseWriter, r *http.Request) { return } + // Respond if r.Method == "DELETE" { - for _, obj := range matchingObjects { - entStr := obj["entity"].(string) - - var objStr string - - if u.IsEntityNonHierarchical(u.EntityStrToInt(entStr)) { - objStr = obj["slug"].(string) - } else { - objStr = obj["id"].(string) - } - - modelErr := models.DeleteObject(entStr, objStr, user.Roles) - if modelErr != nil { - u.ErrLog("Error while deleting object: "+objStr, "DELETE GetGenericObjectById", modelErr.Message, r) - u.RespondWithError(w, modelErr) - return - } - } - u.Respond(w, u.RespDataWrapper("successfully deleted objects", matchingObjects)) + deleteGenericObjects(w, r, user, matchingObjects) } else if r.Method == "OPTIONS" { u.WriteOptionsHeader(w, "POST, DELETE") } else { From 17a66bdc30fef285622fdd201d853b3744558b98 Mon Sep 17 00:00:00 2001 From: cedrok Date: Wed, 28 Aug 2024 17:33:32 +0200 Subject: [PATCH 12/13] refactor(api) const for messages --- API/controllers/entity.go | 42 +++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/API/controllers/entity.go b/API/controllers/entity.go index 8d821e81e..5fcd38a02 100644 --- a/API/controllers/entity.go +++ b/API/controllers/entity.go @@ -21,6 +21,10 @@ import ( "go.mongodb.org/mongo-driver/bson/primitive" ) +const SuccessProcessedMsg = "successfully processed request" +const ErrGettingMsg = "Error while getting " +const ErrParsingPathParamsMsg = "Error while parsing path parameters" + // This function is useful for debugging // purposes. It displays any JSON func viewJson(r *http.Request) { @@ -482,7 +486,7 @@ func HandleGenericObjects(w http.ResponseWriter, r *http.Request) { return imageIDToUrl(u.EntityStrToInt(entityStr), object) }) - u.Respond(w, u.RespDataWrapper("successfully processed request", matchingObjects)) + u.Respond(w, u.RespDataWrapper(SuccessProcessedMsg, matchingObjects)) } } @@ -513,7 +517,7 @@ func getGenericObjects(w http.ResponseWriter, r *http.Request, user *models.Acco ok, err := checkChildrenLimit(entData, entStr, filters, req) if !ok { - u.ErrLog("Error while getting "+entStr, "GET "+entStr, err.Message, r) + u.ErrLog(ErrGettingMsg+entStr, "GET "+entStr, err.Message, r) u.RespondWithError(w, err) } @@ -710,7 +714,7 @@ func HandleComplexFilters(w http.ResponseWriter, r *http.Request) { } else if r.Method == "OPTIONS" { u.WriteOptionsHeader(w, "POST, DELETE") } else { - u.Respond(w, u.RespDataWrapper("successfully processed request", matchingObjects)) + u.Respond(w, u.RespDataWrapper(SuccessProcessedMsg, matchingObjects)) } } @@ -786,8 +790,8 @@ func GetEntity(w http.ResponseWriter, r *http.Request) { data, modelErr = models.GetObjectById(id, entityStr, filters, user.Roles) } else { w.WriteHeader(http.StatusBadRequest) - u.Respond(w, u.Message("Error while parsing path parameters")) - u.ErrLog("Error while parsing path parameters", "GET ENTITY", "", r) + u.Respond(w, u.Message(ErrParsingPathParamsMsg)) + u.ErrLog(ErrParsingPathParamsMsg, "GET ENTITY", "", r) return } @@ -796,7 +800,7 @@ func GetEntity(w http.ResponseWriter, r *http.Request) { u.WriteOptionsHeader(w, "GET, DELETE, OPTIONS, PATCH, PUT") } else { if modelErr != nil { - u.ErrLog("Error while getting "+entityStr, "GET "+strings.ToUpper(entityStr), + u.ErrLog(ErrGettingMsg+entityStr, "GET "+strings.ToUpper(entityStr), modelErr.Message, r) u.RespondWithError(w, modelErr) } else { @@ -904,11 +908,11 @@ func GetLayerObjects(w http.ResponseWriter, r *http.Request) { if r.Method == "OPTIONS" { u.WriteOptionsHeader(w, "GET, DELETE, PATCH, PUT") } else { - u.Respond(w, u.RespDataWrapper("successfully processed request", matchingObjects)) + u.Respond(w, u.RespDataWrapper(SuccessProcessedMsg, matchingObjects)) } } else { w.WriteHeader(http.StatusBadRequest) - u.Respond(w, u.Message("Error while parsing path parameters")) + u.Respond(w, u.Message(ErrParsingPathParamsMsg)) return } } @@ -990,7 +994,7 @@ func GetAllEntities(w http.ResponseWriter, r *http.Request) { // Respond if e != nil { - u.ErrLog("Error while getting "+entStr+"s", "GET ALL "+strings.ToUpper(entStr), + u.ErrLog(ErrGettingMsg+entStr+"s", "GET ALL "+strings.ToUpper(entStr), e.Message, r) u.RespondWithError(w, e) } else { @@ -1086,8 +1090,8 @@ func DeleteEntity(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] if id == "" { w.WriteHeader(http.StatusBadRequest) - u.Respond(w, u.Message("Error while parsing path parameters")) - u.ErrLog("Error while parsing path parameters", "DELETE ENTITY", "", r) + u.Respond(w, u.Message(ErrParsingPathParamsMsg)) + u.ErrLog(ErrParsingPathParamsMsg, "DELETE ENTITY", "", r) } else { if entityStr == u.HIERARCHYOBJS_ENT { obj, err := models.GetHierarchicalObjectById(id, u.RequestFilters{}, user.Roles) @@ -1357,7 +1361,7 @@ func GetEntityByQuery(w http.ResponseWriter, r *http.Request) { data, modelErr = models.GetManyObjects(entStr, bsonMap, filters, "", user.Roles) if modelErr != nil { - u.ErrLog("Error while getting "+entStr, "GET ENTITYQUERY", modelErr.Message, r) + u.ErrLog(ErrGettingMsg+entStr, "GET ENTITYQUERY", modelErr.Message, r) u.RespondWithError(w, modelErr) } else { u.Respond(w, u.RespDataWrapper("successfully got query for "+entStr, data)) @@ -1514,8 +1518,8 @@ func GetEntitiesOfAncestor(w http.ResponseWriter, r *http.Request) { id, e = mux.Vars(r)["id"] if !e { w.WriteHeader(http.StatusBadRequest) - u.Respond(w, u.Message("Error while parsing path parameters")) - u.ErrLog("Error while parsing path parameters", "GET CHILDRENOFPARENT", "", r) + u.Respond(w, u.Message(ErrParsingPathParamsMsg)) + u.ErrLog(ErrParsingPathParamsMsg, "GET CHILDRENOFPARENT", "", r) return } @@ -1601,7 +1605,7 @@ func GetHierarchyByName(w http.ResponseWriter, r *http.Request) { if !e || !e2 { w.WriteHeader(http.StatusBadRequest) u.Respond(w, u.Message("Error while parsing URL")) - u.ErrLog("Error while parsing path parameters", "GetHierarchyByName", "", r) + u.ErrLog(ErrParsingPathParamsMsg, "GetHierarchyByName", "", r) return } @@ -1644,7 +1648,7 @@ func GetHierarchyByName(w http.ResponseWriter, r *http.Request) { // Respond if modelErr != nil { - u.ErrLog("Error while getting "+entity, "GET "+entity, modelErr.Message, r) + u.ErrLog(ErrGettingMsg+entity, "GET "+entity, modelErr.Message, r) u.RespondWithError(w, modelErr) } else if r.Method == "OPTIONS" { u.WriteOptionsHeader(w, "GET") @@ -1867,12 +1871,12 @@ func LinkEntity(w http.ResponseWriter, r *http.Request) { } } else { w.WriteHeader(http.StatusBadRequest) - u.Respond(w, u.Message("Error while parsing path parameters")) - u.ErrLog("Error while parsing path parameters", "GET ENTITY", "", r) + u.Respond(w, u.Message(ErrParsingPathParamsMsg)) + u.ErrLog(ErrParsingPathParamsMsg, "GET ENTITY", "", r) return } if modelErr != nil { - u.ErrLog("Error while getting "+entityStr, "GET "+strings.ToUpper(entityStr), + u.ErrLog(ErrGettingMsg+entityStr, "GET "+strings.ToUpper(entityStr), modelErr.Message, r) u.RespondWithError(w, modelErr) return From 060a282d599d44a018230875b95a57ce69784d5d Mon Sep 17 00:00:00 2001 From: cedrok Date: Wed, 28 Aug 2024 18:03:05 +0200 Subject: [PATCH 13/13] refactor(api) simplify GetLayerObjects() --- API/controllers/entity.go | 54 ++++++++++++++++++++++----------------- 1 file changed, 31 insertions(+), 23 deletions(-) diff --git a/API/controllers/entity.go b/API/controllers/entity.go index 5fcd38a02..47d04e9ad 100644 --- a/API/controllers/entity.go +++ b/API/controllers/entity.go @@ -527,6 +527,34 @@ func getGenericObjects(w http.ResponseWriter, r *http.Request, user *models.Acco return matchingObjects, true } +func applyLayerAndGetObjs(w http.ResponseWriter, r *http.Request, user *models.Account, filters u.LayerObjsFilters, data map[string]interface{}) ([]map[string]interface{}, bool) { + // Apply layer to get objects request + req := bson.M{} + var searchId string + if filters.IsRecursive { + searchId = filters.Root + ".**.*" + } else { + searchId = filters.Root + ".*" + } + u.AddFilterToReq(req, "id", searchId) + + // Get objects + matchingObjects := []map[string]interface{}{} + entities := u.GetEntitiesById(u.Any, searchId) + fmt.Println(req) + fmt.Println(entities) + for _, entStr := range entities { + entData, err := models.GetManyObjects(entStr, req, u.RequestFilters{}, data["filter"].(string), user.Roles) + if err != nil { + u.ErrLog("Error while looking for objects at "+entStr, "GetLayerObjects", err.Message, r) + u.RespondWithError(w, err) + return nil, false + } + matchingObjects = append(matchingObjects, entData...) + } + return matchingObjects, true +} + func checkChildrenLimit(entData []map[string]interface{}, entStr string, filters u.RequestFilters, req primitive.M) (bool, *u.Error) { if nLimit, e := strconv.Atoi(filters.Limit); e == nil && nLimit > 0 && req["id"] != nil { // Get children until limit level (only for GET) @@ -879,29 +907,9 @@ func GetLayerObjects(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) return } - - // Apply layer to get objects request - req := bson.M{} - var searchId string - if filters.IsRecursive { - searchId = filters.Root + ".**.*" - } else { - searchId = filters.Root + ".*" - } - u.AddFilterToReq(req, "id", searchId) - - // Get objects - matchingObjects := []map[string]interface{}{} - entities := u.GetEntitiesById(u.Any, searchId) - fmt.Println(req) - fmt.Println(entities) - for _, entStr := range entities { - entData, err := models.GetManyObjects(entStr, req, u.RequestFilters{}, data["filter"].(string), user.Roles) - if err != nil { - u.RespondWithError(w, err) - return - } - matchingObjects = append(matchingObjects, entData...) + matchingObjects, ok := applyLayerAndGetObjs(w, r, user, filters, data) + if !ok { + return } // Respond