diff --git a/cmd/internal/db/connection.go b/cmd/internal/db/connection.go index 94c8802..44a45f1 100644 --- a/cmd/internal/db/connection.go +++ b/cmd/internal/db/connection.go @@ -24,17 +24,17 @@ func ConnectDB() { flag.Parse() if *resetAdmin { - ResetAdmin() + DeleteController(0) } } func InitDB() { - // Legacy purposes, DELETE _, err := DB.Exec(` - CREATE TABLE IF NOT EXISTS lamp_state ( + CREATE TABLE IF NOT EXISTS controllers ( id TEXT PRIMARY KEY, - color TEXT NOT NULL, - updated_at DATETIME NOT NULL + token_hash TEXT, + color TEXT, + updated_at DATETIME ); `) @@ -42,23 +42,4 @@ func InitDB() { logger.DBLogger.Fatalf("An error occured while initializing the database: %v", err) } - _, err = DB.Exec(` - CREATE TABLE IF NOT EXISTS controllers ( - id INTEGER PRIMARY KEY, - token_hash TEXT NOT NULL, - color TEXT, - updated_at DATETIME - );`) - if err != nil { - logger.DBLogger.Fatalf("An error occured while initializing the database: %v", err) - } - - _, err = DB.Exec(` - CREATE TABLE IF NOT EXISTS permissions ( - controller_id INTEGER, - target_id INTEGER - );`) - if err != nil { - logger.DBLogger.Fatalf("An error occured while initializing the database: %v", err) - } -} +} \ No newline at end of file diff --git a/cmd/internal/db/queries.go b/cmd/internal/db/queries.go index c1dc28e..1505cff 100644 --- a/cmd/internal/db/queries.go +++ b/cmd/internal/db/queries.go @@ -9,46 +9,25 @@ import ( "golang.org/x/crypto/bcrypt" ) -func CreateController(target int) (string, int, error) { +func CreateController(id int) string { token, _ := utils.GenerateToken() hash, _ := utils.HashToken(token) - var maxID int - stmt := DB.QueryRow("SELECT COALESCE(MAX(id), 0) FROM controllers") - stmt.Scan(&maxID) - id := maxID + 1 - - _, err := DB.Exec("INSERT INTO controllers VALUES (?, ?, '#FFFFFF', CURRENT_TIMESTAMP)", id, hash) + _, err := DB.Exec("INSERT INTO controllers (id, token_hash) VALUES (?, ?)", id, hash) if err != nil { - logger.DBLogger.Printf("Failed to create a new controller: %v", err) - return "", id, err - } - - _, err = DB.Exec("INSERT INTO permissions VALUES (?, ?) ", id, target) - if err != nil { - logger.DBLogger.Printf("Failed to set permissions for %d: %v", id, err) - return token, id, err - } - return token, id, nil -} - -func CreateAdmin() string { - token, _ := utils.GenerateToken() - hash, _ := utils.HashToken(token) - - _, err := DB.Exec("INSERT INTO controllers (id, token_hash) VALUES (0, ?)", hash) - if err != nil { - logger.DBLogger.Fatalf("Error creating admin user: %s", err) + logger.DBLogger.Fatalf("Error creating controller with ID %v: %s",id, err) } return token } -func ResetAdmin() { - _, err := DB.Exec("DELETE FROM controllers WHERE id = 0") +func DeleteController(id int) error { + _, err := DB.Exec("DELETE FROM controllers WHERE id = ?", id) if err != nil { - logger.DBLogger.Printf("An error occured while resetting the admin account: %s", err) + logger.DBLogger.Printf("An error occured while deleting the controller %v: %s", id, err) + return err } + return nil } func IsAdmin(token string) bool { @@ -76,7 +55,7 @@ func ControllerExists(id int) bool { } func ViewColor(id int) (*models.LampState, error) { - row := DB.QueryRow("SELECT * FROM lamp_state WHERE id = ?", id) + row := DB.QueryRow("SELECT id, color, updated_at FROM controllers WHERE id = ?", id) var state models.LampState err := row.Scan(&state.ID, &state.Color, &state.UpdatedAt) @@ -101,7 +80,7 @@ func SetColor(id int, color string) error { return nil } - _, err = DB.Exec("UPDATE lamp_state SET color = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", color, id) + _, err = DB.Exec("UPDATE controllers SET color = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", color, id) if err != nil { logger.DBLogger.Printf("Failed to update lamp %d: %v", id, err) return err diff --git a/cmd/internal/http/server.go b/cmd/internal/http/server.go index e37ceb0..6fa59d8 100644 --- a/cmd/internal/http/server.go +++ b/cmd/internal/http/server.go @@ -12,11 +12,10 @@ import ( func StartHTTPServer() { router := http.NewServeMux() - routes.RegisterUserRoutes(router) - routes.RegisterAdminRoutes(router) + routes.RegisterRoutes(router) if !db.ControllerExists(0) { - adminToken := db.CreateAdmin() + adminToken := db.CreateController(0) fmt.Println("IMPORTANT") fmt.Println("- - - - - - - - - - - - - - - - - - ") fmt.Println("ADMIN TOKEN:") diff --git a/cmd/internal/models/models.go b/cmd/internal/models/models.go index d470586..5229f06 100644 --- a/cmd/internal/models/models.go +++ b/cmd/internal/models/models.go @@ -8,6 +8,7 @@ type HTTPConfig struct { Cooldown float64 `json:"cooldown"` } + type Config struct { HTTP HTTPConfig `json:"http"` FileLogging bool `json:"fileLogging"` diff --git a/cmd/internal/routes/admin.go b/cmd/internal/routes/admin.go deleted file mode 100644 index 0396c10..0000000 --- a/cmd/internal/routes/admin.go +++ /dev/null @@ -1,21 +0,0 @@ -package routes - -import ( - "net/http" - - "github.com/siestaw/laterna/server/cmd/internal/db" - "github.com/siestaw/laterna/server/cmd/utils" -) - -func RegisterAdminRoutes(mux *http.ServeMux) { - mux.HandleFunc("POST /api/v1/admin/controllers", createController) -} - -func createController(w http.ResponseWriter, r *http.Request) { - auth := r.Header.Get("Authorization") - if !db.IsAdmin(auth) { - utils.HTTPErrorHandling(w, r, http.StatusUnauthorized, "Invalid token") - return - } - -} diff --git a/cmd/internal/routes/user.go b/cmd/internal/routes/routes.go similarity index 73% rename from cmd/internal/routes/user.go rename to cmd/internal/routes/routes.go index 7a319cd..1d83026 100644 --- a/cmd/internal/routes/user.go +++ b/cmd/internal/routes/routes.go @@ -12,12 +12,22 @@ import ( "github.com/siestaw/laterna/server/cmd/utils" ) -func RegisterUserRoutes(mux *http.ServeMux) { +func RegisterRoutes(mux *http.ServeMux) { mux.HandleFunc("GET /api/v1/id/{ID}", getCurrent) mux.HandleFunc("PUT /api/v1/id/{ID}", setCurrent) + + mux.HandleFunc("GET /api/v1/controllers", getControllers) + mux.HandleFunc("PUT /api/v1/controllers", setControllers) + mux.HandleFunc("DELETE /api/v1/controllers/{id}", deleteController) } func getCurrent(w http.ResponseWriter, r *http.Request) { + token := r.Header.Get("Authorization") + if !db.IsAdmin(token) { + utils.HTTPErrorHandling(w, r, http.StatusUnauthorized, "Invalid token") + return + } + idStr := r.PathValue("ID") id, err := utils.IDtoInt(idStr) if err != nil { @@ -37,6 +47,12 @@ func getCurrent(w http.ResponseWriter, r *http.Request) { } func setCurrent(w http.ResponseWriter, r *http.Request) { + token := r.Header.Get("Authorization") + if !db.IsAdmin(token) { + utils.HTTPErrorHandling(w, r, http.StatusUnauthorized, "Invalid token") + return + } + idStr := r.PathValue("ID") id, err := utils.IDtoInt(idStr) if err != nil { @@ -76,3 +92,15 @@ func setCurrent(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(updatedState) defer r.Body.Close() } + +func getControllers(w http.ResponseWriter, r *http.Request) { + return +} + +func setControllers(w http.ResponseWriter, r *http.Request) { + return +} + +func deleteController(w http.ResponseWriter, r *http.Request) { + return +} \ No newline at end of file diff --git a/cmd/utils/utils.go b/cmd/utils/utils.go index 03e14b0..7f6d580 100644 --- a/cmd/utils/utils.go +++ b/cmd/utils/utils.go @@ -19,8 +19,8 @@ func IDtoInt(id string) (int, error) { if err != nil { return 0, errors.New("invalid ID format") } - if idInt < 0 { - return 0, errors.New("ID must not be negative") + if idInt <= 0 { + return 0, errors.New("invalid ID") } return idInt, nil } @@ -31,6 +31,7 @@ func IsValidHexColor(color string) bool { return match } + func GenerateToken() (string, error) { bytes := make([]byte, 32) if _, err := rand.Read(bytes); err != nil { diff --git a/config.json.example b/config.json.example index a8e3e70..46dbbcb 100644 --- a/config.json.example +++ b/config.json.example @@ -1,9 +1,8 @@ { "fileLogging": false, - "verboseLogging": true, + "verboseLogging": true, // // not fully implemented yet "http": { - "adminToken": "", "port": 8080, - "cooldown": 5, + "cooldown": 5 } } \ No newline at end of file