From 789f2045bd4705650907e7f2acd3444bff606e73 Mon Sep 17 00:00:00 2001 From: Tushar-E <55044345+Tushar-kalsi@users.noreply.github.com> Date: Tue, 24 Oct 2023 21:19:00 +0530 Subject: [PATCH 1/9] Fix #96 short version of sensor UUID in server side Fixed #96 Some changes in handler.go file in publishHandler function intersepted msg []byte object decode it , made changes as per requirnments . --- backend/handlers.go | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/backend/handlers.go b/backend/handlers.go index a3414d0..1ef26f4 100644 --- a/backend/handlers.go +++ b/backend/handlers.go @@ -6,7 +6,7 @@ import ( "io" "net/http" "os" - + "strings" "github.com/honeynet/ochi/backend/entities" "github.com/julienschmidt/httprouter" @@ -38,6 +38,16 @@ func (cs *server) cssHandler(w http.ResponseWriter, r *http.Request, _ httproute } } +//Helper function which splits into two parts the sensorID by the hyphen +func splitSensorID(sensorID string) string { + parts := strings.Split(sensorID, "-") + if len(parts) > 0 { + return parts[0] + } + return sensorID // Return the original sensorID if there's no hyphen +} + + // publishHandler reads the request body with a limit of 8192 bytes and then publishes // the received message. func (cs *server) publishHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { @@ -49,7 +59,33 @@ func (cs *server) publishHandler(w http.ResponseWriter, r *http.Request, _ httpr } defer body.Close() - cs.publish(msg) + // Unmarshal the JSON message into a map + var data map[string]interface{} + if err := json.Unmarshal(msg, &data); err != nil { + http.Error(w, "Invalid JSON payload", http.StatusBadRequest) + return + } + + // Check if "sensorID" key exists + if sensorID, ok := data["sensorID"].(string); ok { + // Manipulate the "sensorID" + sensorID = splitSensorID(sensorID) + + + // Update the map with the new "sensorID" value + data["sensorID"] = sensorID + } + + // Marshal the map back to a JSON message + alteredMsg , err := json.Marshal(data) + if err != nil { + http.Error(w, "Error processing JSON", http.StatusInternalServerError) + return + } + + + + cs.publish(alteredMsg) w.WriteHeader(http.StatusAccepted) } From c4a961f729b0e94004d502a1cb7901f4b08f6163 Mon Sep 17 00:00:00 2001 From: Tushar-E <55044345+Tushar-kalsi@users.noreply.github.com> Date: Wed, 25 Oct 2023 09:25:35 +0530 Subject: [PATCH 2/9] Fix #96 Removed .split from front end code and added it to backend Removed .split ('-')[0] from front end code and already added this logic in backend --- frontend/components/Message.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/components/Message.svelte b/frontend/components/Message.svelte index 730a649..45fbce8 100644 --- a/frontend/components/Message.svelte +++ b/frontend/components/Message.svelte @@ -16,7 +16,7 @@

