feat: a lot

i did a lot of work, and i also forgot to add commits regularly. I added the controller routes to create and delete controllers, improved error handling und improved the authentification process. I'm gonna add an websocket next and then I should be hopefully done with the foundations of this project. I may also add anviewControllers route which respons with every available controller
This commit is contained in:
Siesta
2025-07-20 18:31:38 +02:00
parent 25bd0cc0c8
commit 57592b4987
10 changed files with 138 additions and 63 deletions
+2 -2
View File
@@ -1,4 +1,4 @@
# Laterna # 🛋️ Laterna (Server)
## 🛜 API Documentation ## 🛜 API Documentation
@@ -42,7 +42,7 @@ Authorization: <token>
$ curl -X POST http://your-server.com/api/v1/controllers \ $ curl -X POST http://your-server.com/api/v1/controllers \
-H "Authorization: $TOKEN" -H "Authorization: $TOKEN"
``` ```
Respons with the newly assigned ID Response with the newly assigned ID. The ID will always be the next available one
#### Delete an controller #### Delete an controller
```bash ```bash
+1 -1
View File
@@ -31,7 +31,7 @@ func ConnectDB() {
func InitDB() { func InitDB() {
_, err := DB.Exec(` _, err := DB.Exec(`
CREATE TABLE IF NOT EXISTS controllers ( CREATE TABLE IF NOT EXISTS controllers (
id TEXT PRIMARY KEY, id INTEGER PRIMARY KEY,
token_hash TEXT, token_hash TEXT,
color TEXT, color TEXT,
updated_at DATETIME updated_at DATETIME
+22 -6
View File
@@ -9,15 +9,31 @@ import (
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
func CreateController(id int) string { func CreateController() (int64, error) {
token, _ := utils.GenerateToken() result, err := DB.Exec("INSERT INTO controllers (color, updated_at) VALUES (?, CURRENT_TIMESTAMP)", "#FFFFF")
hash, _ := utils.HashToken(token)
_, err := DB.Exec("INSERT INTO controllers (id, token_hash) VALUES (?, ?)", id, hash)
if err != nil { if err != nil {
logger.DBLogger.Fatalf("Error creating controller with ID %v: %s",id, err) logger.DBLogger.Printf("Error creating controller: %v", err)
return 0, err
} }
id, err := result.LastInsertId()
if err != nil {
logger.DBLogger.Printf("Error fetching controller ID: %v", err)
return 0, err
}
return id, nil
}
func CreateAdmin() string {
token, err := utils.GenerateToken()
if err != nil {
logger.DBLogger.Fatalf("Error generating admin token: %v", err)
}
token_hash, err := utils.HashToken(token)
if err != nil {
logger.DBLogger.Fatalf("Error hashing admin token: %v", err)
}
DB.Exec("INSERT INTO controllers (id, token_hash) VALUES (0, ?)", token_hash)
return token return token
} }
+3 -2
View File
@@ -12,10 +12,11 @@ import (
func StartHTTPServer() { func StartHTTPServer() {
router := http.NewServeMux() router := http.NewServeMux()
routes.RegisterRoutes(router) routes.RegisterColorRoutes(router)
routes.RegisterControllerRoutes(router)
if !db.ControllerExists(0) { if !db.ControllerExists(0) {
adminToken := db.CreateController(0) adminToken := db.CreateAdmin()
fmt.Println("IMPORTANT") fmt.Println("IMPORTANT")
fmt.Println("- - - - - - - - - - - - - - - - - - ") fmt.Println("- - - - - - - - - - - - - - - - - - ")
fmt.Println("ADMIN TOKEN:") fmt.Println("ADMIN TOKEN:")
+19
View File
@@ -0,0 +1,19 @@
package middleware
import (
"net/http"
"github.com/siestaw/laterna/server/cmd/internal/db"
"github.com/siestaw/laterna/server/cmd/utils"
)
func WithAdminAuth(handlerFunc http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if !db.IsAdmin(token) {
utils.HTTPResponseHandler(w, r, http.StatusUnauthorized, "Invalid token")
return
}
handlerFunc(w, r)
}
}
+9 -3
View File
@@ -1,6 +1,8 @@
package models package models
import "time" import (
"time"
)
type HTTPConfig struct { type HTTPConfig struct {
AdminToken string `json:"adminToken"` AdminToken string `json:"adminToken"`
@@ -15,10 +17,10 @@ type Config struct {
VerboseLogging bool `json:"verboseLogging"` VerboseLogging bool `json:"verboseLogging"`
} }
type HTTPError struct { type HTTPResponse struct {
Timestamp string `json:"timestamp"` Timestamp string `json:"timestamp"`
Status int `json:"status"` Status int `json:"status"`
Error string `json:"error"` Text string `json:"text"`
Message string `json:"message"` Message string `json:"message"`
Path string `json:"path"` Path string `json:"path"`
} }
@@ -32,3 +34,7 @@ type LampState struct {
type LampUpdateRequest struct { type LampUpdateRequest struct {
Color string `json:"color"` Color string `json:"color"`
} }
type ControllerRequests struct {
ID int `json:"ID"`
}
@@ -8,79 +8,78 @@ import (
"github.com/siestaw/laterna/server/cmd/internal/config" "github.com/siestaw/laterna/server/cmd/internal/config"
"github.com/siestaw/laterna/server/cmd/internal/db" "github.com/siestaw/laterna/server/cmd/internal/db"
"github.com/siestaw/laterna/server/cmd/internal/logger" "github.com/siestaw/laterna/server/cmd/internal/logger"
"github.com/siestaw/laterna/server/cmd/internal/middleware"
"github.com/siestaw/laterna/server/cmd/internal/models" "github.com/siestaw/laterna/server/cmd/internal/models"
"github.com/siestaw/laterna/server/cmd/utils" "github.com/siestaw/laterna/server/cmd/utils"
) )
func RegisterRoutes(mux *http.ServeMux) { func RegisterColorRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/v1/id/{ID}", getCurrent) mux.HandleFunc("GET /api/v1/colors/{ID}", middleware.WithAdminAuth(getCurrent))
mux.HandleFunc("PUT /api/v1/id/{ID}", setCurrent) mux.HandleFunc("PUT /api/v1/colors/{ID}", middleware.WithAdminAuth(setCurrent))
// mux.HandleFunc("WS /api/v1/ws/colors/{ID}", setCurrentWebsocket)
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) { func getCurrent(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization") defer r.Body.Close()
if !db.IsAdmin(token) {
utils.HTTPErrorHandling(w, r, http.StatusUnauthorized, "Invalid token")
return
}
idStr := r.PathValue("ID") idStr := r.PathValue("ID")
id, err := utils.IDtoInt(idStr) id, err := utils.IDtoInt(idStr)
if err != nil { if err != nil {
utils.HTTPErrorHandling(w, r, http.StatusBadRequest, err.Error()) utils.HTTPResponseHandler(w, r, http.StatusBadRequest, err.Error())
return
}
if !db.ControllerExists(id) {
utils.HTTPResponseHandler(w, r, http.StatusBadRequest, "Lamp does not exist")
return return
} }
state, err := db.ViewColor(id) state, err := db.ViewColor(id)
if err != nil { if err != nil {
utils.HTTPErrorHandling(w, r, http.StatusBadRequest, "Lamp not found") utils.HTTPResponseHandler(w, r, http.StatusBadRequest, err.Error())
return return
} }
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(state) json.NewEncoder(w).Encode(state)
defer r.Body.Close()
} }
func setCurrent(w http.ResponseWriter, r *http.Request) { func setCurrent(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization") defer r.Body.Close()
if !db.IsAdmin(token) {
utils.HTTPErrorHandling(w, r, http.StatusUnauthorized, "Invalid token")
return
}
idStr := r.PathValue("ID") idStr := r.PathValue("ID")
id, err := utils.IDtoInt(idStr) id, err := utils.IDtoInt(idStr)
if err != nil { if err != nil {
utils.HTTPErrorHandling(w, r, http.StatusBadRequest, err.Error()) utils.HTTPResponseHandler(w, r, http.StatusBadRequest, err.Error())
return return
} }
if !db.ControllerExists(id) {
utils.HTTPResponseHandler(w, r, http.StatusBadRequest, "Lamp does not exist")
return
}
currentState, err := db.ViewColor(id) currentState, err := db.ViewColor(id)
if err != nil { if err != nil {
utils.HTTPErrorHandling(w, r, http.StatusInternalServerError, "Failed to get current lamp color") utils.HTTPResponseHandler(w, r, http.StatusInternalServerError, "Failed to get current lamp color")
return return
} }
if time.Since(currentState.UpdatedAt).Seconds() < config.AppConfig.HTTP.Cooldown { if time.Since(currentState.UpdatedAt).Seconds() < config.AppConfig.HTTP.Cooldown {
utils.HTTPErrorHandling(w, r, http.StatusTooManyRequests, "Slow down!") utils.HTTPResponseHandler(w, r, http.StatusTooManyRequests, "Slow down!")
return return
} }
var req models.LampUpdateRequest var req models.LampUpdateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil { if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
logger.HTTPLogger.Print(err) logger.HTTPLogger.Print(err)
utils.HTTPErrorHandling(w, r, http.StatusBadRequest, "Invalid JSON") utils.HTTPResponseHandler(w, r, http.StatusBadRequest, "Invalid JSON")
return return
} }
err = db.SetColor(id, req.Color) err = db.SetColor(id, req.Color)
if err != nil { if err != nil {
logger.HTTPLogger.Printf("Could not update lamp %d: %s", id, err) logger.HTTPLogger.Printf("Could not update lamp %d: %s", id, err)
utils.HTTPErrorHandling(w, r, http.StatusInternalServerError, err.Error()) utils.HTTPResponseHandler(w, r, http.StatusInternalServerError, err.Error())
return return
} }
@@ -90,17 +89,5 @@ func setCurrent(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(updatedState) json.NewEncoder(w).Encode(updatedState)
defer r.Body.Close() logger.HTTPLogger.Printf("Lamp %d updated to color %s", id, req.Color)
}
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
} }
+47
View File
@@ -0,0 +1,47 @@
package routes
import (
"encoding/json"
"net/http"
"github.com/siestaw/laterna/server/cmd/internal/db"
"github.com/siestaw/laterna/server/cmd/internal/logger"
"github.com/siestaw/laterna/server/cmd/internal/middleware"
"github.com/siestaw/laterna/server/cmd/internal/models"
"github.com/siestaw/laterna/server/cmd/utils"
)
func RegisterControllerRoutes(mux *http.ServeMux) {
mux.HandleFunc("POST /api/v1/controllers", middleware.WithAdminAuth(createController))
mux.HandleFunc("DELETE /api/v1/controllers", middleware.WithAdminAuth(deleteController))
}
func createController(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
ID, err := db.CreateController()
if err != nil {
utils.HTTPResponseHandler(w, r, http.StatusInternalServerError, "An error occured. Check the server logs for more information")
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]int64{"ID": ID})
}
func deleteController(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var req models.ControllerRequests
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
logger.HTTPLogger.Print(err)
utils.HTTPResponseHandler(w, r, http.StatusBadRequest, "Invalid JSON")
return
}
if !db.ControllerExists(req.ID) || req.ID <= 0 {
utils.HTTPResponseHandler(w, r, http.StatusBadRequest,"Invalid ID")
return
}
if db.DeleteController(req.ID) != nil {
utils.HTTPResponseHandler(w, r, http.StatusInternalServerError,"An error occured. Check the server logs for more information")
return
}
utils.HTTPResponseHandler(w, r, http.StatusOK, "Success")
}
+3 -4
View File
@@ -31,7 +31,6 @@ func IsValidHexColor(color string) bool {
return match return match
} }
func GenerateToken() (string, error) { func GenerateToken() (string, error) {
bytes := make([]byte, 32) bytes := make([]byte, 32)
if _, err := rand.Read(bytes); err != nil { if _, err := rand.Read(bytes); err != nil {
@@ -50,12 +49,12 @@ func ValidateToken(providedToken string, storedHash string) bool {
return err == nil return err == nil
} }
func HTTPErrorHandling(w http.ResponseWriter, r *http.Request, status int, message string) { func HTTPResponseHandler(w http.ResponseWriter, r *http.Request, status int, message string) {
timestamp := time.Now().Format("2006-01-02_15-04-05") timestamp := time.Now().Format("2006-01-02_15-04-05")
errResp := models.HTTPError{ errResp := models.HTTPResponse{
Timestamp: timestamp, Timestamp: timestamp,
Status: status, Status: status,
Error: http.StatusText(status), Text: http.StatusText(status),
Message: message, Message: message,
Path: r.URL.Path, Path: r.URL.Path,
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"fileLogging": false, "fileLogging": false,
"verboseLogging": true, // // not fully implemented yet "verboseLogging": true,
"http": { "http": {
"port": 8080, "port": 8080,
"cooldown": 5 "cooldown": 5