diff --git a/backend/entities/sensor.go b/backend/entities/sensor.go new file mode 100644 index 0000000..a6a0b43 --- /dev/null +++ b/backend/entities/sensor.go @@ -0,0 +1,7 @@ +package entities + +type Sensor struct { + ID string `json:"id"` + Name string `json:"name"` + User string `json:"user_id,omitempty"` +} diff --git a/backend/handlers.go b/backend/handlers.go index d2acfc8..09ec761 100644 --- a/backend/handlers.go +++ b/backend/handlers.go @@ -8,7 +8,6 @@ import ( "os" "github.com/honeynet/ochi/backend/entities" - "github.com/julienschmidt/httprouter" "google.golang.org/api/idtoken" ) @@ -343,3 +342,45 @@ 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 + } + +} +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) + + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) + +} diff --git a/backend/repos/query_test.go b/backend/repos/query_test.go index 9d37864..054bdfc 100644 --- a/backend/repos/query_test.go +++ b/backend/repos/query_test.go @@ -140,6 +140,7 @@ func TestUpdateQuery_Existing(t *testing.T) { func initRepo(t *testing.T) *QueryRepo { tmp := t.TempDir() dbPath := fmt.Sprintf("%s/test.db", tmp) + 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..16722b8 --- /dev/null +++ b/backend/repos/sensors.go @@ -0,0 +1,69 @@ +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 + , user_id TEXT NOT NULL + , name TEXT NOT NULL + , UNIQUE (user_id, name) + , FOREIGN KEY (user_id) REFERENCES users(id) + + )`) + + 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(sensor entities.Sensor) error { + + s := entities.Sensor{ID: sensor.ID, User: sensor.User, Name: sensor.Name} + _, err := r.addSensor.Exec(s) + return err +} diff --git a/backend/repos/sensors_test.go b/backend/repos/sensors_test.go new file mode 100644 index 0000000..c165686 --- /dev/null +++ b/backend/repos/sensors_test.go @@ -0,0 +1,28 @@ +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) + + + 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..1da9ad8 100644 --- a/backend/routes.go +++ b/backend/routes.go @@ -50,5 +50,9 @@ 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]))) + r.POST("/sensors", handlers.CorsMiddleware(handlers.BearerMiddleware(cs.addSensor, 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