package controllers import ( "crypto/rand" "database/sql" "encoding/base64" "errors" "net/http" "water/api/internal/models" "github.com/gin-gonic/gin" "water/api/internal/database" _ "github.com/glebarez/go-sqlite" "golang.org/x/crypto/bcrypt" ) // 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 { c.Header("WWW-Authenticate", `Basic realm="Please enter your username and password."`) c.AbortWithStatus(http.StatusUnauthorized) return } db, err := database.EstablishDBConnection() if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } 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 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.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) return } else { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) } } 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.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()}) return } // Generate a simple API token apiToken := generateToken() c.JSON(http.StatusOK, gin.H{"token": apiToken, "user": user, "preferences": preference}) } // 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) if err != nil { return "" } return base64.StdEncoding.EncodeToString(token) }