Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #92 , Added /Sensor route for GET , POST request to list all sensors . #102

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
7 changes: 7 additions & 0 deletions backend/entities/sensor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package entities

type Sensor struct {
ID string `json:"id"`
Name string `json:"name"`
User string `json:"user_id,omitempty"`
}
43 changes: 42 additions & 1 deletion backend/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"os"

"github.com/honeynet/ochi/backend/entities"

"github.com/julienschmidt/httprouter"
"google.golang.org/api/idtoken"
)
Expand Down Expand Up @@ -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)

}
1 change: 1 addition & 0 deletions backend/repos/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
69 changes: 69 additions & 0 deletions backend/repos/sensors.go
Original file line number Diff line number Diff line change
@@ -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
Tushar-kalsi marked this conversation as resolved.
Show resolved Hide resolved
, 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
}
28 changes: 28 additions & 0 deletions backend/repos/sensors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package repos

import (
"fmt"
"testing"

"github.com/jmoiron/sqlx"
"github.com/stretchr/testify/require"
)

func TestGetSesors(t *testing.T) {

}
Comment on lines +11 to +13
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

implement tests


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
}
4 changes: 4 additions & 0 deletions backend/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
14 changes: 10 additions & 4 deletions backend/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down