From 3eafb413a48cde60dea8a7355ee621c6acca952f Mon Sep 17 00:00:00 2001 From: Doog <157747121+doogongithub@users.noreply.github.com> Date: Wed, 21 Feb 2024 22:07:27 -0500 Subject: first commit --- api/go.mod | 32 ++++++++++++++++++++ api/go.sum | 80 +++++++++++++++++++++++++++++++++++++++++++++++++ api/main.go | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 211 insertions(+) create mode 100644 api/go.mod create mode 100644 api/go.sum create mode 100644 api/main.go (limited to 'api') diff --git a/api/go.mod b/api/go.mod new file mode 100644 index 0000000..02f7c09 --- /dev/null +++ b/api/go.mod @@ -0,0 +1,32 @@ +module water/api + +go 1.18 + +require ( + github.com/bytedance/sonic v1.11.0 // indirect + github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect + github.com/chenzhuoyu/iasm v0.9.1 // indirect + github.com/gabriel-vasile/mimetype v1.4.3 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/gin-gonic/gin v1.9.1 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.18.0 // indirect + github.com/goccy/go-json v0.10.2 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.6 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.1.1 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + golang.org/x/arch v0.7.0 // indirect + golang.org/x/crypto v0.19.0 // indirect + golang.org/x/net v0.21.0 // indirect + golang.org/x/sys v0.17.0 // indirect + golang.org/x/text v0.14.0 // indirect + google.golang.org/protobuf v1.32.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/api/go.sum b/api/go.sum new file mode 100644 index 0000000..eff6af1 --- /dev/null +++ b/api/go.sum @@ -0,0 +1,80 @@ +github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= +github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM= +github.com/bytedance/sonic v1.11.0 h1:FwNNv6Vu4z2Onf1++LNzxB/QhitD8wuTdpZzMTGITWo= +github.com/bytedance/sonic v1.11.0/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4= +github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= +github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0= +github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA= +github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= +github.com/chenzhuoyu/iasm v0.9.1 h1:tUHQJXo3NhBqw6s33wkGn9SP3bvrWLdlVIJ3hQBL7P0= +github.com/chenzhuoyu/iasm v0.9.1/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= +github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= +github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.18.0 h1:BvolUXjp4zuvkZ5YN5t7ebzbhlUtPsPm2S9NAZ5nl9U= +github.com/go-playground/validator/v10 v10.18.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc= +github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI= +github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc= +golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I= +google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/api/main.go b/api/main.go new file mode 100644 index 0000000..ebae5d1 --- /dev/null +++ b/api/main.go @@ -0,0 +1,99 @@ +package main + +import ( + "net/http" + "crypto/rand" + "encoding/base64" + + "github.com/gin-gonic/gin" +) + +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" { + c.AbortWithStatus(204) + return + } + + c.Next() + } +} + +func generateToken() string { + token := make([]byte, 32) + rand.Read(token) + return base64.StdEncoding.EncodeToString(token) +} + +type User struct { + Username string + Password string +} + +var users = map[string]User{ + "user1": {"user1", "password1"}, +} + +func setupRouter() *gin.Engine { + // Disable Console Color + // gin.DisableConsoleColor() + r := gin.Default() + r.Use(CORSMiddleware()) + + api := r.Group("api/v1") + + api.POST("/auth", func(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 + } + + user, exists := users[username] + + if !exists || user.Password != password { + c.AbortWithStatus(http.StatusUnauthorized) + return + } + + // Generate a simple API token + apiToken := generateToken() + c.JSON(http.StatusOK, gin.H{"token": apiToken}) + }) + + stats := api.Group("stats") + + stats.GET("/", func(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"status": "ok"}) + }) + + stats.POST("/", func(c *gin.Context) { + c.JSON(http.StatusCreated, gin.H{"status": "created"}) + }) + + stats.GET("/:uuid", func(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"status": "ok", "uuid": c.Param("uuid")}) + }) + + stats.PATCH("/:uuid", func(c *gin.Context) { + c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) + }) + + stats.DELETE("/:uuid", func(c *gin.Context) { + c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) + }) + + return r +} + +func main() { + r := setupRouter() + // Listen and Server in 0.0.0.0:8080 + r.Run(":8080") +} -- cgit v1.1 From e37c73e33a4aaf7fb8d25b5af03627f20bcda19f Mon Sep 17 00:00:00 2001 From: Doog <157747121+doogongithub@users.noreply.github.com> Date: Sat, 24 Feb 2024 20:08:35 -0500 Subject: add gitignore --- api/go.mod | 6 ++- api/go.sum | 9 ++++ api/lib/models.go | 23 ++++++++++ api/main.go | 127 ++++++++++++++++++++++++++++++++++++++++++++++-------- 4 files changed, 145 insertions(+), 20 deletions(-) create mode 100644 api/lib/models.go (limited to 'api') diff --git a/api/go.mod b/api/go.mod index 02f7c09..08ad9e1 100644 --- a/api/go.mod +++ b/api/go.mod @@ -3,12 +3,16 @@ module water/api go 1.18 require ( + github.com/gin-gonic/gin v1.9.1 + github.com/mattn/go-sqlite3 v1.14.22 +) + +require ( github.com/bytedance/sonic v1.11.0 // indirect github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect github.com/chenzhuoyu/iasm v0.9.1 // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect github.com/gin-contrib/sse v0.1.0 // indirect - github.com/gin-gonic/gin v1.9.1 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.18.0 // indirect diff --git a/api/go.sum b/api/go.sum index eff6af1..5174feb 100644 --- a/api/go.sum +++ b/api/go.sum @@ -10,6 +10,7 @@ github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLI github.com/chenzhuoyu/iasm v0.9.1 h1:tUHQJXo3NhBqw6s33wkGn9SP3bvrWLdlVIJ3hQBL7P0= github.com/chenzhuoyu/iasm v0.9.1/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= @@ -17,6 +18,7 @@ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= @@ -25,6 +27,7 @@ github.com/go-playground/validator/v10 v10.18.0 h1:BvolUXjp4zuvkZ5YN5t7ebzbhlUtP github.com/go-playground/validator/v10 v10.18.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= @@ -36,6 +39,8 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= +github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -43,6 +48,7 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI= github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= @@ -52,6 +58,7 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= @@ -70,8 +77,10 @@ golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I= google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/api/lib/models.go b/api/lib/models.go new file mode 100644 index 0000000..92e5703 --- /dev/null +++ b/api/lib/models.go @@ -0,0 +1,23 @@ +package models + +import "time" + +type Statistic struct { + ID int64 `json:"id"` + Date time.Time `json:"date"` + UserID int64 `json:"user_id"` + Quantity int `json:"quantity"` +} + +type User struct { + ID int64 + Name string +} + +type Token struct { + ID int64 + UserID int64 + Token string + CreatedAt time.Time + ExpiredAt time.Time +} diff --git a/api/main.go b/api/main.go index ebae5d1..292a5f9 100644 --- a/api/main.go +++ b/api/main.go @@ -4,8 +4,13 @@ import ( "net/http" "crypto/rand" "encoding/base64" + "database/sql" + "strings" + "errors" "github.com/gin-gonic/gin" + _ "github.com/mattn/go-sqlite3" + "water/api/lib" ) func CORSMiddleware() gin.HandlerFunc { @@ -30,6 +35,44 @@ func generateToken() string { return base64.StdEncoding.EncodeToString(token) } +func establishDBConnection() *sql.DB { + db, err := sql.Open("sqlite3", "../db/water.sqlite3") + if err != nil { + panic(err) + } + return db +} + +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() + } +} + type User struct { Username string Password string @@ -44,6 +87,8 @@ func setupRouter() *gin.Engine { // gin.DisableConsoleColor() r := gin.Default() r.Use(CORSMiddleware()) + r.Use(gin.Logger()) + r.Use(gin.Recovery()) api := r.Group("api/v1") @@ -68,26 +113,70 @@ func setupRouter() *gin.Engine { }) stats := api.Group("stats") + stats.Use(TokenRequired()) + { + stats.GET("/", func(c *gin.Context) { + db := establishDBConnection() + defer db.Close() + + rows, err := db.Query("SELECT * FROM statistics"); + if err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + defer rows.Close() + + var data []models.Statistic + for rows.Next() { + var stat models.Statistic + if err := rows.Scan(&stat.ID, &stat.Date, &stat.UserID, &stat.Quantity); err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + data = append(data, stat) + } + + c.JSON(http.StatusOK, data) + }) + + stats.POST("/", func(c *gin.Context) { + var stat models.Statistic + + if err := c.BindJSON(&stat); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + db := establishDBConnection() + defer db.Close() + + result, err := db.Exec("INSERT INTO statistics (date, user_id, quantity) values (?, ?, ?)", stat.Date, stat.UserID, stat.Quantity) + + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + } + + id, err := result.LastInsertId() + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + } + + c.JSON(http.StatusCreated, gin.H{"status": "created", "id": id}) + }) + + stats.GET("/:uuid", func(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"status": "ok", "uuid": c.Param("uuid")}) + }) + + stats.PATCH("/:uuid", func(c *gin.Context) { + c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) + }) + + stats.DELETE("/:uuid", func(c *gin.Context) { + c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) + }) + } - stats.GET("/", func(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"status": "ok"}) - }) - - stats.POST("/", func(c *gin.Context) { - c.JSON(http.StatusCreated, gin.H{"status": "created"}) - }) - - stats.GET("/:uuid", func(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"status": "ok", "uuid": c.Param("uuid")}) - }) - - stats.PATCH("/:uuid", func(c *gin.Context) { - c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) - }) - - stats.DELETE("/:uuid", func(c *gin.Context) { - c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) - }) return r } -- cgit v1.1 From 9f9a33cbf55d38987a66b709284d2bb4ffea0fe9 Mon Sep 17 00:00:00 2001 From: Doog <157747121+doogongithub@users.noreply.github.com> Date: Thu, 29 Feb 2024 20:13:48 -0500 Subject: modify api, build additional FE components, add types --- api/go.mod | 3 ++- api/go.sum | 2 ++ api/lib/models.go | 38 ++++++++++++++++++++++++++++---------- api/main.go | 48 ++++++++++++++++++++++++++++++------------------ 4 files changed, 62 insertions(+), 29 deletions(-) (limited to 'api') diff --git a/api/go.mod b/api/go.mod index 08ad9e1..6a326bc 100644 --- a/api/go.mod +++ b/api/go.mod @@ -4,7 +4,9 @@ go 1.18 require ( github.com/gin-gonic/gin v1.9.1 + github.com/google/uuid v1.6.0 github.com/mattn/go-sqlite3 v1.14.22 + golang.org/x/crypto v0.19.0 ) require ( @@ -27,7 +29,6 @@ require ( github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect golang.org/x/arch v0.7.0 // indirect - golang.org/x/crypto v0.19.0 // indirect golang.org/x/net v0.21.0 // indirect golang.org/x/sys v0.17.0 // indirect golang.org/x/text v0.14.0 // indirect diff --git a/api/go.sum b/api/go.sum index 5174feb..115a832 100644 --- a/api/go.sum +++ b/api/go.sum @@ -29,6 +29,8 @@ github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= diff --git a/api/lib/models.go b/api/lib/models.go index 92e5703..f959519 100644 --- a/api/lib/models.go +++ b/api/lib/models.go @@ -1,23 +1,41 @@ package models -import "time" +import ( + "time" + "github.com/google/uuid" +) type Statistic struct { - ID int64 `json:"id"` + ID int64 `json:"-"` Date time.Time `json:"date"` - UserID int64 `json:"user_id"` + User User `json:"user"` Quantity int `json:"quantity"` } type User struct { - ID int64 - Name string + ID int64 `json:"-"` + Name string `json:"name"` + UUID uuid.UUID `json:"uuid"` + Password string `json:"-"` } type Token struct { - ID int64 - UserID int64 - Token string - CreatedAt time.Time - ExpiredAt time.Time + ID int64 `json:"-"` + UserID int64 `json:"user_id"` + Token string `json:"token"` + CreatedAt time.Time `json:"created_at"` + ExpiredAt time.Time `json:"expired_at"` +} + +type Preference struct { + ID int64 `json:"-"` + Color string `json:"color"` + UserID int64 `json:"-"` + Size Size `json:"size"` +} + +type Size struct { + ID int64 `json:"-"` + Size int64 `json:"size"` + Unit string `json:"unit"` } diff --git a/api/main.go b/api/main.go index 292a5f9..91b7929 100644 --- a/api/main.go +++ b/api/main.go @@ -10,6 +10,7 @@ import ( "github.com/gin-gonic/gin" _ "github.com/mattn/go-sqlite3" + "golang.org/x/crypto/bcrypt" "water/api/lib" ) @@ -29,6 +30,7 @@ func CORSMiddleware() gin.HandlerFunc { } } +// generatToken will g func generateToken() string { token := make([]byte, 32) rand.Read(token) @@ -43,6 +45,7 @@ func establishDBConnection() *sql.DB { return db } + func checkForTokenInContext(c *gin.Context) (string, error) { authorizationHeader := c.GetHeader("Authorization") if authorizationHeader == "" { @@ -54,6 +57,7 @@ func checkForTokenInContext(c *gin.Context) (string, error) { if len(parts) != 2 || parts[0] != "Bearer" { return "", errors.New("Invalid Authorization header format") } + return parts[1], nil } @@ -73,15 +77,6 @@ func TokenRequired() gin.HandlerFunc { } } -type User struct { - Username string - Password string -} - -var users = map[string]User{ - "user1": {"user1", "password1"}, -} - func setupRouter() *gin.Engine { // Disable Console Color // gin.DisableConsoleColor() @@ -100,16 +95,31 @@ func setupRouter() *gin.Engine { return } - user, exists := users[username] + db := establishDBConnection() + defer db.Close() + + var user models.User + var preference models.Preference + var size models.Size + + row := db.QueryRow("SELECT name, uuid, password, color, size, unit FROM Users u INNER JOIN Preferences p ON p.user_id = u.id INNER JOIN Sizes s ON p.size_id = s.id WHERE u.name = ?", username) + if err := row.Scan(&user.Name, &user.UUID, &user.Password, &preference.Color, &size.Size, &size.Unit); err != nil { + if err == sql.ErrNoRows { + c.AbortWithStatus(http.StatusUnauthorized) + return + } + } + + if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { + c.AbortWithStatus(http.StatusUnauthorized) + return + } - if !exists || user.Password != password { - c.AbortWithStatus(http.StatusUnauthorized) - return - } + preference.Size = size // Generate a simple API token apiToken := generateToken() - c.JSON(http.StatusOK, gin.H{"token": apiToken}) + c.JSON(http.StatusOK, gin.H{"token": apiToken, "user": user, "preferences": preference}) }) stats := api.Group("stats") @@ -119,7 +129,7 @@ func setupRouter() *gin.Engine { db := establishDBConnection() defer db.Close() - rows, err := db.Query("SELECT * FROM statistics"); + 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"); if err != nil { c.JSON(500, gin.H{"error": err.Error()}) return @@ -129,10 +139,12 @@ func setupRouter() *gin.Engine { var data []models.Statistic for rows.Next() { var stat models.Statistic - if err := rows.Scan(&stat.ID, &stat.Date, &stat.UserID, &stat.Quantity); err != nil { + var user models.User + if err := rows.Scan(&stat.Date, &stat.Quantity, &user.UUID, &user.Name); err != nil { c.JSON(500, gin.H{"error": err.Error()}) return } + stat.User = user data = append(data, stat) } @@ -150,7 +162,7 @@ func setupRouter() *gin.Engine { db := establishDBConnection() defer db.Close() - result, err := db.Exec("INSERT INTO statistics (date, user_id, quantity) values (?, ?, ?)", stat.Date, stat.UserID, stat.Quantity) + result, err := db.Exec("INSERT INTO statistics (date, user_id, quantity) values (?, ?, ?)", stat.Date, 1, stat.Quantity) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) -- cgit v1.1 From cf2113e77edabf8e3a632c7b76c769752039ba88 Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Sat, 2 Mar 2024 16:52:55 -0500 Subject: feat: Add API logging Add logging to the API to keep track of specific requests and headers. Also added CORS middleware to handle OPTIONS requests. --- The commit adds logging functionality to the API and includes a middleware function to handle CORS OPTIONS requests. This will allow us to track specific requests and headers received by the API. [API/main.go](/api/main.go): - Added import for the 'log' package - Added logging statements to print the request headers and "_I am here_" message - Removed unnecessary newlines and comments [fe/src/app.css](/fe/src/app.css): - Added a new style for button hover effects [fe/src/lib/Card.svelte](/fe/src/lib/Card.svelte): - Added a new `height` prop to the Card component [fe/src/lib/Column.svelte](/fe/src/lib/Column.svelte): - Added a new CSS class for column layout - Set the width and gap using CSS variables [fe/src/lib/DataView.svelte](/fe/src/lib/DataView.svelte): - Updated the 'fetchData' function to also fetch 'totals' and 'userStats' data - Added canvas references and chart variables for bar and line charts - Added a new 'getLastSevenDays' function to calculate the labels for the charts - Updated the 'onMount' function to initialize the bar and line charts using the canvas references and data - Updated the 'onDestroy' function to destroy the bar and line charts - Added a new 'addFormOpen' store and imported it - Added a new 'onClick' handler for the Add button to open the AddForm modal - Updated the layout and added Card components to display the bar and line charts and the JSON data - Added a new 'fetchTotals' function to fetch data for the 'totals' section - Added a new 'fetchStatsForUser' function to fetch data for the 'userStats' section [fe/src/lib/Layout.svelte](/fe/src/lib/Layout.svelte): - Added a new 'preferenceFormOpen' variable and initialized it to 'false' - Added a new 'showPreferencesDialog' function to set 'preferenceFormOpen' to 'true' - Added a new 'closePreferenceDialog' function to set 'preferenceFormOpen' to 'false' - Added a new 'showAddDialog' function to open the AddForm modal --- api/main.go | 384 ++++++++++++++++++++++++++++++++++++------------------------ 1 file changed, 229 insertions(+), 155 deletions(-) (limited to 'api') diff --git a/api/main.go b/api/main.go index 91b7929..57feb09 100644 --- a/api/main.go +++ b/api/main.go @@ -2,193 +2,267 @@ package main import ( "net/http" - "crypto/rand" - "encoding/base64" - "database/sql" - "strings" - "errors" + "crypto/rand" + "encoding/base64" + "database/sql" + "strings" + "errors" + "log" "github.com/gin-gonic/gin" - _ "github.com/mattn/go-sqlite3" - "golang.org/x/crypto/bcrypt" - "water/api/lib" + _ "github.com/mattn/go-sqlite3" + "golang.org/x/crypto/bcrypt" + "water/api/lib" ) 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" { - c.AbortWithStatus(204) - return - } - - c.Next() - } + 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") + + log.Println("I am here") + + if c.Request.Method == "OPTIONS" { + log.Println(c.Request.Header) + c.AbortWithStatus(204) + return + } + + log.Println(c.Request.Header) + c.Next() + } } // generatToken will g func generateToken() string { - token := make([]byte, 32) - rand.Read(token) - return base64.StdEncoding.EncodeToString(token) + token := make([]byte, 32) + rand.Read(token) + return base64.StdEncoding.EncodeToString(token) } func establishDBConnection() *sql.DB { - db, err := sql.Open("sqlite3", "../db/water.sqlite3") - if err != nil { - panic(err) - } - return db + db, err := sql.Open("sqlite3", "../db/water.sqlite3") + if err != nil { + panic(err) + } + return db } - func checkForTokenInContext(c *gin.Context) (string, error) { - authorizationHeader := c.GetHeader("Authorization") - if authorizationHeader == "" { - return "", errors.New("Authorization header is missing") - } + authorizationHeader := c.GetHeader("Authorization") + if authorizationHeader == "" { + return "", errors.New("Authorization header is missing") + } - parts := strings.Split(authorizationHeader, " ") + parts := strings.Split(authorizationHeader, " ") - if len(parts) != 2 || parts[0] != "Bearer" { - return "", errors.New("Invalid Authorization header format") - } + if len(parts) != 2 || parts[0] != "Bearer" { + return "", errors.New("Invalid Authorization header format") + } - - return parts[1], nil + return parts[1], nil } - func TokenRequired() gin.HandlerFunc { - return func(c *gin.Context) { - _, err := checkForTokenInContext(c) + return func(c *gin.Context) { + _, err := checkForTokenInContext(c) - if err != nil { - c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) - c.Abort() - return - } + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) + c.Abort() + return + } - c.Next() - } + 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", func(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 := establishDBConnection() - defer db.Close() - - var user models.User - var preference models.Preference - var size models.Size - - row := db.QueryRow("SELECT name, uuid, password, color, size, unit FROM Users u INNER JOIN Preferences p ON p.user_id = u.id INNER JOIN Sizes s ON p.size_id = s.id WHERE u.name = ?", username) - if err := row.Scan(&user.Name, &user.UUID, &user.Password, &preference.Color, &size.Size, &size.Unit); err != nil { - if err == sql.ErrNoRows { - c.AbortWithStatus(http.StatusUnauthorized) - return - } - } - - if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { - c.AbortWithStatus(http.StatusUnauthorized) - return - } - - preference.Size = size + r.Use(CORSMiddleware()) + r.Use(gin.Logger()) + r.Use(gin.Recovery()) + + api := r.Group("api/v1") + + api.POST("/auth", func(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 := establishDBConnection() + defer db.Close() + + var user models.User + var preference models.Preference + var size models.Size + + row := db.QueryRow("SELECT name, uuid, password, color, size, unit FROM Users u INNER JOIN Preferences p ON p.user_id = u.id INNER JOIN Sizes s ON p.size_id = s.id WHERE u.name = ?", username) + if err := row.Scan(&user.Name, &user.UUID, &user.Password, &preference.Color, &size.Size, &size.Unit); err != nil { + if err == sql.ErrNoRows { + c.AbortWithStatus(http.StatusUnauthorized) + return + } + } + + if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { + c.AbortWithStatus(http.StatusUnauthorized) + return + } + + preference.Size = size // Generate a simple API token apiToken := generateToken() - c.JSON(http.StatusOK, gin.H{"token": apiToken, "user": user, "preferences": preference}) - }) - - stats := api.Group("stats") - stats.Use(TokenRequired()) - { - stats.GET("/", func(c *gin.Context) { - db := establishDBConnection() - defer db.Close() - - 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"); - if err != nil { - c.JSON(500, gin.H{"error": err.Error()}) - return - } - defer rows.Close() - - var data []models.Statistic - for rows.Next() { - var stat models.Statistic - var user models.User - if err := rows.Scan(&stat.Date, &stat.Quantity, &user.UUID, &user.Name); err != nil { - c.JSON(500, gin.H{"error": err.Error()}) - return - } - stat.User = user - data = append(data, stat) - } - - c.JSON(http.StatusOK, data) - }) - - stats.POST("/", func(c *gin.Context) { - var stat models.Statistic - - if err := c.BindJSON(&stat); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - return - } - - db := establishDBConnection() - defer db.Close() - - result, err := db.Exec("INSERT INTO statistics (date, user_id, quantity) values (?, ?, ?)", stat.Date, 1, stat.Quantity) - - if err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - } - - id, err := result.LastInsertId() - if err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - } - - c.JSON(http.StatusCreated, gin.H{"status": "created", "id": id}) - }) - - stats.GET("/:uuid", func(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"status": "ok", "uuid": c.Param("uuid")}) - }) - - stats.PATCH("/:uuid", func(c *gin.Context) { - c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) - }) - - stats.DELETE("/:uuid", func(c *gin.Context) { - c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) - }) - } - + c.JSON(http.StatusOK, gin.H{"token": apiToken, "user": user, "preferences": preference}) + }) + + stats := api.Group("/stats") + stats.Use(TokenRequired()) + { + stats.GET("/", func(c *gin.Context) { + db := establishDBConnection() + defer db.Close() + + 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") + if err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + defer rows.Close() + + var data []models.Statistic + + for rows.Next() { + var stat models.Statistic + var user models.User + if err := rows.Scan(&stat.Date, &stat.Quantity, &user.UUID, &user.Name); err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + stat.User = user + data = append(data, stat) + } + + + // TODO: return to this and figure out how to best collect the data you are looking for for each user (zach and parker) + rows, err = db.Query("SELECT date(s.date), SUM(s.quantity) as total FROM Statistics s WHERE s.date >= date('now', '-7 days') GROUP BY DATE(s.date)") + if err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + defer rows.Close() + + var dailySummaries []models.DailySummary + for rows.Next() { + var summary models.DailySummary + if err := rows.Scan(&summary.Date, &summary.Total); err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + dailySummaries = append(dailySummaries, summary) + } + + c.JSON(http.StatusOK, gin.H{"stats": data, "totals": dailySummaries}) + rows, err = db.Query("SELECT s.date, SUM(s.quantity) as total, u.uuid, u.name FROM Statistics s INNER JOIN Users u ON u.id = s.user_id WHERE s.date >= date('now', '-7 days') GROUP BY s.date, s.user_id") + + if err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + defer rows.Close() + + var totals []interface{} + for rows.Next() { + var stat models.Statistic + var user models.User + if err := rows.Scan(&stat.Date, &stat.Quantity, &user.UUID, &user.Name); err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + stat.User = user + totals = append(totals, stat) + } + + c.JSON(http.StatusOK, gin.H{"stats": data, "totals": totals}) + }) + + stats.POST("/", func(c *gin.Context) { + var stat models.Statistic + + if err := c.BindJSON(&stat); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + db := establishDBConnection() + defer db.Close() + + result, err := db.Exec("INSERT INTO statistics (date, user_id, quantity) values (?, ?, ?)", stat.Date, 1, stat.Quantity) + + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + } + + id, err := result.LastInsertId() + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + } + + c.JSON(http.StatusCreated, gin.H{"status": "created", "id": id}) + }) + + stats.GET("/totals/", func(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"status": "ok"}) + }) + + // stats.GET("/totals/", func(c *gin.Context) { + // db := establishDBConnection() + // defer db.Close() + // + // rows, err := db.Query("SELECT s.date, SUM(s.quantity) as total, u.uuid, u.name FROM Statistics s INNER JOIN Users u ON u.id = s.user_id WHERE s.date >= date('now', '-7 days') GROUP BY s.date, s.user_id") + // + // if err != nil { + // c.JSON(500, gin.H{"error": err.Error()}) + // return + // } + // defer rows.Close() + // + // var data []models.Statistic + // for rows.Next() { + // var stat models.Statistic + // var user models.User + // if err := rows.Scan(&stat.Date, &stat.Quantity, &user.UUID, &user.Name); err != nil { + // c.JSON(500, gin.H{"error": err.Error()}) + // return + // } + // stat.User = user + // data = append(data, stat) + // } + // + // c.JSON(http.StatusOK, data) + // + // }) + + stats.GET("user/:uuid", func(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"status": "ok", "uuid": c.Param("uuid")}) + }) + + stats.PATCH("user/:uuid", func(c *gin.Context) { + c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) + }) + + stats.DELETE("user/:uuid", func(c *gin.Context) { + c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) + }) + } return r } -- cgit v1.1 From 5fa57845052655883120ba4d19a85d8756fb8d8c Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Wed, 6 Mar 2024 21:53:07 -0500 Subject: [FEAT] Refactor API main file and models This commit refactors the `main.go` file in the API directory, as well as the related models in the `models.go` file. The changes include: - Reordering imports and removing unnecessary imports - Fixing error messages to be more descriptive - Handling database connections more efficiently with deferred closures - Handling errors and returning appropriate error responses - Adding proper JSON bindings for POST requests - Adding new views in the database scripts for aggregated statistics and daily user statistics No changes were made to imports and requires. --- api/lib/models.go | 41 ----------- api/main.go | 215 ++++++++++++++++++++++++++++++------------------------ api/models.go | 57 +++++++++++++++ 3 files changed, 178 insertions(+), 135 deletions(-) delete mode 100644 api/lib/models.go create mode 100644 api/models.go (limited to 'api') diff --git a/api/lib/models.go b/api/lib/models.go deleted file mode 100644 index f959519..0000000 --- a/api/lib/models.go +++ /dev/null @@ -1,41 +0,0 @@ -package models - -import ( - "time" - "github.com/google/uuid" -) - -type Statistic struct { - ID int64 `json:"-"` - Date time.Time `json:"date"` - User User `json:"user"` - Quantity int `json:"quantity"` -} - -type User struct { - ID int64 `json:"-"` - Name string `json:"name"` - UUID uuid.UUID `json:"uuid"` - Password string `json:"-"` -} - -type Token struct { - ID int64 `json:"-"` - UserID int64 `json:"user_id"` - Token string `json:"token"` - CreatedAt time.Time `json:"created_at"` - ExpiredAt time.Time `json:"expired_at"` -} - -type Preference struct { - ID int64 `json:"-"` - Color string `json:"color"` - UserID int64 `json:"-"` - Size Size `json:"size"` -} - -type Size struct { - ID int64 `json:"-"` - Size int64 `json:"size"` - Unit string `json:"unit"` -} diff --git a/api/main.go b/api/main.go index 57feb09..17a3c3a 100644 --- a/api/main.go +++ b/api/main.go @@ -1,18 +1,17 @@ package main import ( - "net/http" "crypto/rand" - "encoding/base64" "database/sql" - "strings" + "encoding/base64" "errors" "log" + "net/http" + "strings" "github.com/gin-gonic/gin" _ "github.com/mattn/go-sqlite3" "golang.org/x/crypto/bcrypt" - "water/api/lib" ) func CORSMiddleware() gin.HandlerFunc { @@ -22,15 +21,12 @@ func CORSMiddleware() gin.HandlerFunc { 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") - log.Println("I am here") - if c.Request.Method == "OPTIONS" { log.Println(c.Request.Header) - c.AbortWithStatus(204) + c.AbortWithStatus(http.StatusNoContent) return } - log.Println(c.Request.Header) c.Next() } } @@ -38,7 +34,10 @@ func CORSMiddleware() gin.HandlerFunc { // generatToken will g func generateToken() string { token := make([]byte, 32) - rand.Read(token) + _, err := rand.Read(token) + if err != nil { + return "" + } return base64.StdEncoding.EncodeToString(token) } @@ -53,13 +52,13 @@ func establishDBConnection() *sql.DB { func checkForTokenInContext(c *gin.Context) (string, error) { authorizationHeader := c.GetHeader("Authorization") if authorizationHeader == "" { - return "", errors.New("Authorization header is missing") + 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 "", errors.New("invalid Authorization header format") } return parts[1], nil @@ -98,15 +97,21 @@ func setupRouter() *gin.Engine { } db := establishDBConnection() - defer db.Close() + 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 - var size models.Size + var user User + var preference Preference + var size Size row := db.QueryRow("SELECT name, uuid, password, color, size, unit FROM Users u INNER JOIN Preferences p ON p.user_id = u.id INNER JOIN Sizes s ON p.size_id = s.id WHERE u.name = ?", username) if err := row.Scan(&user.Name, &user.UUID, &user.Password, &preference.Color, &size.Size, &size.Unit); err != nil { - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { c.AbortWithStatus(http.StatusUnauthorized) return } @@ -129,128 +134,147 @@ func setupRouter() *gin.Engine { { stats.GET("/", func(c *gin.Context) { db := establishDBConnection() - defer db.Close() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(db) 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") if err != nil { - c.JSON(500, gin.H{"error": err.Error()}) + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - defer rows.Close() + defer func(rows *sql.Rows) { + err := rows.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(rows) - var data []models.Statistic + var data []Statistic for rows.Next() { - var stat models.Statistic - var user models.User + var stat Statistic + var user User if err := rows.Scan(&stat.Date, &stat.Quantity, &user.UUID, &user.Name); err != nil { - c.JSON(500, gin.H{"error": err.Error()}) + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } stat.User = user data = append(data, stat) } + c.JSON(http.StatusOK, data) + }) - // TODO: return to this and figure out how to best collect the data you are looking for for each user (zach and parker) - rows, err = db.Query("SELECT date(s.date), SUM(s.quantity) as total FROM Statistics s WHERE s.date >= date('now', '-7 days') GROUP BY DATE(s.date)") - if err != nil { - c.JSON(500, gin.H{"error": err.Error()}) + stats.POST("/", func(c *gin.Context) { + var stat StatisticPost + + if err := c.BindJSON(&stat); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - defer rows.Close() - var dailySummaries []models.DailySummary - for rows.Next() { - var summary models.DailySummary - if err := rows.Scan(&summary.Date, &summary.Total); err != nil { - c.JSON(500, gin.H{"error": err.Error()}) + db := establishDBConnection() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - dailySummaries = append(dailySummaries, summary) - } + }(db) - c.JSON(http.StatusOK, gin.H{"stats": data, "totals": dailySummaries}) - rows, err = db.Query("SELECT s.date, SUM(s.quantity) as total, u.uuid, u.name FROM Statistics s INNER JOIN Users u ON u.id = s.user_id WHERE s.date >= date('now', '-7 days') GROUP BY s.date, s.user_id") + result, err := db.Exec("INSERT INTO statistics (date, user_id, quantity) values (?, ?, ?)", stat.Date, stat.UserID, stat.Quantity) if err != nil { - c.JSON(500, gin.H{"error": err.Error()}) - return + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } - defer rows.Close() - var totals []interface{} - for rows.Next() { - var stat models.Statistic - var user models.User - if err := rows.Scan(&stat.Date, &stat.Quantity, &user.UUID, &user.Name); err != nil { - c.JSON(500, gin.H{"error": err.Error()}) - return - } - stat.User = user - totals = append(totals, stat) + id, err := result.LastInsertId() + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } - c.JSON(http.StatusOK, gin.H{"stats": data, "totals": totals}) + c.JSON(http.StatusCreated, gin.H{"status": "created", "id": id}) }) - stats.POST("/", func(c *gin.Context) { - var stat models.Statistic + stats.GET("weekly/", func(c *gin.Context) { + db := establishDBConnection() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(db) - if err := c.BindJSON(&stat); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + rows, err := db.Query("SELECT date, total FROM `WeeklyStatisticsView`") + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } + defer func(rows *sql.Rows) { + err := rows.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(rows) + + var data []WeeklyStatistic + for rows.Next() { + var weeklyStat WeeklyStatistic + if err := rows.Scan(&weeklyStat.Date, &weeklyStat.Total); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } + data = append(data, weeklyStat) + } + + c.JSON(http.StatusOK, data) + }) + stats.GET("totals/", func(c *gin.Context) { db := establishDBConnection() - defer db.Close() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(db) - result, err := db.Exec("INSERT INTO statistics (date, user_id, quantity) values (?, ?, ?)", stat.Date, 1, stat.Quantity) + rows, err := db.Query("SELECT name, total FROM DailyUserStatistics") if err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return } + defer func(rows *sql.Rows) { + err := rows.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(rows) - id, err := result.LastInsertId() - if err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + var data []DailyUserTotals + for rows.Next() { + var stat DailyUserTotals + if err := rows.Scan(&stat.Name, &stat.Total); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + data = append(data, stat) } - c.JSON(http.StatusCreated, gin.H{"status": "created", "id": id}) - }) + c.JSON(http.StatusOK, data) - stats.GET("/totals/", func(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"status": "ok"}) }) - // stats.GET("/totals/", func(c *gin.Context) { - // db := establishDBConnection() - // defer db.Close() - // - // rows, err := db.Query("SELECT s.date, SUM(s.quantity) as total, u.uuid, u.name FROM Statistics s INNER JOIN Users u ON u.id = s.user_id WHERE s.date >= date('now', '-7 days') GROUP BY s.date, s.user_id") - // - // if err != nil { - // c.JSON(500, gin.H{"error": err.Error()}) - // return - // } - // defer rows.Close() - // - // var data []models.Statistic - // for rows.Next() { - // var stat models.Statistic - // var user models.User - // if err := rows.Scan(&stat.Date, &stat.Quantity, &user.UUID, &user.Name); err != nil { - // c.JSON(500, gin.H{"error": err.Error()}) - // return - // } - // stat.User = user - // data = append(data, stat) - // } - // - // c.JSON(http.StatusOK, data) - // - // }) - stats.GET("user/:uuid", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"status": "ok", "uuid": c.Param("uuid")}) }) @@ -270,5 +294,8 @@ func setupRouter() *gin.Engine { func main() { r := setupRouter() // Listen and Server in 0.0.0.0:8080 - r.Run(":8080") + err := r.Run(":8080") + if err != nil { + return + } } diff --git a/api/models.go b/api/models.go new file mode 100644 index 0000000..0845d1d --- /dev/null +++ b/api/models.go @@ -0,0 +1,57 @@ +package main + +import ( + "time" + "github.com/google/uuid" +) + +type Statistic struct { + ID int64 `json:"-"` + Date time.Time `json:"date"` + User User `json:"user"` + Quantity int `json:"quantity"` +} + +type StatisticPost struct { + Date time.Time `json:"date"` + Quantity int64 `json:"quantity"` + UserID int64 `json:"user_id"` +} + +type User struct { + ID int64 `json:"-"` + Name string `json:"name"` + UUID uuid.UUID `json:"uuid"` + Password string `json:"-"` +} + +type Token struct { + ID int64 `json:"-"` + UserID int64 `json:"user_id"` + Token string `json:"token"` + CreatedAt time.Time `json:"created_at"` + ExpiredAt time.Time `json:"expired_at"` +} + +type Preference struct { + ID int64 `json:"-"` + Color string `json:"color"` + UserID int64 `json:"-"` + Size Size `json:"size"` +} + +type Size struct { + ID int64 `json:"-"` + Size int64 `json:"size"` + Unit string `json:"unit"` +} + +type WeeklyStatistic struct { + Date string `json:"date"` + Total int64 `json:"total"` +} + +type DailyUserTotals struct { + Name string `json:"name"` + Total int64 `json:"total"` +} \ No newline at end of file -- cgit v1.1 From 6651daca670664f3de8af9c7bcb74b1e7c6c6be9 Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Thu, 7 Mar 2024 19:16:07 -0500 Subject: Add CORS middleware and authentication middleware to the API server. The `setupRouter` function in `main.go` now includes a CORS middleware and a token authentication middleware. The CORS middleware allows cross-origin resource sharing by setting the appropriate response headers. The token authentication middleware checks for the presence of an `Authorization` header with a valid bearer token. If the token is missing or invalid, an unauthorized response is returned. In addition to these changes, a new test file `main_test.go` has been added to test the `/api/v1/auth` route. This test suite includes two test cases: one for successful authentication and one for failed authentication. Update go.mod to include new dependencies. The `go.mod` file has been modified to include two new dependencies: `github.com/spf13/viper` and `github.com/stretchr/testify`. Ignore go.sum changes. Ignore changes in the `go.sum` file, as they only include updates to existing dependencies. --- api/cmd/main.go | 104 +++++++++++++ api/cmd/main_test.go | 56 +++++++ api/go.mod | 19 +++ api/go.sum | 47 +++++- api/internal/controllers/auth.go | 66 ++++++++ api/internal/controllers/stats.go | 164 ++++++++++++++++++++ api/internal/controllers/user.go | 17 +++ api/internal/database/database.go | 22 +++ api/internal/models/auth.go | 11 ++ api/internal/models/preferences.go | 14 ++ api/internal/models/statistics.go | 26 ++++ api/internal/models/user.go | 10 ++ api/main.go | 301 ------------------------------------- api/models.go | 57 ------- 14 files changed, 551 insertions(+), 363 deletions(-) create mode 100644 api/cmd/main.go create mode 100644 api/cmd/main_test.go create mode 100644 api/internal/controllers/auth.go create mode 100644 api/internal/controllers/stats.go create mode 100644 api/internal/controllers/user.go create mode 100644 api/internal/database/database.go create mode 100644 api/internal/models/auth.go create mode 100644 api/internal/models/preferences.go create mode 100644 api/internal/models/statistics.go create mode 100644 api/internal/models/user.go delete mode 100644 api/main.go delete mode 100644 api/models.go (limited to 'api') diff --git a/api/cmd/main.go b/api/cmd/main.go new file mode 100644 index 0000000..1924556 --- /dev/null +++ b/api/cmd/main.go @@ -0,0 +1,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 + } +} diff --git a/api/cmd/main_test.go b/api/cmd/main_test.go new file mode 100644 index 0000000..8d0df8d --- /dev/null +++ b/api/cmd/main_test.go @@ -0,0 +1,56 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" + "net/http/httptest" + "testing" + + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" +) + +func getTestUserCredentials() (string, string) { + viper.SetConfigName(".env") + viper.AddConfigPath(".") + err := viper.ReadInConfig() + if err != nil { + log.Fatalf("Error while reading config file %s", err) + } + + testUser := viper.GetString("TEST_USER") + testPass := viper.GetString("TEST_PASS") + return testUser, testPass +} + +func TestAuthRoute(t *testing.T) { + router := setupRouter() + + username, password := getTestUserCredentials() + + w := httptest.NewRecorder() + req, _ := http.NewRequest("POST", "/api/v1/auth", nil) + req.SetBasicAuth(username, password) + router.ServeHTTP(w, req) + + assert.Equal(t, http.StatusOK, w.Code, "response should return a 200 code") + + var response map[string]interface{} + _ = json.Unmarshal(w.Body.Bytes(), &response) + _, exists := response["token"] + assert.True(t, exists, "response should return a token") +} + +func TestAuthRouteFailure(t *testing.T) { + router := setupRouter() + + w := httptest.NewRecorder() + req, _ := http.NewRequest("POST", "/api/v1/auth", nil) + req.SetBasicAuth("asdf", "asdf") + router.ServeHTTP(w, req) + + assert.Equal(t, http.StatusUnauthorized, w.Code, "should return a 401 code") +} + +func Test \ No newline at end of file diff --git a/api/go.mod b/api/go.mod index 6a326bc..6c414bc 100644 --- a/api/go.mod +++ b/api/go.mod @@ -6,6 +6,8 @@ require ( github.com/gin-gonic/gin v1.9.1 github.com/google/uuid v1.6.0 github.com/mattn/go-sqlite3 v1.14.22 + github.com/spf13/viper v1.18.2 + github.com/stretchr/testify v1.8.4 golang.org/x/crypto v0.19.0 ) @@ -13,25 +15,42 @@ require ( github.com/bytedance/sonic v1.11.0 // indirect github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect github.com/chenzhuoyu/iasm v0.9.1 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect github.com/gin-contrib/sse v0.1.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.18.0 // indirect github.com/goccy/go-json v0.10.2 // indirect + github.com/hashicorp/hcl v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.2.6 // indirect github.com/leodido/go-urn v1.4.0 // indirect + github.com/magiconair/properties v1.8.7 // indirect github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.1.1 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/sagikazarmark/locafero v0.4.0 // indirect + github.com/sagikazarmark/slog-shim v0.1.0 // indirect + github.com/sourcegraph/conc v0.3.0 // indirect + github.com/spf13/afero v1.11.0 // indirect + github.com/spf13/cast v1.6.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/subosito/gotenv v1.6.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect + go.uber.org/atomic v1.9.0 // indirect + go.uber.org/multierr v1.9.0 // indirect golang.org/x/arch v0.7.0 // indirect + golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect golang.org/x/net v0.21.0 // indirect golang.org/x/sys v0.17.0 // indirect golang.org/x/text v0.14.0 // indirect google.golang.org/protobuf v1.32.0 // indirect + gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/api/go.sum b/api/go.sum index 115a832..20771f7 100644 --- a/api/go.sum +++ b/api/go.sum @@ -10,8 +10,12 @@ github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLI github.com/chenzhuoyu/iasm v0.9.1 h1:tUHQJXo3NhBqw6s33wkGn9SP3bvrWLdlVIJ3hQBL7P0= github.com/chenzhuoyu/iasm v0.9.1/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= @@ -27,22 +31,30 @@ github.com/go-playground/validator/v10 v10.18.0 h1:BvolUXjp4zuvkZ5YN5t7ebzbhlUtP github.com/go-playground/validator/v10 v10.18.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= -github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc= github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= +github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -50,8 +62,24 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI= github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= +github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= +github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= +github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= +github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= +github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= +github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= +github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= +github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= +github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ= +github.com/spf13/viper v1.18.2/go.mod h1:EKmWIqdnk5lOcmR72yw6hS+8OPYcwD0jteitLMVB+yk= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -62,15 +90,23 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= +go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= +go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc= golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g= +golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k= golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -79,11 +115,12 @@ golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I= google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/api/internal/controllers/auth.go b/api/internal/controllers/auth.go new file mode 100644 index 0000000..744a884 --- /dev/null +++ b/api/internal/controllers/auth.go @@ -0,0 +1,66 @@ +package controllers + +import ( + "encoding/base64" + "net/http" + "github.com/gin-gonic/gin" + "water/api/database" + "errors" + "crypto/rand" + "database/sql" + + "water/api/models" + _ "github.com/mattn/go-sqlite3" + "golang.org/x/crypto/bcrypt" +) + +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 := database.EstablishDBConnection() + 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 + var size models.Size + + row := db.QueryRow("SELECT name, uuid, password, color, size, unit FROM Users u INNER JOIN Preferences p ON p.user_id = u.id INNER JOIN Sizes s ON p.size_id = s.id WHERE u.name = ?", username) + if err := row.Scan(&user.Name, &user.UUID, &user.Password, &preference.Color, &size.Size, &size.Unit); err != nil { + if errors.Is(err, sql.ErrNoRows) { + c.AbortWithStatus(http.StatusUnauthorized) + return + } + } + + if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { + c.AbortWithStatus(http.StatusUnauthorized) + return + } + + preference.Size = size + + // Generate a simple API token + apiToken := generateToken() + c.JSON(http.StatusOK, gin.H{"token": apiToken, "user": user, "preferences": preference}) +} + +// generatToken will g +func generateToken() string { + token := make([]byte, 32) + _, err := rand.Read(token) + if err != nil { + return "" + } + return base64.StdEncoding.EncodeToString(token) +} \ No newline at end of file diff --git a/api/internal/controllers/stats.go b/api/internal/controllers/stats.go new file mode 100644 index 0000000..9808ace --- /dev/null +++ b/api/internal/controllers/stats.go @@ -0,0 +1,164 @@ +package controllers + +import ( + "database/sql" + "github.com/gin-gonic/gin" + "net/http" + "water/api/database" + "water/api/models" +) + +func GetAllStatistics(c *gin.Context) { + db := database.EstablishDBConnection() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(db) + + 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") + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + defer func(rows *sql.Rows) { + err := rows.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(rows) + + var data []models.Statistic + + for rows.Next() { + var stat models.Statistic + var user models.User + if err := rows.Scan(&stat.Date, &stat.Quantity, &user.UUID, &user.Name); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + stat.User = user + data = append(data, stat) + } + + c.JSON(http.StatusOK, data) +} + +func PostNewStatistic(c *gin.Context) { + var stat models.StatisticPost + + if err := c.BindJSON(&stat); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + db := database.EstablishDBConnection() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(db) + + result, err := db.Exec("INSERT INTO statistics (date, user_id, quantity) values (?, ?, ?)", stat.Date, stat.UserID, stat.Quantity) + + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + } + + id, err := result.LastInsertId() + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + } + + c.JSON(http.StatusCreated, gin.H{"status": "created", "id": id}) +} + +func GetWeeklyStatistics (c *gin.Context) { + db := database.EstablishDBConnection() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(db) + + rows, err := db.Query("SELECT date, total FROM `WeeklyStatisticsView`") + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + defer func(rows *sql.Rows) { + err := rows.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(rows) + + var data []models.WeeklyStatistic + for rows.Next() { + var weeklyStat models.WeeklyStatistic + if err := rows.Scan(&weeklyStat.Date, &weeklyStat.Total); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } + data = append(data, weeklyStat) + } + + c.JSON(http.StatusOK, data) +} + +func GetDailyUserStatistics(c *gin.Context) { + db := database.EstablishDBConnection() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(db) + + rows, err := db.Query("SELECT name, total FROM DailyUserStatistics") + + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + defer func(rows *sql.Rows) { + err := rows.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(rows) + + var data []models.DailyUserTotals + for rows.Next() { + var stat models.DailyUserTotals + if err := rows.Scan(&stat.Name, &stat.Total); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + data = append(data, stat) + } + + c.JSON(http.StatusOK, data) + +} + +func GetUserStatistics(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"status": "ok", "uuid": c.Param("uuid")}) +} + +func UpdateUserStatistic(c *gin.Context) { + c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) +} + +func DeleteUserStatistic(c *gin.Context) { + c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) +} diff --git a/api/internal/controllers/user.go b/api/internal/controllers/user.go new file mode 100644 index 0000000..1f3f813 --- /dev/null +++ b/api/internal/controllers/user.go @@ -0,0 +1,17 @@ +package controllers + +import ( + "net/http" + "github.com/gin-gonic/gin" +) + +func GetUser(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"message": "User found"}) +} +func GetUserPreferences(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"message": "Preferences fetched successfully"}) +} + +func UpdateUserPreferences(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"message": "Preferences updated successfully"}) +} \ No newline at end of file diff --git a/api/internal/database/database.go b/api/internal/database/database.go new file mode 100644 index 0000000..e313af5 --- /dev/null +++ b/api/internal/database/database.go @@ -0,0 +1,22 @@ +package database + +import ( + "database/sql" + _ "github.com/mattn/go-sqlite3" + "log" +) + +func SetupDatabase() { + _, err := sql.Open("sqlite3", "water.db") + if err != nil { + log.Fatal(err) + } +} + +func EstablishDBConnection() *sql.DB { + db, err := sql.Open("sqlite3", "../db/water.sqlite3") + if err != nil { + panic(err) + } + return db +} \ No newline at end of file diff --git a/api/internal/models/auth.go b/api/internal/models/auth.go new file mode 100644 index 0000000..41344d5 --- /dev/null +++ b/api/internal/models/auth.go @@ -0,0 +1,11 @@ +package models + +import "time" + +type Token struct { + ID int64 `json:"-"` + UserID int64 `json:"user_id"` + Token string `json:"token"` + CreatedAt time.Time `json:"created_at"` + ExpiredAt time.Time `json:"expired_at"` +} diff --git a/api/internal/models/preferences.go b/api/internal/models/preferences.go new file mode 100644 index 0000000..cbbd47c --- /dev/null +++ b/api/internal/models/preferences.go @@ -0,0 +1,14 @@ +package models + +type Preference struct { + ID int64 `json:"-"` + Color string `json:"color"` + UserID int64 `json:"-"` + Size Size `json:"size"` +} + +type Size struct { + ID int64 `json:"-"` + Size int64 `json:"size"` + Unit string `json:"unit"` +} diff --git a/api/internal/models/statistics.go b/api/internal/models/statistics.go new file mode 100644 index 0000000..457e6a0 --- /dev/null +++ b/api/internal/models/statistics.go @@ -0,0 +1,26 @@ +package models + +import "time" + +type Statistic struct { + ID int64 `json:"-"` + Date time.Time `json:"date"` + User User `json:"user"` + Quantity int `json:"quantity"` +} + +type StatisticPost struct { + Date time.Time `json:"date"` + Quantity int64 `json:"quantity"` + UserID int64 `json:"user_id"` +} + +type WeeklyStatistic struct { + Date string `json:"date"` + Total int64 `json:"total"` +} + +type DailyUserTotals struct { + Name string `json:"name"` + Total int64 `json:"total"` +} diff --git a/api/internal/models/user.go b/api/internal/models/user.go new file mode 100644 index 0000000..2a3e6fd --- /dev/null +++ b/api/internal/models/user.go @@ -0,0 +1,10 @@ +package models + +import "github.com/google/uuid" + +type User struct { + ID int64 `json:"-"` + Name string `json:"name"` + UUID uuid.UUID `json:"uuid"` + Password string `json:"-"` +} diff --git a/api/main.go b/api/main.go deleted file mode 100644 index 17a3c3a..0000000 --- a/api/main.go +++ /dev/null @@ -1,301 +0,0 @@ -package main - -import ( - "crypto/rand" - "database/sql" - "encoding/base64" - "errors" - "log" - "net/http" - "strings" - - "github.com/gin-gonic/gin" - _ "github.com/mattn/go-sqlite3" - "golang.org/x/crypto/bcrypt" -) - -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() - } -} - -// generatToken will g -func generateToken() string { - token := make([]byte, 32) - _, err := rand.Read(token) - if err != nil { - return "" - } - return base64.StdEncoding.EncodeToString(token) -} - -func establishDBConnection() *sql.DB { - db, err := sql.Open("sqlite3", "../db/water.sqlite3") - if err != nil { - panic(err) - } - return db -} - -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", func(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 := establishDBConnection() - defer func(db *sql.DB) { - err := db.Close() - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - }(db) - - var user User - var preference Preference - var size Size - - row := db.QueryRow("SELECT name, uuid, password, color, size, unit FROM Users u INNER JOIN Preferences p ON p.user_id = u.id INNER JOIN Sizes s ON p.size_id = s.id WHERE u.name = ?", username) - if err := row.Scan(&user.Name, &user.UUID, &user.Password, &preference.Color, &size.Size, &size.Unit); err != nil { - if errors.Is(err, sql.ErrNoRows) { - c.AbortWithStatus(http.StatusUnauthorized) - return - } - } - - if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { - c.AbortWithStatus(http.StatusUnauthorized) - return - } - - preference.Size = size - - // Generate a simple API token - apiToken := generateToken() - c.JSON(http.StatusOK, gin.H{"token": apiToken, "user": user, "preferences": preference}) - }) - - stats := api.Group("/stats") - stats.Use(TokenRequired()) - { - stats.GET("/", func(c *gin.Context) { - db := establishDBConnection() - defer func(db *sql.DB) { - err := db.Close() - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - }(db) - - 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") - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - defer func(rows *sql.Rows) { - err := rows.Close() - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - }(rows) - - var data []Statistic - - for rows.Next() { - var stat Statistic - var user User - if err := rows.Scan(&stat.Date, &stat.Quantity, &user.UUID, &user.Name); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - stat.User = user - data = append(data, stat) - } - - c.JSON(http.StatusOK, data) - }) - - stats.POST("/", func(c *gin.Context) { - var stat StatisticPost - - if err := c.BindJSON(&stat); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - return - } - - db := establishDBConnection() - defer func(db *sql.DB) { - err := db.Close() - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - }(db) - - result, err := db.Exec("INSERT INTO statistics (date, user_id, quantity) values (?, ?, ?)", stat.Date, stat.UserID, stat.Quantity) - - if err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - } - - id, err := result.LastInsertId() - if err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - } - - c.JSON(http.StatusCreated, gin.H{"status": "created", "id": id}) - }) - - stats.GET("weekly/", func(c *gin.Context) { - db := establishDBConnection() - defer func(db *sql.DB) { - err := db.Close() - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - }(db) - - rows, err := db.Query("SELECT date, total FROM `WeeklyStatisticsView`") - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - defer func(rows *sql.Rows) { - err := rows.Close() - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - }(rows) - - var data []WeeklyStatistic - for rows.Next() { - var weeklyStat WeeklyStatistic - if err := rows.Scan(&weeklyStat.Date, &weeklyStat.Total); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - } - data = append(data, weeklyStat) - } - - c.JSON(http.StatusOK, data) - }) - - stats.GET("totals/", func(c *gin.Context) { - db := establishDBConnection() - defer func(db *sql.DB) { - err := db.Close() - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - }(db) - - rows, err := db.Query("SELECT name, total FROM DailyUserStatistics") - - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - defer func(rows *sql.Rows) { - err := rows.Close() - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - }(rows) - - var data []DailyUserTotals - for rows.Next() { - var stat DailyUserTotals - if err := rows.Scan(&stat.Name, &stat.Total); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - data = append(data, stat) - } - - c.JSON(http.StatusOK, data) - - }) - - stats.GET("user/:uuid", func(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"status": "ok", "uuid": c.Param("uuid")}) - }) - - stats.PATCH("user/:uuid", func(c *gin.Context) { - c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) - }) - - stats.DELETE("user/:uuid", func(c *gin.Context) { - c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) - }) - } - - return r -} - -func main() { - r := setupRouter() - // Listen and Server in 0.0.0.0:8080 - err := r.Run(":8080") - if err != nil { - return - } -} diff --git a/api/models.go b/api/models.go deleted file mode 100644 index 0845d1d..0000000 --- a/api/models.go +++ /dev/null @@ -1,57 +0,0 @@ -package main - -import ( - "time" - "github.com/google/uuid" -) - -type Statistic struct { - ID int64 `json:"-"` - Date time.Time `json:"date"` - User User `json:"user"` - Quantity int `json:"quantity"` -} - -type StatisticPost struct { - Date time.Time `json:"date"` - Quantity int64 `json:"quantity"` - UserID int64 `json:"user_id"` -} - -type User struct { - ID int64 `json:"-"` - Name string `json:"name"` - UUID uuid.UUID `json:"uuid"` - Password string `json:"-"` -} - -type Token struct { - ID int64 `json:"-"` - UserID int64 `json:"user_id"` - Token string `json:"token"` - CreatedAt time.Time `json:"created_at"` - ExpiredAt time.Time `json:"expired_at"` -} - -type Preference struct { - ID int64 `json:"-"` - Color string `json:"color"` - UserID int64 `json:"-"` - Size Size `json:"size"` -} - -type Size struct { - ID int64 `json:"-"` - Size int64 `json:"size"` - Unit string `json:"unit"` -} - -type WeeklyStatistic struct { - Date string `json:"date"` - Total int64 `json:"total"` -} - -type DailyUserTotals struct { - Name string `json:"name"` - Total int64 `json:"total"` -} \ No newline at end of file -- cgit v1.1 From 29f83e05270d0012ad9f273ac3364106fcff5f50 Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Thu, 7 Mar 2024 19:56:34 -0500 Subject: chore: Update paths in test and database configuration This commit updates the paths in the test suite and database configuration to reflect the new directory structure. In the `api/cmd/main_test.go` file, the path for the config file is changed from `viper.SetConfigName(".env")` to `viper.SetConfigFile("../.env")` and `viper.AddConfigPath(".")` is added for configuration purposes. Additionally, `viper.AutomaticEnv()` is added to enable automatic environment variable configuration. In the same file, error handling is improved by adding explicit checks and error messages. The `api/internal/database/database.go` file is also modified, updating the path for database initialization from `"../db/water.sqlite3"` to `"../../db/water.sqlite3"`. These changes ensure proper configuration and functioning of the application. --- api/cmd/main_test.go | 21 ++++++++++++++++----- api/internal/controllers/auth.go | 14 +++++++------- api/internal/controllers/stats.go | 4 ++-- api/internal/controllers/user.go | 2 +- api/internal/database/database.go | 2 +- 5 files changed, 27 insertions(+), 16 deletions(-) (limited to 'api') diff --git a/api/cmd/main_test.go b/api/cmd/main_test.go index 8d0df8d..a6c8381 100644 --- a/api/cmd/main_test.go +++ b/api/cmd/main_test.go @@ -12,8 +12,9 @@ import ( ) func getTestUserCredentials() (string, string) { - viper.SetConfigName(".env") + viper.SetConfigFile("../.env") viper.AddConfigPath(".") + viper.AutomaticEnv() err := viper.ReadInConfig() if err != nil { log.Fatalf("Error while reading config file %s", err) @@ -29,17 +30,29 @@ func TestAuthRoute(t *testing.T) { username, password := getTestUserCredentials() + log.Println("username", username) + log.Println("password", password) + w := httptest.NewRecorder() - req, _ := http.NewRequest("POST", "/api/v1/auth", nil) + req, err := http.NewRequest("POST", "/api/v1/auth", nil) + if err != nil { + t.Fatalf("Failed to create request: %v", err) + } req.SetBasicAuth(username, password) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code, "response should return a 200 code") var response map[string]interface{} - _ = json.Unmarshal(w.Body.Bytes(), &response) + err = json.Unmarshal(w.Body.Bytes(), &response) + if err != nil { + t.Fatalf("Failed to unmarshal response: %v", err) + } _, exists := response["token"] assert.True(t, exists, "response should return a token") + if !exists { + t.Fatalf("response did not contain token") + } } func TestAuthRouteFailure(t *testing.T) { @@ -52,5 +65,3 @@ func TestAuthRouteFailure(t *testing.T) { assert.Equal(t, http.StatusUnauthorized, w.Code, "should return a 401 code") } - -func Test \ No newline at end of file diff --git a/api/internal/controllers/auth.go b/api/internal/controllers/auth.go index 744a884..de9ed05 100644 --- a/api/internal/controllers/auth.go +++ b/api/internal/controllers/auth.go @@ -1,17 +1,17 @@ package controllers import ( - "encoding/base64" - "net/http" - "github.com/gin-gonic/gin" - "water/api/database" - "errors" "crypto/rand" "database/sql" - - "water/api/models" + "encoding/base64" + "errors" + "github.com/gin-gonic/gin" + "net/http" + "water/api/internal/models" + _ "github.com/mattn/go-sqlite3" "golang.org/x/crypto/bcrypt" + "water/api/internal/database" ) func AuthHandler (c *gin.Context) { diff --git a/api/internal/controllers/stats.go b/api/internal/controllers/stats.go index 9808ace..d8ed434 100644 --- a/api/internal/controllers/stats.go +++ b/api/internal/controllers/stats.go @@ -4,8 +4,8 @@ import ( "database/sql" "github.com/gin-gonic/gin" "net/http" - "water/api/database" - "water/api/models" + "water/api/internal/database" + "water/api/internal/models" ) func GetAllStatistics(c *gin.Context) { diff --git a/api/internal/controllers/user.go b/api/internal/controllers/user.go index 1f3f813..76dedc8 100644 --- a/api/internal/controllers/user.go +++ b/api/internal/controllers/user.go @@ -1,8 +1,8 @@ package controllers import ( - "net/http" "github.com/gin-gonic/gin" + "net/http" ) func GetUser(c *gin.Context) { diff --git a/api/internal/database/database.go b/api/internal/database/database.go index e313af5..19ae818 100644 --- a/api/internal/database/database.go +++ b/api/internal/database/database.go @@ -14,7 +14,7 @@ func SetupDatabase() { } func EstablishDBConnection() *sql.DB { - db, err := sql.Open("sqlite3", "../db/water.sqlite3") + db, err := sql.Open("sqlite3", "../../db/water.sqlite3") if err != nil { panic(err) } -- cgit v1.1 From 831b6f0167b9c1747d128b4a5a648d4de42ff0a9 Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Thu, 7 Mar 2024 20:20:36 -0500 Subject: Refactor router and middleware packages - Move middleware functions from `main.go` to `middleware.go` in the `middleware` package. - Update import statements in `main.go` and use the `router` package instead of the `controllers` package. ``` Refactor router and middleware packages Move middleware functions from `main.go` to `middleware.go` in the `middleware` package. Update import statements in `main.go` and use the `router` package instead of the `controllers` package. ``` --- api/cmd/main.go | 92 +---------------------------------- api/internal/middleware/middleware.go | 55 +++++++++++++++++++++ api/internal/router/router.go | 42 ++++++++++++++++ 3 files changed, 99 insertions(+), 90 deletions(-) create mode 100644 api/internal/middleware/middleware.go create mode 100644 api/internal/router/router.go (limited to 'api') diff --git a/api/cmd/main.go b/api/cmd/main.go index 1924556..d97c942 100644 --- a/api/cmd/main.go +++ b/api/cmd/main.go @@ -1,101 +1,13 @@ 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" + "water/api/internal/router" ) -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() + r := router.SetupRouter() // Listen and Server in 0.0.0.0:8080 err := r.Run(":8080") if err != nil { diff --git a/api/internal/middleware/middleware.go b/api/internal/middleware/middleware.go new file mode 100644 index 0000000..819f1e5 --- /dev/null +++ b/api/internal/middleware/middleware.go @@ -0,0 +1,55 @@ +package middleware + +import ( + "errors" + "github.com/gin-gonic/gin" + "log" + "net/http" + "strings" +) + +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 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 +} \ No newline at end of file diff --git a/api/internal/router/router.go b/api/internal/router/router.go new file mode 100644 index 0000000..adf96d0 --- /dev/null +++ b/api/internal/router/router.go @@ -0,0 +1,42 @@ +package router + +import ( + "github.com/gin-gonic/gin" + "water/api/internal/controllers" + "water/api/internal/middleware" +) + +func SetupRouter() *gin.Engine { + // Disable Console Color + // gin.DisableConsoleColor() + r := gin.Default() + r.Use(middleware.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(middleware.TokenRequired()) + { + user.GET("", controllers.GetUser) + user.GET("preferences", controllers.GetUserPreferences) + user.PATCH("preferences", controllers.UpdateUserPreferences) + } + + stats := api.Group("/stats") + stats.Use(middleware.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 +} \ No newline at end of file -- cgit v1.1 From 8fab2d03bce82e4dee798ebffb1e93c557f62a4b Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Thu, 7 Mar 2024 23:16:22 -0500 Subject: feat: Update authentication route and add comments to exported members - The authentication route in the API has been updated to use a new router setup function. - Comments have been added to all exported members of the `auth.go` module in the internal controllers package. --- api/cmd/main_test.go | 9 +++++---- api/internal/controllers/auth.go | 11 ++++++++++- api/internal/controllers/stats.go | 6 +++++- api/internal/database/database.go | 4 ++-- 4 files changed, 22 insertions(+), 8 deletions(-) (limited to 'api') diff --git a/api/cmd/main_test.go b/api/cmd/main_test.go index a6c8381..049cf6e 100644 --- a/api/cmd/main_test.go +++ b/api/cmd/main_test.go @@ -6,6 +6,7 @@ import ( "net/http" "net/http/httptest" "testing" + "water/api/internal/router" "github.com/spf13/viper" "github.com/stretchr/testify/assert" @@ -26,7 +27,7 @@ func getTestUserCredentials() (string, string) { } func TestAuthRoute(t *testing.T) { - router := setupRouter() + r := router.SetupRouter() username, password := getTestUserCredentials() @@ -39,7 +40,7 @@ func TestAuthRoute(t *testing.T) { t.Fatalf("Failed to create request: %v", err) } req.SetBasicAuth(username, password) - router.ServeHTTP(w, req) + r.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code, "response should return a 200 code") @@ -56,12 +57,12 @@ func TestAuthRoute(t *testing.T) { } func TestAuthRouteFailure(t *testing.T) { - router := setupRouter() + r := router.SetupRouter() w := httptest.NewRecorder() req, _ := http.NewRequest("POST", "/api/v1/auth", nil) req.SetBasicAuth("asdf", "asdf") - router.ServeHTTP(w, req) + r.ServeHTTP(w, req) assert.Equal(t, http.StatusUnauthorized, w.Code, "should return a 401 code") } diff --git a/api/internal/controllers/auth.go b/api/internal/controllers/auth.go index de9ed05..58653d0 100644 --- a/api/internal/controllers/auth.go +++ b/api/internal/controllers/auth.go @@ -14,6 +14,11 @@ import ( "water/api/internal/database" ) + + +// 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 { @@ -55,7 +60,11 @@ func AuthHandler (c *gin.Context) { c.JSON(http.StatusOK, gin.H{"token": apiToken, "user": user, "preferences": preference}) } -// generatToken will g + +// 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) diff --git a/api/internal/controllers/stats.go b/api/internal/controllers/stats.go index d8ed434..2234787 100644 --- a/api/internal/controllers/stats.go +++ b/api/internal/controllers/stats.go @@ -8,6 +8,10 @@ import ( "water/api/internal/models" ) +// TODO: add comments to all exported members of package. + +// GetAllStatistics connects to the database and queries for all statistics in the database. +// If none have been found it will return an error, otherwise a 200 code is sent along with the list of statistics. func GetAllStatistics(c *gin.Context) { db := database.EstablishDBConnection() defer func(db *sql.DB) { @@ -78,7 +82,7 @@ func PostNewStatistic(c *gin.Context) { c.JSON(http.StatusCreated, gin.H{"status": "created", "id": id}) } -func GetWeeklyStatistics (c *gin.Context) { +func GetWeeklyStatistics(c *gin.Context) { db := database.EstablishDBConnection() defer func(db *sql.DB) { err := db.Close() diff --git a/api/internal/database/database.go b/api/internal/database/database.go index 19ae818..7af9780 100644 --- a/api/internal/database/database.go +++ b/api/internal/database/database.go @@ -7,14 +7,14 @@ import ( ) func SetupDatabase() { - _, err := sql.Open("sqlite3", "water.db") + _, err := sql.Open("sqlite3", "water.sqlite3") if err != nil { log.Fatal(err) } } func EstablishDBConnection() *sql.DB { - db, err := sql.Open("sqlite3", "../../db/water.sqlite3") + db, err := sql.Open("sqlite3", "../db/water.sqlite3") if err != nil { panic(err) } -- cgit v1.1 From 9cae9c1d2a0b4f7fa72f3075541b9ffafe1a7275 Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Fri, 15 Mar 2024 18:49:43 -0400 Subject: Add routes for preference, clean up and add types --- api/internal/controllers/auth.go | 18 ++++++---- api/internal/controllers/preferences.go | 45 +++++++++++++++++++++++++ api/internal/controllers/user.go | 59 ++++++++++++++++++++++++++++++--- api/internal/middleware/middleware.go | 7 ++-- api/internal/models/auth.go | 2 +- api/internal/models/preferences.go | 8 ++--- api/internal/models/statistics.go | 2 +- api/internal/models/user.go | 2 +- api/internal/router/router.go | 5 +-- 9 files changed, 125 insertions(+), 23 deletions(-) create mode 100644 api/internal/controllers/preferences.go (limited to 'api') diff --git a/api/internal/controllers/auth.go b/api/internal/controllers/auth.go index 58653d0..ab2fbbb 100644 --- a/api/internal/controllers/auth.go +++ b/api/internal/controllers/auth.go @@ -38,23 +38,27 @@ func AuthHandler (c *gin.Context) { var user models.User var preference models.Preference - var size models.Size - row := db.QueryRow("SELECT name, uuid, password, color, size, unit FROM Users u INNER JOIN Preferences p ON p.user_id = u.id INNER JOIN Sizes s ON p.size_id = s.id WHERE u.name = ?", username) - if err := row.Scan(&user.Name, &user.UUID, &user.Password, &preference.Color, &size.Size, &size.Unit); err != nil { + 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.AbortWithStatus(http.StatusUnauthorized) + c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) return } } + 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.AbortWithStatus(http.StatusUnauthorized) + c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()}) return } - preference.Size = size - // Generate a simple API token apiToken := generateToken() c.JSON(http.StatusOK, gin.H{"token": apiToken, "user": user, "preferences": preference}) 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 @@ +package controllers + +import ( + "github.com/gin-gonic/gin" + "net/http" + "database/sql" + "water/api/internal/database" + "water/api/internal/models" +) + +func GetSizes(c *gin.Context) { + db := database.EstablishDBConnection() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } + }(db) + + rows, err := db.Query("SELECT id, size, unit FROM Sizes") + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + defer func(rows *sql.Rows) { + err := rows.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(rows) + + var data []models.Size + + for rows.Next() { + var size models.Size + if err := rows.Scan(&size.ID, &size.Size, &size.Unit); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + data = append(data, size) + } + + c.JSON(http.StatusOK, data) +} diff --git a/api/internal/controllers/user.go b/api/internal/controllers/user.go index 76dedc8..dbb09cf 100644 --- a/api/internal/controllers/user.go +++ b/api/internal/controllers/user.go @@ -1,17 +1,68 @@ package controllers import ( - "github.com/gin-gonic/gin" + "database/sql" + "errors" + "log" "net/http" + "water/api/internal/database" + "water/api/internal/models" + + "github.com/gin-gonic/gin" ) func GetUser(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "User found"}) } func GetUserPreferences(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"message": "Preferences fetched successfully"}) + db := database.EstablishDBConnection() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(db) + + var preference models.Preference + + row := db.QueryRow("SELECT id, user_id, color, size_id FROM Preferences WHERE user_id = ?", c.Param("id")) + if err := row.Scan(&preference.ID, &preference.UserID, &preference.Color, &preference.SizeID); 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()}) + return + } + } + + c.JSON(http.StatusOK, preference) } func UpdateUserPreferences(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"message": "Preferences updated successfully"}) -} \ No newline at end of file + db := database.EstablishDBConnection() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(db) + + var newPreferences models.Preference + if err := c.BindJSON(&newPreferences); err != nil { + c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()}) + return + } + + log.Printf("newPreferences: %v", newPreferences) + + _, err := db.Exec("UPDATE Preferences SET color = ?, size_id = ? WHERE id = ?", newPreferences.Color, newPreferences.SizeID, newPreferences.ID) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.Status(http.StatusNoContent) +} diff --git a/api/internal/middleware/middleware.go b/api/internal/middleware/middleware.go index 819f1e5..aa27fb8 100644 --- a/api/internal/middleware/middleware.go +++ b/api/internal/middleware/middleware.go @@ -2,10 +2,11 @@ package middleware import ( "errors" - "github.com/gin-gonic/gin" "log" "net/http" "strings" + + "github.com/gin-gonic/gin" ) func TokenRequired() gin.HandlerFunc { @@ -27,7 +28,7 @@ func CORSMiddleware() gin.HandlerFunc { 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") + c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, PATCH") if c.Request.Method == "OPTIONS" { log.Println(c.Request.Header) @@ -52,4 +53,4 @@ func checkForTokenInContext(c *gin.Context) (string, error) { } return parts[1], nil -} \ No newline at end of file +} diff --git a/api/internal/models/auth.go b/api/internal/models/auth.go index 41344d5..fa7dbe4 100644 --- a/api/internal/models/auth.go +++ b/api/internal/models/auth.go @@ -3,7 +3,7 @@ package models import "time" type Token struct { - ID int64 `json:"-"` + ID int64 `json:"id"` UserID int64 `json:"user_id"` Token string `json:"token"` CreatedAt time.Time `json:"created_at"` diff --git a/api/internal/models/preferences.go b/api/internal/models/preferences.go index cbbd47c..8022099 100644 --- a/api/internal/models/preferences.go +++ b/api/internal/models/preferences.go @@ -1,14 +1,14 @@ package models type Preference struct { - ID int64 `json:"-"` + ID int64 `json:"id"` Color string `json:"color"` - UserID int64 `json:"-"` - Size Size `json:"size"` + UserID int64 `json:"user_id"` + SizeID int64 `json:"size_id"` } type Size struct { - ID int64 `json:"-"` + ID int64 `json:"id"` Size int64 `json:"size"` Unit string `json:"unit"` } diff --git a/api/internal/models/statistics.go b/api/internal/models/statistics.go index 457e6a0..7dceb3a 100644 --- a/api/internal/models/statistics.go +++ b/api/internal/models/statistics.go @@ -3,7 +3,7 @@ package models import "time" type Statistic struct { - ID int64 `json:"-"` + ID int64 `json:"id"` Date time.Time `json:"date"` User User `json:"user"` Quantity int `json:"quantity"` diff --git a/api/internal/models/user.go b/api/internal/models/user.go index 2a3e6fd..ca5daa4 100644 --- a/api/internal/models/user.go +++ b/api/internal/models/user.go @@ -3,7 +3,7 @@ package models import "github.com/google/uuid" type User struct { - ID int64 `json:"-"` + ID int64 `json:"id"` Name string `json:"name"` UUID uuid.UUID `json:"uuid"` Password string `json:"-"` diff --git a/api/internal/router/router.go b/api/internal/router/router.go index adf96d0..3c86b8c 100644 --- a/api/internal/router/router.go +++ b/api/internal/router/router.go @@ -17,13 +17,14 @@ func SetupRouter() *gin.Engine { api := r.Group("api/v1") api.POST("/auth", controllers.AuthHandler) + api.GET("/sizes", middleware.TokenRequired(), controllers.GetSizes) + api.PATCH("/user/preferences", controllers.UpdateUserPreferences) - user := api.Group("/user/:uuid") + user := api.Group("/user/:id") user.Use(middleware.TokenRequired()) { user.GET("", controllers.GetUser) user.GET("preferences", controllers.GetUserPreferences) - user.PATCH("preferences", controllers.UpdateUserPreferences) } stats := api.Group("/stats") -- cgit v1.1 From c4e5776f9e174fe6bf91721649c0541a9fb310ae Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Fri, 15 Mar 2024 21:41:12 -0400 Subject: add env samples, move files --- api/.env.sample | 10 ++++++++++ api/cmd/main.go | 13 +++++++++---- api/internal/config/config.go | 17 +++++++++++++++++ api/internal/database/database.go | 16 +++++++++------- 4 files changed, 45 insertions(+), 11 deletions(-) create mode 100644 api/.env.sample create mode 100644 api/internal/config/config.go (limited to 'api') diff --git a/api/.env.sample b/api/.env.sample new file mode 100644 index 0000000..6e25893 --- /dev/null +++ b/api/.env.sample @@ -0,0 +1,10 @@ +# user for test +TEST_USER=user1 +# test user password +TEST_PASS=12345 +# database path +DB_PATH="path/to/database/file" +# database driver +DB_DRIVER="sqlite3" +# port +PORT=":8080" \ No newline at end of file diff --git a/api/cmd/main.go b/api/cmd/main.go index d97c942..c23eff1 100644 --- a/api/cmd/main.go +++ b/api/cmd/main.go @@ -1,16 +1,21 @@ package main import ( - "water/api/internal/database" + "log" + "water/api/internal/config" "water/api/internal/router" ) func main() { - database.SetupDatabase() + c, err := config.Load() + if err != nil { + log.Fatalf("Error while reading config file %s", err) + } + r := router.SetupRouter() // Listen and Server in 0.0.0.0:8080 - err := r.Run(":8080") + err = r.Run(c.GetString("PORT")) if err != nil { - return + log.Fatal(err) } } diff --git a/api/internal/config/config.go b/api/internal/config/config.go new file mode 100644 index 0000000..1892696 --- /dev/null +++ b/api/internal/config/config.go @@ -0,0 +1,17 @@ +package config + +import ( + "fmt" + "github.com/spf13/viper" +) + +func Load() (*viper.Viper, error) { + v := viper.New() + v.SetConfigFile(".env") + v.AddConfigPath(".") + err := v.ReadInConfig() + if err != nil { + return nil, fmt.Errorf("error reading .env file: %s", err) + } + return v, nil +} \ No newline at end of file diff --git a/api/internal/database/database.go b/api/internal/database/database.go index 7af9780..1866655 100644 --- a/api/internal/database/database.go +++ b/api/internal/database/database.go @@ -4,17 +4,19 @@ import ( "database/sql" _ "github.com/mattn/go-sqlite3" "log" + "path/filepath" + "water/api/internal/config" ) -func SetupDatabase() { - _, err := sql.Open("sqlite3", "water.sqlite3") +func EstablishDBConnection() *sql.DB { + c, err := config.Load() + + driver := c.GetString("DB_DRIVER") + path, err := filepath.Abs(c.GetString("DB_PATH")) if err != nil { - log.Fatal(err) + log.Fatal("There was and error getting the absolute path of the database.") } -} - -func EstablishDBConnection() *sql.DB { - db, err := sql.Open("sqlite3", "../db/water.sqlite3") + db, err := sql.Open(driver, path) if err != nil { panic(err) } -- cgit v1.1 From cc49361bcbf689510035e7bbdcce9d8467a36282 Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Fri, 15 Mar 2024 21:45:01 -0400 Subject: add newline, clean up test --- api/cmd/main_test.go | 10 ++-------- api/internal/config/config.go | 2 +- 2 files changed, 3 insertions(+), 9 deletions(-) (limited to 'api') diff --git a/api/cmd/main_test.go b/api/cmd/main_test.go index 049cf6e..a4db57a 100644 --- a/api/cmd/main_test.go +++ b/api/cmd/main_test.go @@ -8,15 +8,12 @@ import ( "testing" "water/api/internal/router" - "github.com/spf13/viper" "github.com/stretchr/testify/assert" + "water/api/internal/config" ) func getTestUserCredentials() (string, string) { - viper.SetConfigFile("../.env") - viper.AddConfigPath(".") - viper.AutomaticEnv() - err := viper.ReadInConfig() + viper, err := config.Load() if err != nil { log.Fatalf("Error while reading config file %s", err) } @@ -31,9 +28,6 @@ func TestAuthRoute(t *testing.T) { username, password := getTestUserCredentials() - log.Println("username", username) - log.Println("password", password) - w := httptest.NewRecorder() req, err := http.NewRequest("POST", "/api/v1/auth", nil) if err != nil { diff --git a/api/internal/config/config.go b/api/internal/config/config.go index 1892696..d54e40e 100644 --- a/api/internal/config/config.go +++ b/api/internal/config/config.go @@ -14,4 +14,4 @@ func Load() (*viper.Viper, error) { return nil, fmt.Errorf("error reading .env file: %s", err) } return v, nil -} \ No newline at end of file +} -- cgit v1.1 From fd1332a3df191577e91c6d846a8b5db1747099fd Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Fri, 15 Mar 2024 22:00:10 -0400 Subject: cleanup --- api/internal/router/router.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'api') diff --git a/api/internal/router/router.go b/api/internal/router/router.go index 3c86b8c..a71c3e6 100644 --- a/api/internal/router/router.go +++ b/api/internal/router/router.go @@ -30,10 +30,10 @@ func SetupRouter() *gin.Engine { stats := api.Group("/stats") stats.Use(middleware.TokenRequired()) { - stats.GET("/", controllers.GetAllStatistics) - stats.POST("/", controllers.PostNewStatistic) - stats.GET("weekly/", controllers.GetWeeklyStatistics) - stats.GET("daily/", controllers.GetDailyUserStatistics) + 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) -- cgit v1.1