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/stats.go | 164 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 api/internal/controllers/stats.go (limited to 'api/internal/controllers/stats.go') 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"}) +} -- 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/stats.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'api/internal/controllers/stats.go') 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) { -- 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/stats.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'api/internal/controllers/stats.go') 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() -- cgit v1.1