aboutsummaryrefslogtreecommitdiff
path: root/api/internal
diff options
context:
space:
mode:
Diffstat (limited to 'api/internal')
-rw-r--r--api/internal/config/config.go17
-rw-r--r--api/internal/controllers/auth.go79
-rw-r--r--api/internal/controllers/preferences.go45
-rw-r--r--api/internal/controllers/stats.go168
-rw-r--r--api/internal/controllers/user.go68
-rw-r--r--api/internal/database/database.go24
-rw-r--r--api/internal/middleware/middleware.go56
-rw-r--r--api/internal/models/auth.go11
-rw-r--r--api/internal/models/preferences.go14
-rw-r--r--api/internal/models/statistics.go26
-rw-r--r--api/internal/models/user.go10
-rw-r--r--api/internal/router/router.go43
12 files changed, 561 insertions, 0 deletions
diff --git a/api/internal/config/config.go b/api/internal/config/config.go
new file mode 100644
index 0000000..d54e40e
--- /dev/null
+++ b/api/internal/config/config.go
@@ -0,0 +1,17 @@
1package config
2
3import (
4 "fmt"
5 "github.com/spf13/viper"
6)
7
8func Load() (*viper.Viper, error) {
9 v := viper.New()
10 v.SetConfigFile(".env")
11 v.AddConfigPath(".")
12 err := v.ReadInConfig()
13 if err != nil {
14 return nil, fmt.Errorf("error reading .env file: %s", err)
15 }
16 return v, nil
17}
diff --git a/api/internal/controllers/auth.go b/api/internal/controllers/auth.go
new file mode 100644
index 0000000..ab2fbbb
--- /dev/null
+++ b/api/internal/controllers/auth.go
@@ -0,0 +1,79 @@
1package controllers
2
3import (
4 "crypto/rand"
5 "database/sql"
6 "encoding/base64"
7 "errors"
8 "github.com/gin-gonic/gin"
9 "net/http"
10 "water/api/internal/models"
11
12 _ "github.com/mattn/go-sqlite3"
13 "golang.org/x/crypto/bcrypt"
14 "water/api/internal/database"
15)
16
17
18
19// AuthHandler is a function that handles users' authentication. It checks if the request
20// has valid credentials, authenticates the user and sets the user's session.
21// If the authentication is successful, it will allow the user to access protected routes.
22func AuthHandler (c *gin.Context) {
23 username, password, ok := c.Request.BasicAuth()
24 if !ok {
25 c.Header("WWW-Authenticate", `Basic realm="Please enter your username and password."`)
26 c.AbortWithStatus(http.StatusUnauthorized)
27 return
28 }
29
30 db := database.EstablishDBConnection()
31 defer func(db *sql.DB) {
32 err := db.Close()
33 if err != nil {
34 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
35 return
36 }
37 }(db)
38
39 var user models.User
40 var preference models.Preference
41
42 row := db.QueryRow("SELECT id as 'id', name, uuid, password FROM Users WHERE name = ?", username)
43 if err := row.Scan(&user.ID, &user.Name, &user.UUID, &user.Password); err != nil {
44 if errors.Is(err, sql.ErrNoRows) {
45 c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
46 return
47 }
48 }
49
50 row = db.QueryRow("SELECT id, color, size_id, user_id FROM Preferences where user_id = ?", user.ID)
51 if err := row.Scan(&preference.ID, &preference.Color, &preference.SizeID, &preference.UserID); err != nil {
52 if errors.Is(err, sql.ErrNoRows) {
53 c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
54 }
55 }
56
57 if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
58 c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
59 return
60 }
61
62 // Generate a simple API token
63 apiToken := generateToken()
64 c.JSON(http.StatusOK, gin.H{"token": apiToken, "user": user, "preferences": preference})
65}
66
67
68// generateToken is a helper function used in the AuthHandler. It generates a random token for API authentication.
69// This function creates an empty byte slice of length 32 and fills it with cryptographic random data using the rand.Read function.
70// If an error occurs during the generation, it will return an empty string.
71// The generated cryptographic random data is then encoded into a base64 string and returned.
72func generateToken() string {
73 token := make([]byte, 32)
74 _, err := rand.Read(token)
75 if err != nil {
76 return ""
77 }
78 return base64.StdEncoding.EncodeToString(token)
79} \ No newline at end of file
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 @@
1package controllers
2
3import (
4 "github.com/gin-gonic/gin"
5 "net/http"
6 "database/sql"
7 "water/api/internal/database"
8 "water/api/internal/models"
9)
10
11func GetSizes(c *gin.Context) {
12 db := database.EstablishDBConnection()
13 defer func(db *sql.DB) {
14 err := db.Close()
15 if err != nil {
16 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
17 }
18 }(db)
19
20 rows, err := db.Query("SELECT id, size, unit FROM Sizes")
21 if err != nil {
22 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
23 return
24 }
25 defer func(rows *sql.Rows) {
26 err := rows.Close()
27 if err != nil {
28 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
29 return
30 }
31 }(rows)
32
33 var data []models.Size
34
35 for rows.Next() {
36 var size models.Size
37 if err := rows.Scan(&size.ID, &size.Size, &size.Unit); err != nil {
38 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
39 return
40 }
41 data = append(data, size)
42 }
43
44 c.JSON(http.StatusOK, data)
45}
diff --git a/api/internal/controllers/stats.go b/api/internal/controllers/stats.go
new file mode 100644
index 0000000..2234787
--- /dev/null
+++ b/api/internal/controllers/stats.go
@@ -0,0 +1,168 @@
1package controllers
2
3import (
4 "database/sql"
5 "github.com/gin-gonic/gin"
6 "net/http"
7 "water/api/internal/database"
8 "water/api/internal/models"
9)
10
11// TODO: add comments to all exported members of package.
12
13// GetAllStatistics connects to the database and queries for all statistics in the database.
14// If none have been found it will return an error, otherwise a 200 code is sent along with the list of statistics.
15func GetAllStatistics(c *gin.Context) {
16 db := database.EstablishDBConnection()
17 defer func(db *sql.DB) {
18 err := db.Close()
19 if err != nil {
20 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
21 return
22 }
23 }(db)
24
25 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")
26 if err != nil {
27 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
28 return
29 }
30 defer func(rows *sql.Rows) {
31 err := rows.Close()
32 if err != nil {
33 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
34 return
35 }
36 }(rows)
37
38 var data []models.Statistic
39
40 for rows.Next() {
41 var stat models.Statistic
42 var user models.User
43 if err := rows.Scan(&stat.Date, &stat.Quantity, &user.UUID, &user.Name); err != nil {
44 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
45 return
46 }
47 stat.User = user
48 data = append(data, stat)
49 }
50
51 c.JSON(http.StatusOK, data)
52}
53
54func PostNewStatistic(c *gin.Context) {
55 var stat models.StatisticPost
56
57 if err := c.BindJSON(&stat); err != nil {
58 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
59 return
60 }
61
62 db := database.EstablishDBConnection()
63 defer func(db *sql.DB) {
64 err := db.Close()
65 if err != nil {
66 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
67 return
68 }
69 }(db)
70
71 result, err := db.Exec("INSERT INTO statistics (date, user_id, quantity) values (?, ?, ?)", stat.Date, stat.UserID, stat.Quantity)
72
73 if err != nil {
74 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
75 }
76
77 id, err := result.LastInsertId()
78 if err != nil {
79 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
80 }
81
82 c.JSON(http.StatusCreated, gin.H{"status": "created", "id": id})
83}
84
85func GetWeeklyStatistics(c *gin.Context) {
86 db := database.EstablishDBConnection()
87 defer func(db *sql.DB) {
88 err := db.Close()
89 if err != nil {
90 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
91 return
92 }
93 }(db)
94
95 rows, err := db.Query("SELECT date, total FROM `WeeklyStatisticsView`")
96 if err != nil {
97 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
98 return
99 }
100 defer func(rows *sql.Rows) {
101 err := rows.Close()
102 if err != nil {
103 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
104 return
105 }
106 }(rows)
107
108 var data []models.WeeklyStatistic
109 for rows.Next() {
110 var weeklyStat models.WeeklyStatistic
111 if err := rows.Scan(&weeklyStat.Date, &weeklyStat.Total); err != nil {
112 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
113 }
114 data = append(data, weeklyStat)
115 }
116
117 c.JSON(http.StatusOK, data)
118}
119
120func GetDailyUserStatistics(c *gin.Context) {
121 db := database.EstablishDBConnection()
122 defer func(db *sql.DB) {
123 err := db.Close()
124 if err != nil {
125 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
126 return
127 }
128 }(db)
129
130 rows, err := db.Query("SELECT name, total FROM DailyUserStatistics")
131
132 if err != nil {
133 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
134 return
135 }
136 defer func(rows *sql.Rows) {
137 err := rows.Close()
138 if err != nil {
139 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
140 return
141 }
142 }(rows)
143
144 var data []models.DailyUserTotals
145 for rows.Next() {
146 var stat models.DailyUserTotals
147 if err := rows.Scan(&stat.Name, &stat.Total); err != nil {
148 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
149 return
150 }
151 data = append(data, stat)
152 }
153
154 c.JSON(http.StatusOK, data)
155
156}
157
158func GetUserStatistics(c *gin.Context) {
159 c.JSON(http.StatusOK, gin.H{"status": "ok", "uuid": c.Param("uuid")})
160}
161
162func UpdateUserStatistic(c *gin.Context) {
163 c.JSON(http.StatusNoContent, gin.H{"status": "No Content"})
164}
165
166func DeleteUserStatistic(c *gin.Context) {
167 c.JSON(http.StatusNoContent, gin.H{"status": "No Content"})
168}
diff --git a/api/internal/controllers/user.go b/api/internal/controllers/user.go
new file mode 100644
index 0000000..dbb09cf
--- /dev/null
+++ b/api/internal/controllers/user.go
@@ -0,0 +1,68 @@
1package controllers
2
3import (
4 "database/sql"
5 "errors"
6 "log"
7 "net/http"
8 "water/api/internal/database"
9 "water/api/internal/models"
10
11 "github.com/gin-gonic/gin"
12)
13
14func GetUser(c *gin.Context) {
15 c.JSON(http.StatusOK, gin.H{"message": "User found"})
16}
17func GetUserPreferences(c *gin.Context) {
18 db := database.EstablishDBConnection()
19 defer func(db *sql.DB) {
20 err := db.Close()
21 if err != nil {
22 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
23 return
24 }
25 }(db)
26
27 var preference models.Preference
28
29 row := db.QueryRow("SELECT id, user_id, color, size_id FROM Preferences WHERE user_id = ?", c.Param("id"))
30 if err := row.Scan(&preference.ID, &preference.UserID, &preference.Color, &preference.SizeID); err != nil {
31 if errors.Is(err, sql.ErrNoRows) {
32 c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
33 return
34 } else {
35 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
36 return
37 }
38 }
39
40 c.JSON(http.StatusOK, preference)
41}
42
43func UpdateUserPreferences(c *gin.Context) {
44 db := database.EstablishDBConnection()
45 defer func(db *sql.DB) {
46 err := db.Close()
47 if err != nil {
48 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
49 return
50 }
51 }(db)
52
53 var newPreferences models.Preference
54 if err := c.BindJSON(&newPreferences); err != nil {
55 c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
56 return
57 }
58
59 log.Printf("newPreferences: %v", newPreferences)
60
61 _, err := db.Exec("UPDATE Preferences SET color = ?, size_id = ? WHERE id = ?", newPreferences.Color, newPreferences.SizeID, newPreferences.ID)
62 if err != nil {
63 c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
64 return
65 }
66
67 c.Status(http.StatusNoContent)
68}
diff --git a/api/internal/database/database.go b/api/internal/database/database.go
new file mode 100644
index 0000000..1866655
--- /dev/null
+++ b/api/internal/database/database.go
@@ -0,0 +1,24 @@
1package database
2
3import (
4 "database/sql"
5 _ "github.com/mattn/go-sqlite3"
6 "log"
7 "path/filepath"
8 "water/api/internal/config"
9)
10
11func EstablishDBConnection() *sql.DB {
12 c, err := config.Load()
13
14 driver := c.GetString("DB_DRIVER")
15 path, err := filepath.Abs(c.GetString("DB_PATH"))
16 if err != nil {
17 log.Fatal("There was and error getting the absolute path of the database.")
18 }
19 db, err := sql.Open(driver, path)
20 if err != nil {
21 panic(err)
22 }
23 return db
24} \ No newline at end of file
diff --git a/api/internal/middleware/middleware.go b/api/internal/middleware/middleware.go
new file mode 100644
index 0000000..aa27fb8
--- /dev/null
+++ b/api/internal/middleware/middleware.go
@@ -0,0 +1,56 @@
1package middleware
2
3import (
4 "errors"
5 "log"
6 "net/http"
7 "strings"
8
9 "github.com/gin-gonic/gin"
10)
11
12func TokenRequired() gin.HandlerFunc {
13 return func(c *gin.Context) {
14 _, err := checkForTokenInContext(c)
15
16 if err != nil {
17 c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
18 c.Abort()
19 return
20 }
21
22 c.Next()
23 }
24}
25
26func CORSMiddleware() gin.HandlerFunc {
27 return func(c *gin.Context) {
28 c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
29 c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
30 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")
31 c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, PATCH")
32
33 if c.Request.Method == "OPTIONS" {
34 log.Println(c.Request.Header)
35 c.AbortWithStatus(http.StatusNoContent)
36 return
37 }
38
39 c.Next()
40 }
41}
42
43func checkForTokenInContext(c *gin.Context) (string, error) {
44 authorizationHeader := c.GetHeader("Authorization")
45 if authorizationHeader == "" {
46 return "", errors.New("authorization header is missing")
47 }
48
49 parts := strings.Split(authorizationHeader, " ")
50
51 if len(parts) != 2 || parts[0] != "Bearer" {
52 return "", errors.New("invalid Authorization header format")
53 }
54
55 return parts[1], nil
56}
diff --git a/api/internal/models/auth.go b/api/internal/models/auth.go
new file mode 100644
index 0000000..fa7dbe4
--- /dev/null
+++ b/api/internal/models/auth.go
@@ -0,0 +1,11 @@
1package models
2
3import "time"
4
5type Token struct {
6 ID int64 `json:"id"`
7 UserID int64 `json:"user_id"`
8 Token string `json:"token"`
9 CreatedAt time.Time `json:"created_at"`
10 ExpiredAt time.Time `json:"expired_at"`
11}
diff --git a/api/internal/models/preferences.go b/api/internal/models/preferences.go
new file mode 100644
index 0000000..8022099
--- /dev/null
+++ b/api/internal/models/preferences.go
@@ -0,0 +1,14 @@
1package models
2
3type Preference struct {
4 ID int64 `json:"id"`
5 Color string `json:"color"`
6 UserID int64 `json:"user_id"`
7 SizeID int64 `json:"size_id"`
8}
9
10type Size struct {
11 ID int64 `json:"id"`
12 Size int64 `json:"size"`
13 Unit string `json:"unit"`
14}
diff --git a/api/internal/models/statistics.go b/api/internal/models/statistics.go
new file mode 100644
index 0000000..7dceb3a
--- /dev/null
+++ b/api/internal/models/statistics.go
@@ -0,0 +1,26 @@
1package models
2
3import "time"
4
5type Statistic struct {
6 ID int64 `json:"id"`
7 Date time.Time `json:"date"`
8 User User `json:"user"`
9 Quantity int `json:"quantity"`
10}
11
12type StatisticPost struct {
13 Date time.Time `json:"date"`
14 Quantity int64 `json:"quantity"`
15 UserID int64 `json:"user_id"`
16}
17
18type WeeklyStatistic struct {
19 Date string `json:"date"`
20 Total int64 `json:"total"`
21}
22
23type DailyUserTotals struct {
24 Name string `json:"name"`
25 Total int64 `json:"total"`
26}
diff --git a/api/internal/models/user.go b/api/internal/models/user.go
new file mode 100644
index 0000000..ca5daa4
--- /dev/null
+++ b/api/internal/models/user.go
@@ -0,0 +1,10 @@
1package models
2
3import "github.com/google/uuid"
4
5type User struct {
6 ID int64 `json:"id"`
7 Name string `json:"name"`
8 UUID uuid.UUID `json:"uuid"`
9 Password string `json:"-"`
10}
diff --git a/api/internal/router/router.go b/api/internal/router/router.go
new file mode 100644
index 0000000..a71c3e6
--- /dev/null
+++ b/api/internal/router/router.go
@@ -0,0 +1,43 @@
1package router
2
3import (
4 "github.com/gin-gonic/gin"
5 "water/api/internal/controllers"
6 "water/api/internal/middleware"
7)
8
9func SetupRouter() *gin.Engine {
10 // Disable Console Color
11 // gin.DisableConsoleColor()
12 r := gin.Default()
13 r.Use(middleware.CORSMiddleware())
14 r.Use(gin.Logger())
15 r.Use(gin.Recovery())
16
17 api := r.Group("api/v1")
18
19 api.POST("/auth", controllers.AuthHandler)
20 api.GET("/sizes", middleware.TokenRequired(), controllers.GetSizes)
21 api.PATCH("/user/preferences", controllers.UpdateUserPreferences)
22
23 user := api.Group("/user/:id")
24 user.Use(middleware.TokenRequired())
25 {
26 user.GET("", controllers.GetUser)
27 user.GET("preferences", controllers.GetUserPreferences)
28 }
29
30 stats := api.Group("/stats")
31 stats.Use(middleware.TokenRequired())
32 {
33 stats.GET("", controllers.GetAllStatistics)
34 stats.POST("", controllers.PostNewStatistic)
35 stats.GET("weekly", controllers.GetWeeklyStatistics)
36 stats.GET("daily", controllers.GetDailyUserStatistics)
37 stats.GET("user/:uuid", controllers.GetUserStatistics)
38 stats.PATCH("user/:uuid", controllers.UpdateUserStatistic)
39 stats.DELETE("user/:uuid", controllers.DeleteUserStatistic)
40 }
41
42 return r
43} \ No newline at end of file