aboutsummaryrefslogtreecommitdiff
path: root/api/internal/controllers/auth.go
blob: b06c6ef70f703d05054967d093ce05fb68899ca5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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/mattn/go-sqlite3"
	"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)
}