- {message.sensorID.split('-')[0]} | {message.srcHost}:{message.srcPort} -> {message.dstPort}: + {message.sensorID} | {message.srcHost}:{message.srcPort} -> {message.dstPort}: {#if message.handler}{message.handler}{:else}{message.rule}{/if} {#if message.scanner}"{message.scanner}"{/if} Details From 7b1c280ba8ed16998605e49f8397563c836166b0 Mon Sep 17 00:00:00 2001 From: Tushar-E <55044345+Tushar-kalsi@users.noreply.github.com> Date: Wed, 25 Oct 2023 23:01:49 +0530 Subject: [PATCH 3/9] Fix #96 Made changes as per discussion . I have made changes as per discussion please review . --- backend/handlers.go | 72 +++++++++++++++++++++++++-------------------- 1 file changed, 40 insertions(+), 32 deletions(-) diff --git a/backend/handlers.go b/backend/handlers.go index 1ef26f4..1a0c579 100644 --- a/backend/handlers.go +++ b/backend/handlers.go @@ -1,16 +1,16 @@ package backend import ( + "bytes" "context" "encoding/json" - "io" - "net/http" - "os" - "strings" + "fmt" "github.com/honeynet/ochi/backend/entities" - "github.com/julienschmidt/httprouter" "google.golang.org/api/idtoken" + "io" + "net/http" + "os" ) func (cs *server) indexHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { @@ -38,16 +38,14 @@ func (cs *server) cssHandler(w http.ResponseWriter, r *http.Request, _ httproute } } -//Helper function which splits into two parts the sensorID by the hyphen -func splitSensorID(sensorID string) string { - parts := strings.Split(sensorID, "-") - if len(parts) > 0 { - return parts[0] - } - return sensorID // Return the original sensorID if there's no hyphen +// Helper function which splits into two parts the sensorID by the hyphen +func extractFirst8CharactersOfSensorId(sensorID string) (string, error) { + if len(sensorID) < 8 { + return "", fmt.Errorf("Sensor ID must have at least 8 characters") + } + return sensorID[:8], nil } - // publishHandler reads the request body with a limit of 8192 bytes and then publishes // the received message. func (cs *server) publishHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { @@ -58,35 +56,45 @@ func (cs *server) publishHandler(w http.ResponseWriter, r *http.Request, _ httpr return } defer body.Close() - // Unmarshal the JSON message into a map - var data map[string]interface{} - if err := json.Unmarshal(msg, &data); err != nil { + decoder := json.NewDecoder(bytes.NewReader(msg)) + // Create a new map to store the sensorDataMap + var sensorIDMap map[string]interface{} + // Decode into the sensorDataMap + if err := decoder.Decode(&sensorIDMap); err != nil { http.Error(w, "Invalid JSON payload", http.StatusBadRequest) return } - - // Check if "sensorID" key exists - if sensorID, ok := data["sensorID"].(string); ok { - // Manipulate the "sensorID" - sensorID = splitSensorID(sensorID) - - - // Update the map with the new "sensorID" value - data["sensorID"] = sensorID + if sensorIDMap == nil { + // Handle the case where sensorMap is nil + http.Error(w, "Invalid JSON payload", http.StatusBadRequest) + return } - - // Marshal the map back to a JSON message - alteredMsg , err := json.Marshal(data) + // Get the sensorID from the map + sensorID, exists := sensorIDMap["sensorID"] + if !exists { + http.Error(w, "Sensor Id does not exists.", http.StatusBadRequest) + return + } + sensorIDStr, ok := sensorID.(string) + if !ok { + http.Error(w, "Sensor ID is not a string.", http.StatusBadRequest) + return + } + sensorID, err = extractFirst8CharactersOfSensorId(sensorIDStr) + if err != nil { + http.Error(w, "Sensor ID is less than 8 characters.", http.StatusBadRequest) + return + } + sensorIDMap["sensorID"] = sensorID + // Convert the sensorID back to a JSON message + alteredMsg, err := json.Marshal(sensorIDMap) if err != nil { http.Error(w, "Error processing JSON", http.StatusInternalServerError) return } - - - + // Publish the altered JSON message cs.publish(alteredMsg) - w.WriteHeader(http.StatusAccepted) } From 2536962d135f1d0ae9da34af008af45e290d8d97 Mon Sep 17 00:00:00 2001 From: Tushar-E <55044345+Tushar-kalsi@users.noreply.github.com> Date: Thu, 26 Oct 2023 10:22:50 +0530 Subject: [PATCH 4/9] Updated handlers.go file. --- backend/handlers.go | 51 ++++++++++++++------------------------------- 1 file changed, 16 insertions(+), 35 deletions(-) diff --git a/backend/handlers.go b/backend/handlers.go index 1a0c579..1f44cb0 100644 --- a/backend/handlers.go +++ b/backend/handlers.go @@ -1,16 +1,15 @@ package backend import ( - "bytes" "context" "encoding/json" - "fmt" - "github.com/honeynet/ochi/backend/entities" - "github.com/julienschmidt/httprouter" - "google.golang.org/api/idtoken" "io" "net/http" "os" + + "github.com/honeynet/ochi/backend/entities" + "github.com/julienschmidt/httprouter" + "google.golang.org/api/idtoken" ) func (cs *server) indexHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { @@ -38,54 +37,36 @@ func (cs *server) cssHandler(w http.ResponseWriter, r *http.Request, _ httproute } } -// Helper function which splits into two parts the sensorID by the hyphen -func extractFirst8CharactersOfSensorId(sensorID string) (string, error) { - if len(sensorID) < 8 { - return "", fmt.Errorf("Sensor ID must have at least 8 characters") - } - return sensorID[:8], nil -} - // publishHandler reads the request body with a limit of 8192 bytes and then publishes // the received message. func (cs *server) publishHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { body := http.MaxBytesReader(w, r.Body, 8192) - msg, err := io.ReadAll(body) - if err != nil { - http.Error(w, http.StatusText(http.StatusRequestEntityTooLarge), http.StatusRequestEntityTooLarge) - return - } - defer body.Close() + // Unmarshal the JSON message into a map - decoder := json.NewDecoder(bytes.NewReader(msg)) + decoder := json.NewDecoder(body) + // Create a new map to store the sensorDataMap - var sensorIDMap map[string]interface{} + var sensorIDMap map[string]string // Decode into the sensorDataMap if err := decoder.Decode(&sensorIDMap); err != nil { - http.Error(w, "Invalid JSON payload", http.StatusBadRequest) - return - } - if sensorIDMap == nil { - // Handle the case where sensorMap is nil - http.Error(w, "Invalid JSON payload", http.StatusBadRequest) + http.Error(w, "JSON decoding error: "+err.Error(), http.StatusBadRequest) return } + // Get the sensorID from the map sensorID, exists := sensorIDMap["sensorID"] if !exists { http.Error(w, "Sensor Id does not exists.", http.StatusBadRequest) return } - sensorIDStr, ok := sensorID.(string) - if !ok { - http.Error(w, "Sensor ID is not a string.", http.StatusBadRequest) - return - } - sensorID, err = extractFirst8CharactersOfSensorId(sensorIDStr) - if err != nil { - http.Error(w, "Sensor ID is less than 8 characters.", http.StatusBadRequest) + + if len(sensorID) < 8 { + http.Error(w, "Sensor ID must have at least 8 characters.", http.StatusBadRequest) return } + + sensorID = sensorID[:8] + sensorIDMap["sensorID"] = sensorID // Convert the sensorID back to a JSON message alteredMsg, err := json.Marshal(sensorIDMap) From e4e2d7000f7fb0285f580b7eab48579e39b50eab Mon Sep 17 00:00:00 2001 From: Tushar-E <55044345+Tushar-kalsi@users.noreply.github.com> Date: Thu, 26 Oct 2023 16:47:18 +0530 Subject: [PATCH 5/9] Changes made in error codes. --- backend/handlers.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/handlers.go b/backend/handlers.go index 1f44cb0..3c57a6e 100644 --- a/backend/handlers.go +++ b/backend/handlers.go @@ -49,19 +49,19 @@ func (cs *server) publishHandler(w http.ResponseWriter, r *http.Request, _ httpr var sensorIDMap map[string]string // Decode into the sensorDataMap if err := decoder.Decode(&sensorIDMap); err != nil { - http.Error(w, "JSON decoding error: "+err.Error(), http.StatusBadRequest) + http.Error(w, err.Error(), http.StatusBadRequest) return } // Get the sensorID from the map sensorID, exists := sensorIDMap["sensorID"] if !exists { - http.Error(w, "Sensor Id does not exists.", http.StatusBadRequest) + http.Error(w, "sensor id does not exists", http.StatusBadRequest) return } if len(sensorID) < 8 { - http.Error(w, "Sensor ID must have at least 8 characters.", http.StatusBadRequest) + http.Error(w, "sensor id must have at least 8 characters", http.StatusBadRequest) return } From 930eeb839a7ef901196e0ae5405b6dc9049a6727 Mon Sep 17 00:00:00 2001 From: Tushar kalsi <55044345+Tushar-kalsi@users.noreply.github.com> Date: Wed, 29 Nov 2023 23:11:52 +0530 Subject: [PATCH 6/9] Adding /sensor route. Added some file for /sensor route. --- backend/entities/sensor.go | 7 ++++ backend/handlers.go | 24 +++++++++++++ backend/repos/query_test.go | 2 ++ backend/repos/sensors.go | 66 +++++++++++++++++++++++++++++++++++ backend/repos/sensors_test.go | 30 ++++++++++++++++ backend/routes.go | 3 ++ backend/server.go | 14 +++++--- 7 files changed, 142 insertions(+), 4 deletions(-) create mode 100644 backend/entities/sensor.go create mode 100644 backend/repos/sensors.go create mode 100644 backend/repos/sensors_test.go diff --git a/backend/entities/sensor.go b/backend/entities/sensor.go new file mode 100644 index 0000000..ac18b8d --- /dev/null +++ b/backend/entities/sensor.go @@ -0,0 +1,7 @@ +package entities + +type Sensor struct { + Id string `json:"id"` + Name string `json:"name"` + OwnerId string `json:"ownerid"` +} diff --git a/backend/handlers.go b/backend/handlers.go index 9751afe..6f3cbf4 100644 --- a/backend/handlers.go +++ b/backend/handlers.go @@ -342,3 +342,27 @@ func (cs *server) getEventByIDHandler(w http.ResponseWriter, r *http.Request, p http.Error(w, err.Error(), http.StatusInternalServerError) } } + +func (cs *server) getSensorsByUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) { + + userId := userIDFromCtx(r.Context()) + events, err := cs.sensorRepo.GetSensorsByOwnerId(userId) + + if err != nil { + if isNotFoundError(err) { + http.Error(w, err.Error(), http.StatusNotFound) + return + } + + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusOK) + + if err = json.NewEncoder(w).Encode(events); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + +} diff --git a/backend/repos/query_test.go b/backend/repos/query_test.go index 9d37864..8a718f5 100644 --- a/backend/repos/query_test.go +++ b/backend/repos/query_test.go @@ -140,6 +140,8 @@ func TestUpdateQuery_Existing(t *testing.T) { func initRepo(t *testing.T) *QueryRepo { tmp := t.TempDir() dbPath := fmt.Sprintf("%s/test.db", tmp) + + fmt.Println("path ", dbPath) db, err := sqlx.Connect("sqlite3", dbPath) require.NoError(t, err) diff --git a/backend/repos/sensors.go b/backend/repos/sensors.go new file mode 100644 index 0000000..def0ca0 --- /dev/null +++ b/backend/repos/sensors.go @@ -0,0 +1,66 @@ +package repos + +import ( + "strings" + + "github.com/honeynet/ochi/backend/entities" + + "github.com/jmoiron/sqlx" + "github.com/jmoiron/sqlx/reflectx" +) + +type SensorRepo struct { + getSensorsByUser *sqlx.Stmt + addSensor *sqlx.NamedStmt +} + +func NewSensorRepo(db *sqlx.DB) (*SensorRepo, error) { + + r := &SensorRepo{} + db.Mapper = reflectx.NewMapperFunc("json", strings.ToLower) + _, err := db.Exec(`CREATE TABLE IF NOT EXISTS sensors( + id TEXT PRIMARY KEY NOT NULL + , ownerid TEXT NOT NULL + , name TEXT NOT NULL + + )`) + + if err != nil { + return nil, err + } + + r.getSensorsByUser, err = db.Preparex(` SELECT * sensors + WHERE + WHERE ownerid=? + `) + + if err != nil { + + return nil, err + } + + r.addSensor, err = db.PrepareNamed(` + INSERT INTO sensors (id , ownerid , name) VALUES (:id , :ownerid , :name) + `) + if err != nil { + return nil, err + } + + return r, nil +} + +func (r *SensorRepo) GetSensorsByOwnerId(ownerId string) ([]entities.Sensor, error) { + + ss := []entities.Sensor{} + + err := r.getSensorsByUser.Select(ownerId) + + return ss, err + +} + +func (r *SensorRepo) AddSensors(s entities.Sensor) error { + + r.addSensor.Exec() + +} diff --git a/backend/repos/sensors_test.go b/backend/repos/sensors_test.go new file mode 100644 index 0000000..ae66ba1 --- /dev/null +++ b/backend/repos/sensors_test.go @@ -0,0 +1,30 @@ +package repos + +import ( + "fmt" + "testing" + + "github.com/jmoiron/sqlx" + "github.com/stretchr/testify/require" +) + +func TestGetSesors(t *testing.T) { + +} + + +func initRepoForSensors(t *testing.T) *SensorRepo { + tmp := t.TempDir() + dbPath := fmt.Sprintf("%s/test.db", tmp) + + fmt.Println("path ", dbPath) + db, err := sqlx.Connect("sqlite3", dbPath) + require.NoError(t, err) + + // defer os.Remove("./querytest.db") + r, err := NewSensorRepo(db) + require.NoError(t, err) + require.NotNil(t, r) + return r +} + diff --git a/backend/routes.go b/backend/routes.go index 37707e9..79607d4 100644 --- a/backend/routes.go +++ b/backend/routes.go @@ -50,5 +50,8 @@ func newRouter(cs *server) (*httprouter.Router, error) { r.GET("/api/events", handlers.CorsMiddleware(handlers.BearerMiddleware(cs.getEventsHandler, os.Args[3]))) r.GET("/api/events/:id", handlers.CorsMiddleware(handlers.BearerMiddleware(cs.getEventByIDHandler, os.Args[3]))) + // sensor + r.GET("/sensors", handlers.CorsMiddleware(handlers.BearerMiddleware(cs.getSensorsByUser, os.Args[3]))) + return r, nil } diff --git a/backend/server.go b/backend/server.go index 468c825..9d16f04 100644 --- a/backend/server.go +++ b/backend/server.go @@ -40,10 +40,10 @@ type server struct { subscribers map[*subscriber]struct{} // the repositories - uRepo *repos.UserRepo - queryRepo *repos.QueryRepo - eventRepo *repos.EventRepo - + uRepo *repos.UserRepo + queryRepo *repos.QueryRepo + eventRepo *repos.EventRepo + sensorRepo *repos.SensorRepo // http client httpClient *http.Client @@ -85,6 +85,12 @@ func NewServer(fsys fs.FS) (*server, error) { log.Fatal(err) } + cs.sensorRepo, err = repos.NewSensorRepo(db) + + if err != nil { + log.Fatal(err) + } + cs.mux, err = newRouter(cs) if err != nil { return nil, err From c01f694e179b792454acb2de0ed932ff3a0dd5d4 Mon Sep 17 00:00:00 2001 From: Tushar kalsi <55044345+Tushar-kalsi@users.noreply.github.com> Date: Thu, 30 Nov 2023 00:58:41 +0530 Subject: [PATCH 7/9] FIX #92 , Added /sensor route for Get and POST request . Added /Sensor route as GET request to list all sensors stored by owner id . POST request for adding sensor under current user id as owner id . --- backend/entities/sensor.go | 2 +- backend/handlers.go | 29 +++++++++++++++++++++++++++++ backend/repos/sensors.go | 12 ++++++++++-- backend/routes.go | 1 + 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/backend/entities/sensor.go b/backend/entities/sensor.go index ac18b8d..7a121a1 100644 --- a/backend/entities/sensor.go +++ b/backend/entities/sensor.go @@ -3,5 +3,5 @@ package entities type Sensor struct { Id string `json:"id"` Name string `json:"name"` - OwnerId string `json:"ownerid"` + OwnerId string `json:"ownerid,omitempty"` } diff --git a/backend/handlers.go b/backend/handlers.go index 6f3cbf4..36f63ed 100644 --- a/backend/handlers.go +++ b/backend/handlers.go @@ -366,3 +366,32 @@ func (cs *server) getSensorsByUser(w http.ResponseWriter, r *http.Request, p htt } } + +func (cs *server) addSensor(w http.ResponseWriter, r *http.Request, p httprouter.Params){ + + + userId := userIDFromCtx(r.Context()) + + decoder := json.NewDecoder(r.Body) + defer r.Body.Close() + var sensor entities.Sensor + err := decoder.Decode(&sensor) + + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + + } + + err = cs.sensorRepo.AddSensors(sensor, userId) + + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + + } + + w.WriteHeader(http.StatusOK) + +} + diff --git a/backend/repos/sensors.go b/backend/repos/sensors.go index def0ca0..caab060 100644 --- a/backend/repos/sensors.go +++ b/backend/repos/sensors.go @@ -59,8 +59,16 @@ func (r *SensorRepo) GetSensorsByOwnerId(ownerId string) ([]entities.Sensor, err } -func (r *SensorRepo) AddSensors(s entities.Sensor) error { +func (r *SensorRepo) AddSensors(sensor entities.Sensor , userId string) error { - r.addSensor.Exec() + s:=entities.Sensor{Id: sensor.Id , OwnerId: userId, Name:sensor.Name} + + _, err:=r.addSensor.Exec(s) + if err != nil { + return err + } + + return nil + } diff --git a/backend/routes.go b/backend/routes.go index 79607d4..1da9ad8 100644 --- a/backend/routes.go +++ b/backend/routes.go @@ -52,6 +52,7 @@ func newRouter(cs *server) (*httprouter.Router, error) { // sensor r.GET("/sensors", handlers.CorsMiddleware(handlers.BearerMiddleware(cs.getSensorsByUser, os.Args[3]))) + r.POST("/sensors", handlers.CorsMiddleware(handlers.BearerMiddleware(cs.addSensor, os.Args[3]))) return r, nil } From eec66b9f6161d42b8c08cc9d5710f29298787107 Mon Sep 17 00:00:00 2001 From: Tushar kalsi <55044345+Tushar-kalsi@users.noreply.github.com> Date: Thu, 30 Nov 2023 01:01:24 +0530 Subject: [PATCH 8/9] FIX #92 Added /sensor route . --- backend/handlers.go | 6 ++---- backend/repos/query_test.go | 3 +-- backend/repos/sensors.go | 12 ++++++------ backend/repos/sensors_test.go | 6 ++---- 4 files changed, 11 insertions(+), 16 deletions(-) diff --git a/backend/handlers.go b/backend/handlers.go index 36f63ed..30c7e5b 100644 --- a/backend/handlers.go +++ b/backend/handlers.go @@ -367,11 +367,10 @@ func (cs *server) getSensorsByUser(w http.ResponseWriter, r *http.Request, p htt } -func (cs *server) addSensor(w http.ResponseWriter, r *http.Request, p httprouter.Params){ - +func (cs *server) addSensor(w http.ResponseWriter, r *http.Request, p httprouter.Params) { userId := userIDFromCtx(r.Context()) - + decoder := json.NewDecoder(r.Body) defer r.Body.Close() var sensor entities.Sensor @@ -394,4 +393,3 @@ func (cs *server) addSensor(w http.ResponseWriter, r *http.Request, p httprouter w.WriteHeader(http.StatusOK) } - diff --git a/backend/repos/query_test.go b/backend/repos/query_test.go index 8a718f5..054bdfc 100644 --- a/backend/repos/query_test.go +++ b/backend/repos/query_test.go @@ -140,8 +140,7 @@ func TestUpdateQuery_Existing(t *testing.T) { func initRepo(t *testing.T) *QueryRepo { tmp := t.TempDir() dbPath := fmt.Sprintf("%s/test.db", tmp) - - fmt.Println("path ", dbPath) + db, err := sqlx.Connect("sqlite3", dbPath) require.NoError(t, err) diff --git a/backend/repos/sensors.go b/backend/repos/sensors.go index caab060..bb416c2 100644 --- a/backend/repos/sensors.go +++ b/backend/repos/sensors.go @@ -59,16 +59,16 @@ func (r *SensorRepo) GetSensorsByOwnerId(ownerId string) ([]entities.Sensor, err } -func (r *SensorRepo) AddSensors(sensor entities.Sensor , userId string) error { +func (r *SensorRepo) AddSensors(sensor entities.Sensor, userId string) error { - s:=entities.Sensor{Id: sensor.Id , OwnerId: userId, Name:sensor.Name} + s := entities.Sensor{Id: sensor.Id, OwnerId: userId, Name: sensor.Name} + + _, err := r.addSensor.Exec(s) - _, err:=r.addSensor.Exec(s) - if err != nil { - return err + return err } - return nil + return nil } diff --git a/backend/repos/sensors_test.go b/backend/repos/sensors_test.go index ae66ba1..c165686 100644 --- a/backend/repos/sensors_test.go +++ b/backend/repos/sensors_test.go @@ -9,15 +9,14 @@ import ( ) func TestGetSesors(t *testing.T) { - -} +} func initRepoForSensors(t *testing.T) *SensorRepo { tmp := t.TempDir() dbPath := fmt.Sprintf("%s/test.db", tmp) + - fmt.Println("path ", dbPath) db, err := sqlx.Connect("sqlite3", dbPath) require.NoError(t, err) @@ -27,4 +26,3 @@ func initRepoForSensors(t *testing.T) *SensorRepo { require.NotNil(t, r) return r } - From 94d4c77f963d7015e5408e2559c8127ae5927872 Mon Sep 17 00:00:00 2001 From: Tushar-E <55044345+Tushar-kalsi@users.noreply.github.com> Date: Tue, 19 Dec 2023 01:21:40 +0530 Subject: [PATCH 9/9] Updated files for sensors --- backend/entities/sensor.go | 4 ++-- backend/handlers.go | 13 ++----------- backend/repos/sensors.go | 17 ++++++----------- 3 files changed, 10 insertions(+), 24 deletions(-) diff --git a/backend/entities/sensor.go b/backend/entities/sensor.go index 7a121a1..a6a0b43 100644 --- a/backend/entities/sensor.go +++ b/backend/entities/sensor.go @@ -1,7 +1,7 @@ package entities type Sensor struct { - Id string `json:"id"` + ID string `json:"id"` Name string `json:"name"` - OwnerId string `json:"ownerid,omitempty"` + User string `json:"user_id,omitempty"` } diff --git a/backend/handlers.go b/backend/handlers.go index 30c7e5b..09ec761 100644 --- a/backend/handlers.go +++ b/backend/handlers.go @@ -342,12 +342,9 @@ func (cs *server) getEventByIDHandler(w http.ResponseWriter, r *http.Request, p http.Error(w, err.Error(), http.StatusInternalServerError) } } - func (cs *server) getSensorsByUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) { - userId := userIDFromCtx(r.Context()) events, err := cs.sensorRepo.GetSensorsByOwnerId(userId) - if err != nil { if isNotFoundError(err) { http.Error(w, err.Error(), http.StatusNotFound) @@ -366,30 +363,24 @@ func (cs *server) getSensorsByUser(w http.ResponseWriter, r *http.Request, p htt } } - func (cs *server) addSensor(w http.ResponseWriter, r *http.Request, p httprouter.Params) { - userId := userIDFromCtx(r.Context()) - decoder := json.NewDecoder(r.Body) defer r.Body.Close() var sensor entities.Sensor err := decoder.Decode(&sensor) - if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return - } + sensor.User = userId - err = cs.sensorRepo.AddSensors(sensor, userId) + err = cs.sensorRepo.AddSensors(sensor) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return - } - w.WriteHeader(http.StatusOK) } diff --git a/backend/repos/sensors.go b/backend/repos/sensors.go index bb416c2..16722b8 100644 --- a/backend/repos/sensors.go +++ b/backend/repos/sensors.go @@ -20,8 +20,10 @@ func NewSensorRepo(db *sqlx.DB) (*SensorRepo, error) { db.Mapper = reflectx.NewMapperFunc("json", strings.ToLower) _, err := db.Exec(`CREATE TABLE IF NOT EXISTS sensors( id TEXT PRIMARY KEY NOT NULL - , ownerid TEXT NOT NULL + , user_id TEXT NOT NULL , name TEXT NOT NULL + , UNIQUE (user_id, name) + , FOREIGN KEY (user_id) REFERENCES users(id) )`) @@ -59,16 +61,9 @@ func (r *SensorRepo) GetSensorsByOwnerId(ownerId string) ([]entities.Sensor, err } -func (r *SensorRepo) AddSensors(sensor entities.Sensor, userId string) error { - - s := entities.Sensor{Id: sensor.Id, OwnerId: userId, Name: sensor.Name} +func (r *SensorRepo) AddSensors(sensor entities.Sensor) error { + s := entities.Sensor{ID: sensor.ID, User: sensor.User, Name: sensor.Name} _, err := r.addSensor.Exec(s) - - if err != nil { - return err - } - - return nil - + return err }