From 6651daca670664f3de8af9c7bcb74b1e7c6c6be9 Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Thu, 7 Mar 2024 19:16:07 -0500 Subject: Add CORS middleware and authentication middleware to the API server. The `setupRouter` function in `main.go` now includes a CORS middleware and a token authentication middleware. The CORS middleware allows cross-origin resource sharing by setting the appropriate response headers. The token authentication middleware checks for the presence of an `Authorization` header with a valid bearer token. If the token is missing or invalid, an unauthorized response is returned. In addition to these changes, a new test file `main_test.go` has been added to test the `/api/v1/auth` route. This test suite includes two test cases: one for successful authentication and one for failed authentication. Update go.mod to include new dependencies. The `go.mod` file has been modified to include two new dependencies: `github.com/spf13/viper` and `github.com/stretchr/testify`. Ignore go.sum changes. Ignore changes in the `go.sum` file, as they only include updates to existing dependencies. --- api/internal/controllers/auth.go | 66 +++++++++++++++ api/internal/controllers/stats.go | 164 +++++++++++++++++++++++++++++++++++++ api/internal/controllers/user.go | 17 ++++ api/internal/database/database.go | 22 +++++ api/internal/models/auth.go | 11 +++ api/internal/models/preferences.go | 14 ++++ api/internal/models/statistics.go | 26 ++++++ api/internal/models/user.go | 10 +++ 8 files changed, 330 insertions(+) create mode 100644 api/internal/controllers/auth.go create mode 100644 api/internal/controllers/stats.go create mode 100644 api/internal/controllers/user.go create mode 100644 api/internal/database/database.go create mode 100644 api/internal/models/auth.go create mode 100644 api/internal/models/preferences.go create mode 100644 api/internal/models/statistics.go create mode 100644 api/internal/models/user.go (limited to 'api/internal') diff --git a/api/internal/controllers/auth.go b/api/internal/controllers/auth.go new file mode 100644 index 0000000..744a884 --- /dev/null +++ b/api/internal/controllers/auth.go @@ -0,0 +1,66 @@ +package controllers + +import ( + "encoding/base64" + "net/http" + "github.com/gin-gonic/gin" + "water/api/database" + "errors" + "crypto/rand" + "database/sql" + + "water/api/models" + _ "github.com/mattn/go-sqlite3" + "golang.org/x/crypto/bcrypt" +) + +func AuthHandler (c *gin.Context) { + username, password, ok := c.Request.BasicAuth() + if !ok { + c.Header("WWW-Authenticate", `Basic realm="Please enter your username and password."`) + c.AbortWithStatus(http.StatusUnauthorized) + return + } + + 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 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 { + if errors.Is(err, sql.ErrNoRows) { + c.AbortWithStatus(http.StatusUnauthorized) + return + } + } + + if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { + c.AbortWithStatus(http.StatusUnauthorized) + return + } + + preference.Size = size + + // Generate a simple API token + apiToken := generateToken() + c.JSON(http.StatusOK, gin.H{"token": apiToken, "user": user, "preferences": preference}) +} + +// generatToken will g +func generateToken() string { + token := make([]byte, 32) + _, err := rand.Read(token) + if err != nil { + return "" + } + return base64.StdEncoding.EncodeToString(token) +} \ No newline at end of file diff --git a/api/internal/controllers/stats.go b/api/internal/controllers/stats.go new file mode 100644 index 0000000..9808ace --- /dev/null +++ b/api/internal/controllers/stats.go @@ -0,0 +1,164 @@ +package controllers + +import ( + "database/sql" + "github.com/gin-gonic/gin" + "net/http" + "water/api/database" + "water/api/models" +) + +func GetAllStatistics(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()}) + return + } + }(db) + + rows, err := db.Query("SELECT s.date, s.quantity, u.uuid, u.name FROM Statistics s INNER JOIN Users u ON u.id = s.user_id") + 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.Statistic + + for rows.Next() { + var stat models.Statistic + var user models.User + if err := rows.Scan(&stat.Date, &stat.Quantity, &user.UUID, &user.Name); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + stat.User = user + data = append(data, stat) + } + + c.JSON(http.StatusOK, data) +} + +func PostNewStatistic(c *gin.Context) { + var stat models.StatisticPost + + if err := c.BindJSON(&stat); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + 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) + + result, err := db.Exec("INSERT INTO statistics (date, user_id, quantity) values (?, ?, ?)", stat.Date, stat.UserID, stat.Quantity) + + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + } + + id, err := result.LastInsertId() + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + } + + c.JSON(http.StatusCreated, gin.H{"status": "created", "id": id}) +} + +func GetWeeklyStatistics (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()}) + return + } + }(db) + + rows, err := db.Query("SELECT date, total FROM `WeeklyStatisticsView`") + 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.WeeklyStatistic + for rows.Next() { + var weeklyStat models.WeeklyStatistic + if err := rows.Scan(&weeklyStat.Date, &weeklyStat.Total); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } + data = append(data, weeklyStat) + } + + c.JSON(http.StatusOK, data) +} + +func GetDailyUserStatistics(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()}) + return + } + }(db) + + rows, err := db.Query("SELECT name, total FROM DailyUserStatistics") + + 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.DailyUserTotals + for rows.Next() { + var stat models.DailyUserTotals + if err := rows.Scan(&stat.Name, &stat.Total); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + data = append(data, stat) + } + + c.JSON(http.StatusOK, data) + +} + +func GetUserStatistics(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"status": "ok", "uuid": c.Param("uuid")}) +} + +func UpdateUserStatistic(c *gin.Context) { + c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) +} + +func DeleteUserStatistic(c *gin.Context) { + c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) +} diff --git a/api/internal/controllers/user.go b/api/internal/controllers/user.go new file mode 100644 index 0000000..1f3f813 --- /dev/null +++ b/api/internal/controllers/user.go @@ -0,0 +1,17 @@ +package controllers + +import ( + "net/http" + "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"}) +} + +func UpdateUserPreferences(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"message": "Preferences updated successfully"}) +} \ No newline at end of file diff --git a/api/internal/database/database.go b/api/internal/database/database.go new file mode 100644 index 0000000..e313af5 --- /dev/null +++ b/api/internal/database/database.go @@ -0,0 +1,22 @@ +package database + +import ( + "database/sql" + _ "github.com/mattn/go-sqlite3" + "log" +) + +func SetupDatabase() { + _, err := sql.Open("sqlite3", "water.db") + if err != nil { + log.Fatal(err) + } +} + +func EstablishDBConnection() *sql.DB { + db, err := sql.Open("sqlite3", "../db/water.sqlite3") + if err != nil { + panic(err) + } + return db +} \ No newline at end of file diff --git a/api/internal/models/auth.go b/api/internal/models/auth.go new file mode 100644 index 0000000..41344d5 --- /dev/null +++ b/api/internal/models/auth.go @@ -0,0 +1,11 @@ +package models + +import "time" + +type Token struct { + ID int64 `json:"-"` + UserID int64 `json:"user_id"` + Token string `json:"token"` + CreatedAt time.Time `json:"created_at"` + ExpiredAt time.Time `json:"expired_at"` +} diff --git a/api/internal/models/preferences.go b/api/internal/models/preferences.go new file mode 100644 index 0000000..cbbd47c --- /dev/null +++ b/api/internal/models/preferences.go @@ -0,0 +1,14 @@ +package models + +type Preference struct { + ID int64 `json:"-"` + Color string `json:"color"` + UserID int64 `json:"-"` + Size Size `json:"size"` +} + +type Size struct { + ID int64 `json:"-"` + Size int64 `json:"size"` + Unit string `json:"unit"` +} diff --git a/api/internal/models/statistics.go b/api/internal/models/statistics.go new file mode 100644 index 0000000..457e6a0 --- /dev/null +++ b/api/internal/models/statistics.go @@ -0,0 +1,26 @@ +package models + +import "time" + +type Statistic struct { + ID int64 `json:"-"` + Date time.Time `json:"date"` + User User `json:"user"` + Quantity int `json:"quantity"` +} + +type StatisticPost struct { + Date time.Time `json:"date"` + Quantity int64 `json:"quantity"` + UserID int64 `json:"user_id"` +} + +type WeeklyStatistic struct { + Date string `json:"date"` + Total int64 `json:"total"` +} + +type DailyUserTotals struct { + Name string `json:"name"` + Total int64 `json:"total"` +} diff --git a/api/internal/models/user.go b/api/internal/models/user.go new file mode 100644 index 0000000..2a3e6fd --- /dev/null +++ b/api/internal/models/user.go @@ -0,0 +1,10 @@ +package models + +import "github.com/google/uuid" + +type User struct { + ID int64 `json:"-"` + Name string `json:"name"` + UUID uuid.UUID `json:"uuid"` + Password string `json:"-"` +} -- cgit v1.1 From 29f83e05270d0012ad9f273ac3364106fcff5f50 Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Thu, 7 Mar 2024 19:56:34 -0500 Subject: chore: Update paths in test and database configuration This commit updates the paths in the test suite and database configuration to reflect the new directory structure. In the `api/cmd/main_test.go` file, the path for the config file is changed from `viper.SetConfigName(".env")` to `viper.SetConfigFile("../.env")` and `viper.AddConfigPath(".")` is added for configuration purposes. Additionally, `viper.AutomaticEnv()` is added to enable automatic environment variable configuration. In the same file, error handling is improved by adding explicit checks and error messages. The `api/internal/database/database.go` file is also modified, updating the path for database initialization from `"../db/water.sqlite3"` to `"../../db/water.sqlite3"`. These changes ensure proper configuration and functioning of the application. --- api/internal/controllers/auth.go | 14 +++++++------- api/internal/controllers/stats.go | 4 ++-- api/internal/controllers/user.go | 2 +- api/internal/database/database.go | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) (limited to 'api/internal') diff --git a/api/internal/controllers/auth.go b/api/internal/controllers/auth.go index 744a884..de9ed05 100644 --- a/api/internal/controllers/auth.go +++ b/api/internal/controllers/auth.go @@ -1,17 +1,17 @@ package controllers import ( - "encoding/base64" - "net/http" - "github.com/gin-gonic/gin" - "water/api/database" - "errors" "crypto/rand" "database/sql" - - "water/api/models" + "encoding/base64" + "errors" + "github.com/gin-gonic/gin" + "net/http" + "water/api/internal/models" + _ "github.com/mattn/go-sqlite3" "golang.org/x/crypto/bcrypt" + "water/api/internal/database" ) func AuthHandler (c *gin.Context) { diff --git a/api/internal/controllers/stats.go b/api/internal/controllers/stats.go index 9808ace..d8ed434 100644 --- a/api/internal/controllers/stats.go +++ b/api/internal/controllers/stats.go @@ -4,8 +4,8 @@ import ( "database/sql" "github.com/gin-gonic/gin" "net/http" - "water/api/database" - "water/api/models" + "water/api/internal/database" + "water/api/internal/models" ) func GetAllStatistics(c *gin.Context) { diff --git a/api/internal/controllers/user.go b/api/internal/controllers/user.go index 1f3f813..76dedc8 100644 --- a/api/internal/controllers/user.go +++ b/api/internal/controllers/user.go @@ -1,8 +1,8 @@ package controllers import ( - "net/http" "github.com/gin-gonic/gin" + "net/http" ) func GetUser(c *gin.Context) { diff --git a/api/internal/database/database.go b/api/internal/database/database.go index e313af5..19ae818 100644 --- a/api/internal/database/database.go +++ b/api/internal/database/database.go @@ -14,7 +14,7 @@ func SetupDatabase() { } func EstablishDBConnection() *sql.DB { - db, err := sql.Open("sqlite3", "../db/water.sqlite3") + db, err := sql.Open("sqlite3", "../../db/water.sqlite3") if err != nil { panic(err) } -- cgit v1.1 From 831b6f0167b9c1747d128b4a5a648d4de42ff0a9 Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Thu, 7 Mar 2024 20:20:36 -0500 Subject: Refactor router and middleware packages - Move middleware functions from `main.go` to `middleware.go` in the `middleware` package. - Update import statements in `main.go` and use the `router` package instead of the `controllers` package. ``` Refactor router and middleware packages Move middleware functions from `main.go` to `middleware.go` in the `middleware` package. Update import statements in `main.go` and use the `router` package instead of the `controllers` package. ``` --- api/internal/middleware/middleware.go | 55 +++++++++++++++++++++++++++++++++++ api/internal/router/router.go | 42 ++++++++++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 api/internal/middleware/middleware.go create mode 100644 api/internal/router/router.go (limited to 'api/internal') diff --git a/api/internal/middleware/middleware.go b/api/internal/middleware/middleware.go new file mode 100644 index 0000000..819f1e5 --- /dev/null +++ b/api/internal/middleware/middleware.go @@ -0,0 +1,55 @@ +package middleware + +import ( + "errors" + "github.com/gin-gonic/gin" + "log" + "net/http" + "strings" +) + +func TokenRequired() gin.HandlerFunc { + return func(c *gin.Context) { + _, err := checkForTokenInContext(c) + + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) + c.Abort() + return + } + + c.Next() + } +} + +func CORSMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + 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") + + if c.Request.Method == "OPTIONS" { + log.Println(c.Request.Header) + c.AbortWithStatus(http.StatusNoContent) + return + } + + c.Next() + } +} + +func checkForTokenInContext(c *gin.Context) (string, error) { + authorizationHeader := c.GetHeader("Authorization") + if authorizationHeader == "" { + return "", errors.New("authorization header is missing") + } + + parts := strings.Split(authorizationHeader, " ") + + if len(parts) != 2 || parts[0] != "Bearer" { + return "", errors.New("invalid Authorization header format") + } + + return parts[1], nil +} \ No newline at end of file diff --git a/api/internal/router/router.go b/api/internal/router/router.go new file mode 100644 index 0000000..adf96d0 --- /dev/null +++ b/api/internal/router/router.go @@ -0,0 +1,42 @@ +package router + +import ( + "github.com/gin-gonic/gin" + "water/api/internal/controllers" + "water/api/internal/middleware" +) + +func SetupRouter() *gin.Engine { + // Disable Console Color + // gin.DisableConsoleColor() + r := gin.Default() + r.Use(middleware.CORSMiddleware()) + r.Use(gin.Logger()) + r.Use(gin.Recovery()) + + api := r.Group("api/v1") + + api.POST("/auth", controllers.AuthHandler) + + user := api.Group("/user/:uuid") + user.Use(middleware.TokenRequired()) + { + user.GET("", controllers.GetUser) + user.GET("preferences", controllers.GetUserPreferences) + user.PATCH("preferences", controllers.UpdateUserPreferences) + } + + stats := api.Group("/stats") + stats.Use(middleware.TokenRequired()) + { + stats.GET("/", controllers.GetAllStatistics) + stats.POST("/", controllers.PostNewStatistic) + stats.GET("weekly/", controllers.GetWeeklyStatistics) + stats.GET("daily/", controllers.GetDailyUserStatistics) + stats.GET("user/:uuid", controllers.GetUserStatistics) + stats.PATCH("user/:uuid", controllers.UpdateUserStatistic) + stats.DELETE("user/:uuid", controllers.DeleteUserStatistic) + } + + return r +} \ No newline at end of file -- cgit v1.1 From 8fab2d03bce82e4dee798ebffb1e93c557f62a4b Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Thu, 7 Mar 2024 23:16:22 -0500 Subject: feat: Update authentication route and add comments to exported members - The authentication route in the API has been updated to use a new router setup function. - Comments have been added to all exported members of the `auth.go` module in the internal controllers package. --- api/internal/controllers/auth.go | 11 ++++++++++- api/internal/controllers/stats.go | 6 +++++- api/internal/database/database.go | 4 ++-- 3 files changed, 17 insertions(+), 4 deletions(-) (limited to 'api/internal') diff --git a/api/internal/controllers/auth.go b/api/internal/controllers/auth.go index de9ed05..58653d0 100644 --- a/api/internal/controllers/auth.go +++ b/api/internal/controllers/auth.go @@ -14,6 +14,11 @@ import ( "water/api/internal/database" ) + + +// AuthHandler is a function that handles users' authentication. It checks if the request +// has valid credentials, authenticates the user and sets the user's session. +// If the authentication is successful, it will allow the user to access protected routes. func AuthHandler (c *gin.Context) { username, password, ok := c.Request.BasicAuth() if !ok { @@ -55,7 +60,11 @@ func AuthHandler (c *gin.Context) { c.JSON(http.StatusOK, gin.H{"token": apiToken, "user": user, "preferences": preference}) } -// generatToken will g + +// generateToken is a helper function used in the AuthHandler. It generates a random token for API authentication. +// This function creates an empty byte slice of length 32 and fills it with cryptographic random data using the rand.Read function. +// If an error occurs during the generation, it will return an empty string. +// The generated cryptographic random data is then encoded into a base64 string and returned. func generateToken() string { token := make([]byte, 32) _, err := rand.Read(token) diff --git a/api/internal/controllers/stats.go b/api/internal/controllers/stats.go index d8ed434..2234787 100644 --- a/api/internal/controllers/stats.go +++ b/api/internal/controllers/stats.go @@ -8,6 +8,10 @@ import ( "water/api/internal/models" ) +// TODO: add comments to all exported members of package. + +// GetAllStatistics connects to the database and queries for all statistics in the database. +// If none have been found it will return an error, otherwise a 200 code is sent along with the list of statistics. func GetAllStatistics(c *gin.Context) { db := database.EstablishDBConnection() defer func(db *sql.DB) { @@ -78,7 +82,7 @@ func PostNewStatistic(c *gin.Context) { c.JSON(http.StatusCreated, gin.H{"status": "created", "id": id}) } -func GetWeeklyStatistics (c *gin.Context) { +func GetWeeklyStatistics(c *gin.Context) { db := database.EstablishDBConnection() defer func(db *sql.DB) { err := db.Close() diff --git a/api/internal/database/database.go b/api/internal/database/database.go index 19ae818..7af9780 100644 --- a/api/internal/database/database.go +++ b/api/internal/database/database.go @@ -7,14 +7,14 @@ import ( ) func SetupDatabase() { - _, err := sql.Open("sqlite3", "water.db") + _, err := sql.Open("sqlite3", "water.sqlite3") if err != nil { log.Fatal(err) } } func EstablishDBConnection() *sql.DB { - db, err := sql.Open("sqlite3", "../../db/water.sqlite3") + db, err := sql.Open("sqlite3", "../db/water.sqlite3") if err != nil { panic(err) } -- cgit v1.1 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 From c4e5776f9e174fe6bf91721649c0541a9fb310ae Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Fri, 15 Mar 2024 21:41:12 -0400 Subject: add env samples, move files --- api/internal/config/config.go | 17 +++++++++++++++++ api/internal/database/database.go | 16 +++++++++------- 2 files changed, 26 insertions(+), 7 deletions(-) create mode 100644 api/internal/config/config.go (limited to 'api/internal') diff --git a/api/internal/config/config.go b/api/internal/config/config.go new file mode 100644 index 0000000..1892696 --- /dev/null +++ b/api/internal/config/config.go @@ -0,0 +1,17 @@ +package config + +import ( + "fmt" + "github.com/spf13/viper" +) + +func Load() (*viper.Viper, error) { + v := viper.New() + v.SetConfigFile(".env") + v.AddConfigPath(".") + err := v.ReadInConfig() + if err != nil { + return nil, fmt.Errorf("error reading .env file: %s", err) + } + return v, nil +} \ No newline at end of file diff --git a/api/internal/database/database.go b/api/internal/database/database.go index 7af9780..1866655 100644 --- a/api/internal/database/database.go +++ b/api/internal/database/database.go @@ -4,17 +4,19 @@ import ( "database/sql" _ "github.com/mattn/go-sqlite3" "log" + "path/filepath" + "water/api/internal/config" ) -func SetupDatabase() { - _, err := sql.Open("sqlite3", "water.sqlite3") +func EstablishDBConnection() *sql.DB { + c, err := config.Load() + + driver := c.GetString("DB_DRIVER") + path, err := filepath.Abs(c.GetString("DB_PATH")) if err != nil { - log.Fatal(err) + log.Fatal("There was and error getting the absolute path of the database.") } -} - -func EstablishDBConnection() *sql.DB { - db, err := sql.Open("sqlite3", "../db/water.sqlite3") + db, err := sql.Open(driver, path) if err != nil { panic(err) } -- cgit v1.1 From cc49361bcbf689510035e7bbdcce9d8467a36282 Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Fri, 15 Mar 2024 21:45:01 -0400 Subject: add newline, clean up test --- api/internal/config/config.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'api/internal') diff --git a/api/internal/config/config.go b/api/internal/config/config.go index 1892696..d54e40e 100644 --- a/api/internal/config/config.go +++ b/api/internal/config/config.go @@ -14,4 +14,4 @@ func Load() (*viper.Viper, error) { return nil, fmt.Errorf("error reading .env file: %s", err) } return v, nil -} \ No newline at end of file +} -- cgit v1.1 From fd1332a3df191577e91c6d846a8b5db1747099fd Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Fri, 15 Mar 2024 22:00:10 -0400 Subject: cleanup --- api/internal/router/router.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'api/internal') diff --git a/api/internal/router/router.go b/api/internal/router/router.go index 3c86b8c..a71c3e6 100644 --- a/api/internal/router/router.go +++ b/api/internal/router/router.go @@ -30,10 +30,10 @@ func SetupRouter() *gin.Engine { stats := api.Group("/stats") stats.Use(middleware.TokenRequired()) { - stats.GET("/", controllers.GetAllStatistics) - stats.POST("/", controllers.PostNewStatistic) - stats.GET("weekly/", controllers.GetWeeklyStatistics) - stats.GET("daily/", controllers.GetDailyUserStatistics) + stats.GET("", controllers.GetAllStatistics) + stats.POST("", controllers.PostNewStatistic) + stats.GET("weekly", controllers.GetWeeklyStatistics) + stats.GET("daily", controllers.GetDailyUserStatistics) stats.GET("user/:uuid", controllers.GetUserStatistics) stats.PATCH("user/:uuid", controllers.UpdateUserStatistic) stats.DELETE("user/:uuid", controllers.DeleteUserStatistic) -- cgit v1.1