aboutsummaryrefslogtreecommitdiff
path: root/api/internal/controllers/auth.go
diff options
context:
space:
mode:
Diffstat (limited to 'api/internal/controllers/auth.go')
-rw-r--r--api/internal/controllers/auth.go79
1 files changed, 79 insertions, 0 deletions
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