aboutsummaryrefslogtreecommitdiff
path: root/api/cmd/main.go
blob: 1924556d43f8e80ac7e64119dc912e90cb227b55 (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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main

import (
	"errors"
	"log"
	"net/http"
	"strings"
	"water/api/internal/database"
	"water/api/internal/controllers"

	"github.com/gin-gonic/gin"
	_ "github.com/mattn/go-sqlite3"
)

func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		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")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")

		if c.Request.Method == "OPTIONS" {
			log.Println(c.Request.Header)
			c.AbortWithStatus(http.StatusNoContent)
			return
		}

		c.Next()
	}
}

func checkForTokenInContext(c *gin.Context) (string, error) {
	authorizationHeader := c.GetHeader("Authorization")
	if authorizationHeader == "" {
		return "", errors.New("authorization header is missing")
	}

	parts := strings.Split(authorizationHeader, " ")

	if len(parts) != 2 || parts[0] != "Bearer" {
		return "", errors.New("invalid Authorization header format")
	}

	return parts[1], nil
}

func TokenRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		_, err := checkForTokenInContext(c)

		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
			c.Abort()
			return
		}

		c.Next()
	}
}

func setupRouter() *gin.Engine {
	// Disable Console Color
	// gin.DisableConsoleColor()
	r := gin.Default()
	r.Use(CORSMiddleware())
	r.Use(gin.Logger())
	r.Use(gin.Recovery())

	api := r.Group("api/v1")

	api.POST("/auth", controllers.AuthHandler)

	user := api.Group("/user/:uuid")
	user.Use(TokenRequired())
	{
		user.GET("", controllers.GetUser)
		user.GET("preferences", controllers.GetUserPreferences)
		user.PATCH("preferences", controllers.UpdateUserPreferences)
	}

	stats := api.Group("/stats")
	stats.Use(TokenRequired())
	{
		stats.GET("/", controllers.GetAllStatistics)
		stats.POST("/", controllers.PostNewStatistic)
		stats.GET("weekly/", controllers.GetWeeklyStatistics)
		stats.GET("daily/", controllers.GetDailyUserStatistics)
		stats.GET("user/:uuid", controllers.GetUserStatistics)
		stats.PATCH("user/:uuid", controllers.UpdateUserStatistic)
		stats.DELETE("user/:uuid", controllers.DeleteUserStatistic)
	}

	return r
}

func main() {
	database.SetupDatabase()
	r := setupRouter()
	// Listen and Server in 0.0.0.0:8080
	err := r.Run(":8080")
	if err != nil {
		return
	}
}