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 ++++ 3 files changed, 247 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 (limited to 'api/internal/controllers') 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 -- 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 +- 3 files changed, 10 insertions(+), 10 deletions(-) (limited to 'api/internal/controllers') 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) { -- 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 +++++- 2 files changed, 15 insertions(+), 2 deletions(-) (limited to 'api/internal/controllers') 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() -- 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 ++++++++++++++++++++++++++++++--- 3 files changed, 111 insertions(+), 11 deletions(-) create mode 100644 api/internal/controllers/preferences.go (limited to 'api/internal/controllers') 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) +} -- cgit v1.1