From 9cae9c1d2a0b4f7fa72f3075541b9ffafe1a7275 Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Fri, 15 Mar 2024 18:49:43 -0400 Subject: Add routes for preference, clean up and add types --- api/internal/controllers/auth.go | 18 ++++++---- api/internal/controllers/preferences.go | 45 +++++++++++++++++++++++++ api/internal/controllers/user.go | 59 ++++++++++++++++++++++++++++++--- api/internal/middleware/middleware.go | 7 ++-- api/internal/models/auth.go | 2 +- api/internal/models/preferences.go | 8 ++--- api/internal/models/statistics.go | 2 +- api/internal/models/user.go | 2 +- api/internal/router/router.go | 5 +-- 9 files changed, 125 insertions(+), 23 deletions(-) create mode 100644 api/internal/controllers/preferences.go (limited to 'api/internal') diff --git a/api/internal/controllers/auth.go b/api/internal/controllers/auth.go index 58653d0..ab2fbbb 100644 --- a/api/internal/controllers/auth.go +++ b/api/internal/controllers/auth.go @@ -38,23 +38,27 @@ func AuthHandler (c *gin.Context) { var user models.User var preference models.Preference - var size models.Size - row := db.QueryRow("SELECT name, uuid, password, color, size, unit FROM Users u INNER JOIN Preferences p ON p.user_id = u.id INNER JOIN Sizes s ON p.size_id = s.id WHERE u.name = ?", username) - if err := row.Scan(&user.Name, &user.UUID, &user.Password, &preference.Color, &size.Size, &size.Unit); err != nil { + row := db.QueryRow("SELECT id as 'id', name, uuid, password FROM Users WHERE name = ?", username) + if err := row.Scan(&user.ID, &user.Name, &user.UUID, &user.Password); err != nil { if errors.Is(err, sql.ErrNoRows) { - c.AbortWithStatus(http.StatusUnauthorized) + c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) return } } + row = db.QueryRow("SELECT id, color, size_id, user_id FROM Preferences where user_id = ?", user.ID) + if err := row.Scan(&preference.ID, &preference.Color, &preference.SizeID, &preference.UserID); err != nil { + if errors.Is(err, sql.ErrNoRows) { + c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) + } + } + if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { - c.AbortWithStatus(http.StatusUnauthorized) + c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()}) return } - preference.Size = size - // Generate a simple API token apiToken := generateToken() c.JSON(http.StatusOK, gin.H{"token": apiToken, "user": user, "preferences": preference}) diff --git a/api/internal/controllers/preferences.go b/api/internal/controllers/preferences.go new file mode 100644 index 0000000..a1bcf4f --- /dev/null +++ b/api/internal/controllers/preferences.go @@ -0,0 +1,45 @@ +package controllers + +import ( + "github.com/gin-gonic/gin" + "net/http" + "database/sql" + "water/api/internal/database" + "water/api/internal/models" +) + +func GetSizes(c *gin.Context) { + db := database.EstablishDBConnection() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } + }(db) + + rows, err := db.Query("SELECT id, size, unit FROM Sizes") + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + defer func(rows *sql.Rows) { + err := rows.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(rows) + + var data []models.Size + + for rows.Next() { + var size models.Size + if err := rows.Scan(&size.ID, &size.Size, &size.Unit); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + data = append(data, size) + } + + c.JSON(http.StatusOK, data) +} diff --git a/api/internal/controllers/user.go b/api/internal/controllers/user.go index 76dedc8..dbb09cf 100644 --- a/api/internal/controllers/user.go +++ b/api/internal/controllers/user.go @@ -1,17 +1,68 @@ package controllers import ( - "github.com/gin-gonic/gin" + "database/sql" + "errors" + "log" "net/http" + "water/api/internal/database" + "water/api/internal/models" + + "github.com/gin-gonic/gin" ) func GetUser(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "User found"}) } func GetUserPreferences(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"message": "Preferences fetched successfully"}) + db := database.EstablishDBConnection() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(db) + + var preference models.Preference + + row := db.QueryRow("SELECT id, user_id, color, size_id FROM Preferences WHERE user_id = ?", c.Param("id")) + if err := row.Scan(&preference.ID, &preference.UserID, &preference.Color, &preference.SizeID); err != nil { + if errors.Is(err, sql.ErrNoRows) { + c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) + return + } else { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + } + + c.JSON(http.StatusOK, preference) } func UpdateUserPreferences(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"message": "Preferences updated successfully"}) -} \ No newline at end of file + db := database.EstablishDBConnection() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(db) + + var newPreferences models.Preference + if err := c.BindJSON(&newPreferences); err != nil { + c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()}) + return + } + + log.Printf("newPreferences: %v", newPreferences) + + _, err := db.Exec("UPDATE Preferences SET color = ?, size_id = ? WHERE id = ?", newPreferences.Color, newPreferences.SizeID, newPreferences.ID) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.Status(http.StatusNoContent) +} diff --git a/api/internal/middleware/middleware.go b/api/internal/middleware/middleware.go index 819f1e5..aa27fb8 100644 --- a/api/internal/middleware/middleware.go +++ b/api/internal/middleware/middleware.go @@ -2,10 +2,11 @@ package middleware import ( "errors" - "github.com/gin-gonic/gin" "log" "net/http" "strings" + + "github.com/gin-gonic/gin" ) func TokenRequired() gin.HandlerFunc { @@ -27,7 +28,7 @@ func CORSMiddleware() gin.HandlerFunc { c.Writer.Header().Set("Access-Control-Allow-Origin", "*") c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With") - c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT") + c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, PATCH") if c.Request.Method == "OPTIONS" { log.Println(c.Request.Header) @@ -52,4 +53,4 @@ func checkForTokenInContext(c *gin.Context) (string, error) { } return parts[1], nil -} \ No newline at end of file +} diff --git a/api/internal/models/auth.go b/api/internal/models/auth.go index 41344d5..fa7dbe4 100644 --- a/api/internal/models/auth.go +++ b/api/internal/models/auth.go @@ -3,7 +3,7 @@ package models import "time" type Token struct { - ID int64 `json:"-"` + ID int64 `json:"id"` UserID int64 `json:"user_id"` Token string `json:"token"` CreatedAt time.Time `json:"created_at"` diff --git a/api/internal/models/preferences.go b/api/internal/models/preferences.go index cbbd47c..8022099 100644 --- a/api/internal/models/preferences.go +++ b/api/internal/models/preferences.go @@ -1,14 +1,14 @@ package models type Preference struct { - ID int64 `json:"-"` + ID int64 `json:"id"` Color string `json:"color"` - UserID int64 `json:"-"` - Size Size `json:"size"` + UserID int64 `json:"user_id"` + SizeID int64 `json:"size_id"` } type Size struct { - ID int64 `json:"-"` + ID int64 `json:"id"` Size int64 `json:"size"` Unit string `json:"unit"` } diff --git a/api/internal/models/statistics.go b/api/internal/models/statistics.go index 457e6a0..7dceb3a 100644 --- a/api/internal/models/statistics.go +++ b/api/internal/models/statistics.go @@ -3,7 +3,7 @@ package models import "time" type Statistic struct { - ID int64 `json:"-"` + ID int64 `json:"id"` Date time.Time `json:"date"` User User `json:"user"` Quantity int `json:"quantity"` diff --git a/api/internal/models/user.go b/api/internal/models/user.go index 2a3e6fd..ca5daa4 100644 --- a/api/internal/models/user.go +++ b/api/internal/models/user.go @@ -3,7 +3,7 @@ package models import "github.com/google/uuid" type User struct { - ID int64 `json:"-"` + ID int64 `json:"id"` Name string `json:"name"` UUID uuid.UUID `json:"uuid"` Password string `json:"-"` diff --git a/api/internal/router/router.go b/api/internal/router/router.go index adf96d0..3c86b8c 100644 --- a/api/internal/router/router.go +++ b/api/internal/router/router.go @@ -17,13 +17,14 @@ func SetupRouter() *gin.Engine { api := r.Group("api/v1") api.POST("/auth", controllers.AuthHandler) + api.GET("/sizes", middleware.TokenRequired(), controllers.GetSizes) + api.PATCH("/user/preferences", controllers.UpdateUserPreferences) - user := api.Group("/user/:uuid") + user := api.Group("/user/:id") user.Use(middleware.TokenRequired()) { user.GET("", controllers.GetUser) user.GET("preferences", controllers.GetUserPreferences) - user.PATCH("preferences", controllers.UpdateUserPreferences) } stats := api.Group("/stats") -- cgit v1.1