diff --git a/API/controllers/auth.go b/API/controllers/auth.go index b8aa8088..1f36cb4b 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" { @@ -435,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{}) @@ -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" { @@ -566,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) @@ -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 bbaef28f..7ce3fbf1 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 7806f74f..47d04e9a 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) { @@ -116,9 +120,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"] @@ -145,24 +149,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 +170,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. @@ -203,9 +212,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) @@ -262,37 +271,38 @@ 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 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,11 +457,10 @@ 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{}{} // Get user roles for permissions user := getUserFromToken(w, r) @@ -460,70 +469,126 @@ func HandleGenericObjects(w http.ResponseWriter, r *http.Request) { } // Get objects + matchingObjects, ok := getGenericObjects(w, r, user, "", "HandleGenericObjects") + if !ok { + return + } + + // Respond + if r.Method == "DELETE" { + deleteGenericObjects(w, r, user, matchingObjects) + } else if r.Method == "OPTIONS" { + u.WriteOptionsHeader(w, "GET, DELETE") + } else { + matchingObjects = pie.Map(matchingObjects, func(object map[string]any) map[string]any { + entityStr := object["entity"].(string) + delete(object, "entity") + + return imageIDToUrl(u.EntityStrToInt(entityStr), object) + }) + u.Respond(w, u.RespDataWrapper(SuccessProcessedMsg, matchingObjects)) + } +} + +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) 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) + 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 + return nil, false } // 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 { - // 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) - } - } + ok, err := checkChildrenLimit(entData, entStr, filters, req) + if !ok { + u.ErrLog(ErrGettingMsg+entStr, "GET "+entStr, err.Message, r) + u.RespondWithError(w, err) } + matchingObjects = append(matchingObjects, entData...) } - // Respond - if r.Method == "DELETE" { - for _, obj := range matchingObjects { - entStr := obj["entity"].(string) + return matchingObjects, true +} - var objStr string +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) - if u.IsEntityNonHierarchical(u.EntityStrToInt(entStr)) { - objStr = obj["slug"].(string) - } else { - objStr = obj["id"].(string) - } + // 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 +} - 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 +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 } - eventNotifier <- u.FormatNotifyData("delete", entStr, objStr) } - u.Respond(w, u.RespDataWrapper("successfully deleted objects", matchingObjects)) - } else if r.Method == "OPTIONS" { - u.WriteOptionsHeader(w, "GET") - } else { - matchingObjects = pie.Map(matchingObjects, func(object map[string]any) map[string]any { - entityStr := object["entity"].(string) - delete(object, "entity") + } + return true, nil +} - return imageIDToUrl(u.EntityStrToInt(entityStr), object) - }) - u.Respond(w, u.RespDataWrapper("successfully processed request", matchingObjects)) +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 @@ -639,14 +704,13 @@ 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 var ok bool - matchingObjects := []map[string]interface{}{} // Get user roles for permissions user := getUserFromToken(w, r) @@ -667,55 +731,18 @@ 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 } + // 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") + u.WriteOptionsHeader(w, "POST, DELETE") } else { - u.Respond(w, u.RespDataWrapper("successfully processed request", matchingObjects)) + u.Respond(w, u.RespDataWrapper(SuccessProcessedMsg, matchingObjects)) } } @@ -767,9 +794,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 @@ -791,8 +818,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 } @@ -801,7 +828,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 { @@ -845,9 +872,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 @@ -880,40 +907,20 @@ 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 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 } } @@ -957,9 +964,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 @@ -995,7 +1002,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 { @@ -1064,9 +1071,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 @@ -1091,8 +1098,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) @@ -1200,9 +1207,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 +1321,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 @@ -1362,7 +1369,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)) @@ -1413,9 +1420,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 +1490,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 @@ -1519,8 +1526,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 } @@ -1588,9 +1595,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 @@ -1606,7 +1613,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 } @@ -1649,7 +1656,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") @@ -1692,9 +1699,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 +1741,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 +1831,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 @@ -1872,12 +1879,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 @@ -1934,9 +1941,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 +1967,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 +2011,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 1d2c1bd1..ec252048 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 cfe321e2..5c75b76a 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 4f33aa39..c6ca4987 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 0ab6ed43..bee0815c 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 61d6b009..09e43962 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 diff --git a/CLI/controllers/shell.go b/CLI/controllers/shell.go index 4ec40f06..7693fb31 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)