diff options
author | zberwaldt <17715430+zberwaldt@users.noreply.github.com> | 2024-03-15 22:03:11 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-03-15 22:03:11 -0400 |
commit | 6f8cfbd6cc3d5adbda38e74013c68e3d4745766d (patch) | |
tree | b3f045cd06d6622e23441b442e8f3861050ed444 /api | |
parent | fac21fa0a72d4a7f1a01ccd44e3acf9c90fd95bd (diff) | |
parent | fd1332a3df191577e91c6d846a8b5db1747099fd (diff) |
Merge pull request #1 from zberwaldt/staging
Staging to Prod
Diffstat (limited to 'api')
-rw-r--r-- | api/.env.sample | 10 | ||||
-rw-r--r-- | api/cmd/main.go | 21 | ||||
-rw-r--r-- | api/cmd/main_test.go | 62 | ||||
-rw-r--r-- | api/go.mod | 56 | ||||
-rw-r--r-- | api/go.sum | 128 | ||||
-rw-r--r-- | api/internal/config/config.go | 17 | ||||
-rw-r--r-- | api/internal/controllers/auth.go | 79 | ||||
-rw-r--r-- | api/internal/controllers/preferences.go | 45 | ||||
-rw-r--r-- | api/internal/controllers/stats.go | 168 | ||||
-rw-r--r-- | api/internal/controllers/user.go | 68 | ||||
-rw-r--r-- | api/internal/database/database.go | 24 | ||||
-rw-r--r-- | api/internal/middleware/middleware.go | 56 | ||||
-rw-r--r-- | api/internal/models/auth.go | 11 | ||||
-rw-r--r-- | api/internal/models/preferences.go | 14 | ||||
-rw-r--r-- | api/internal/models/statistics.go | 26 | ||||
-rw-r--r-- | api/internal/models/user.go | 10 | ||||
-rw-r--r-- | api/internal/router/router.go | 43 |
17 files changed, 838 insertions, 0 deletions
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 @@ | |||
1 | # user for test | ||
2 | TEST_USER=user1 | ||
3 | # test user password | ||
4 | TEST_PASS=12345 | ||
5 | # database path | ||
6 | DB_PATH="path/to/database/file" | ||
7 | # database driver | ||
8 | DB_DRIVER="sqlite3" | ||
9 | # port | ||
10 | PORT=":8080" \ No newline at end of file | ||
diff --git a/api/cmd/main.go b/api/cmd/main.go new file mode 100644 index 0000000..c23eff1 --- /dev/null +++ b/api/cmd/main.go | |||
@@ -0,0 +1,21 @@ | |||
1 | package main | ||
2 | |||
3 | import ( | ||
4 | "log" | ||
5 | "water/api/internal/config" | ||
6 | "water/api/internal/router" | ||
7 | ) | ||
8 | |||
9 | func main() { | ||
10 | c, err := config.Load() | ||
11 | if err != nil { | ||
12 | log.Fatalf("Error while reading config file %s", err) | ||
13 | } | ||
14 | |||
15 | r := router.SetupRouter() | ||
16 | // Listen and Server in 0.0.0.0:8080 | ||
17 | err = r.Run(c.GetString("PORT")) | ||
18 | if err != nil { | ||
19 | log.Fatal(err) | ||
20 | } | ||
21 | } | ||
diff --git a/api/cmd/main_test.go b/api/cmd/main_test.go new file mode 100644 index 0000000..a4db57a --- /dev/null +++ b/api/cmd/main_test.go | |||
@@ -0,0 +1,62 @@ | |||
1 | package main | ||
2 | |||
3 | import ( | ||
4 | "encoding/json" | ||
5 | "log" | ||
6 | "net/http" | ||
7 | "net/http/httptest" | ||
8 | "testing" | ||
9 | "water/api/internal/router" | ||
10 | |||
11 | "github.com/stretchr/testify/assert" | ||
12 | "water/api/internal/config" | ||
13 | ) | ||
14 | |||
15 | func getTestUserCredentials() (string, string) { | ||
16 | viper, err := config.Load() | ||
17 | if err != nil { | ||
18 | log.Fatalf("Error while reading config file %s", err) | ||
19 | } | ||
20 | |||
21 | testUser := viper.GetString("TEST_USER") | ||
22 | testPass := viper.GetString("TEST_PASS") | ||
23 | return testUser, testPass | ||
24 | } | ||
25 | |||
26 | func TestAuthRoute(t *testing.T) { | ||
27 | r := router.SetupRouter() | ||
28 | |||
29 | username, password := getTestUserCredentials() | ||
30 | |||
31 | w := httptest.NewRecorder() | ||
32 | req, err := http.NewRequest("POST", "/api/v1/auth", nil) | ||
33 | if err != nil { | ||
34 | t.Fatalf("Failed to create request: %v", err) | ||
35 | } | ||
36 | req.SetBasicAuth(username, password) | ||
37 | r.ServeHTTP(w, req) | ||
38 | |||
39 | assert.Equal(t, http.StatusOK, w.Code, "response should return a 200 code") | ||
40 | |||
41 | var response map[string]interface{} | ||
42 | err = json.Unmarshal(w.Body.Bytes(), &response) | ||
43 | if err != nil { | ||
44 | t.Fatalf("Failed to unmarshal response: %v", err) | ||
45 | } | ||
46 | _, exists := response["token"] | ||
47 | assert.True(t, exists, "response should return a token") | ||
48 | if !exists { | ||
49 | t.Fatalf("response did not contain token") | ||
50 | } | ||
51 | } | ||
52 | |||
53 | func TestAuthRouteFailure(t *testing.T) { | ||
54 | r := router.SetupRouter() | ||
55 | |||
56 | w := httptest.NewRecorder() | ||
57 | req, _ := http.NewRequest("POST", "/api/v1/auth", nil) | ||
58 | req.SetBasicAuth("asdf", "asdf") | ||
59 | r.ServeHTTP(w, req) | ||
60 | |||
61 | assert.Equal(t, http.StatusUnauthorized, w.Code, "should return a 401 code") | ||
62 | } | ||
diff --git a/api/go.mod b/api/go.mod new file mode 100644 index 0000000..6c414bc --- /dev/null +++ b/api/go.mod | |||
@@ -0,0 +1,56 @@ | |||
1 | module water/api | ||
2 | |||
3 | go 1.18 | ||
4 | |||
5 | require ( | ||
6 | github.com/gin-gonic/gin v1.9.1 | ||
7 | github.com/google/uuid v1.6.0 | ||
8 | github.com/mattn/go-sqlite3 v1.14.22 | ||
9 | github.com/spf13/viper v1.18.2 | ||
10 | github.com/stretchr/testify v1.8.4 | ||
11 | golang.org/x/crypto v0.19.0 | ||
12 | ) | ||
13 | |||
14 | require ( | ||
15 | github.com/bytedance/sonic v1.11.0 // indirect | ||
16 | github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect | ||
17 | github.com/chenzhuoyu/iasm v0.9.1 // indirect | ||
18 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect | ||
19 | github.com/fsnotify/fsnotify v1.7.0 // indirect | ||
20 | github.com/gabriel-vasile/mimetype v1.4.3 // indirect | ||
21 | github.com/gin-contrib/sse v0.1.0 // indirect | ||
22 | github.com/go-playground/locales v0.14.1 // indirect | ||
23 | github.com/go-playground/universal-translator v0.18.1 // indirect | ||
24 | github.com/go-playground/validator/v10 v10.18.0 // indirect | ||
25 | github.com/goccy/go-json v0.10.2 // indirect | ||
26 | github.com/hashicorp/hcl v1.0.0 // indirect | ||
27 | github.com/json-iterator/go v1.1.12 // indirect | ||
28 | github.com/klauspost/cpuid/v2 v2.2.6 // indirect | ||
29 | github.com/leodido/go-urn v1.4.0 // indirect | ||
30 | github.com/magiconair/properties v1.8.7 // indirect | ||
31 | github.com/mattn/go-isatty v0.0.20 // indirect | ||
32 | github.com/mitchellh/mapstructure v1.5.0 // indirect | ||
33 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect | ||
34 | github.com/modern-go/reflect2 v1.0.2 // indirect | ||
35 | github.com/pelletier/go-toml/v2 v2.1.1 // indirect | ||
36 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect | ||
37 | github.com/sagikazarmark/locafero v0.4.0 // indirect | ||
38 | github.com/sagikazarmark/slog-shim v0.1.0 // indirect | ||
39 | github.com/sourcegraph/conc v0.3.0 // indirect | ||
40 | github.com/spf13/afero v1.11.0 // indirect | ||
41 | github.com/spf13/cast v1.6.0 // indirect | ||
42 | github.com/spf13/pflag v1.0.5 // indirect | ||
43 | github.com/subosito/gotenv v1.6.0 // indirect | ||
44 | github.com/twitchyliquid64/golang-asm v0.15.1 // indirect | ||
45 | github.com/ugorji/go/codec v1.2.12 // indirect | ||
46 | go.uber.org/atomic v1.9.0 // indirect | ||
47 | go.uber.org/multierr v1.9.0 // indirect | ||
48 | golang.org/x/arch v0.7.0 // indirect | ||
49 | golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect | ||
50 | golang.org/x/net v0.21.0 // indirect | ||
51 | golang.org/x/sys v0.17.0 // indirect | ||
52 | golang.org/x/text v0.14.0 // indirect | ||
53 | google.golang.org/protobuf v1.32.0 // indirect | ||
54 | gopkg.in/ini.v1 v1.67.0 // indirect | ||
55 | gopkg.in/yaml.v3 v3.0.1 // indirect | ||
56 | ) | ||
diff --git a/api/go.sum b/api/go.sum new file mode 100644 index 0000000..20771f7 --- /dev/null +++ b/api/go.sum | |||
@@ -0,0 +1,128 @@ | |||
1 | github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= | ||
2 | github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM= | ||
3 | github.com/bytedance/sonic v1.11.0 h1:FwNNv6Vu4z2Onf1++LNzxB/QhitD8wuTdpZzMTGITWo= | ||
4 | github.com/bytedance/sonic v1.11.0/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4= | ||
5 | github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= | ||
6 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= | ||
7 | github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0= | ||
8 | github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA= | ||
9 | github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= | ||
10 | github.com/chenzhuoyu/iasm v0.9.1 h1:tUHQJXo3NhBqw6s33wkGn9SP3bvrWLdlVIJ3hQBL7P0= | ||
11 | github.com/chenzhuoyu/iasm v0.9.1/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= | ||
12 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= | ||
13 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= | ||
14 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= | ||
15 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= | ||
16 | github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= | ||
17 | github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= | ||
18 | github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= | ||
19 | github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= | ||
20 | github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= | ||
21 | github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= | ||
22 | github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= | ||
23 | github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= | ||
24 | github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= | ||
25 | github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= | ||
26 | github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= | ||
27 | github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= | ||
28 | github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= | ||
29 | github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= | ||
30 | github.com/go-playground/validator/v10 v10.18.0 h1:BvolUXjp4zuvkZ5YN5t7ebzbhlUtPsPm2S9NAZ5nl9U= | ||
31 | github.com/go-playground/validator/v10 v10.18.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= | ||
32 | github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= | ||
33 | github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= | ||
34 | github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= | ||
35 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= | ||
36 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= | ||
37 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= | ||
38 | github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= | ||
39 | github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= | ||
40 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= | ||
41 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= | ||
42 | github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= | ||
43 | github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc= | ||
44 | github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= | ||
45 | github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= | ||
46 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= | ||
47 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= | ||
48 | github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= | ||
49 | github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= | ||
50 | github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= | ||
51 | github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= | ||
52 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= | ||
53 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= | ||
54 | github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= | ||
55 | github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= | ||
56 | github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= | ||
57 | github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= | ||
58 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= | ||
59 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= | ||
60 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= | ||
61 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= | ||
62 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= | ||
63 | github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI= | ||
64 | github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= | ||
65 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= | ||
66 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= | ||
67 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= | ||
68 | github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= | ||
69 | github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= | ||
70 | github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= | ||
71 | github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= | ||
72 | github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= | ||
73 | github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= | ||
74 | github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= | ||
75 | github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= | ||
76 | github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= | ||
77 | github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= | ||
78 | github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= | ||
79 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= | ||
80 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= | ||
81 | github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ= | ||
82 | github.com/spf13/viper v1.18.2/go.mod h1:EKmWIqdnk5lOcmR72yw6hS+8OPYcwD0jteitLMVB+yk= | ||
83 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= | ||
84 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= | ||
85 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= | ||
86 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= | ||
87 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= | ||
88 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= | ||
89 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= | ||
90 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= | ||
91 | github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= | ||
92 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= | ||
93 | github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= | ||
94 | github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= | ||
95 | github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= | ||
96 | github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= | ||
97 | github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= | ||
98 | github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= | ||
99 | go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= | ||
100 | go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= | ||
101 | go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= | ||
102 | go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= | ||
103 | golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= | ||
104 | golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc= | ||
105 | golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= | ||
106 | golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo= | ||
107 | golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= | ||
108 | golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g= | ||
109 | golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k= | ||
110 | golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= | ||
111 | golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= | ||
112 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | ||
113 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | ||
114 | golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= | ||
115 | golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= | ||
116 | golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= | ||
117 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= | ||
118 | google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I= | ||
119 | google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= | ||
120 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= | ||
121 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= | ||
122 | gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= | ||
123 | gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= | ||
124 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= | ||
125 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= | ||
126 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= | ||
127 | nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= | ||
128 | rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= | ||
diff --git a/api/internal/config/config.go b/api/internal/config/config.go new file mode 100644 index 0000000..d54e40e --- /dev/null +++ b/api/internal/config/config.go | |||
@@ -0,0 +1,17 @@ | |||
1 | package config | ||
2 | |||
3 | import ( | ||
4 | "fmt" | ||
5 | "github.com/spf13/viper" | ||
6 | ) | ||
7 | |||
8 | func Load() (*viper.Viper, error) { | ||
9 | v := viper.New() | ||
10 | v.SetConfigFile(".env") | ||
11 | v.AddConfigPath(".") | ||
12 | err := v.ReadInConfig() | ||
13 | if err != nil { | ||
14 | return nil, fmt.Errorf("error reading .env file: %s", err) | ||
15 | } | ||
16 | return v, nil | ||
17 | } | ||
diff --git a/api/internal/controllers/auth.go b/api/internal/controllers/auth.go new file mode 100644 index 0000000..ab2fbbb --- /dev/null +++ b/api/internal/controllers/auth.go | |||
@@ -0,0 +1,79 @@ | |||
1 | package controllers | ||
2 | |||
3 | import ( | ||
4 | "crypto/rand" | ||
5 | "database/sql" | ||
6 | "encoding/base64" | ||
7 | "errors" | ||
8 | "github.com/gin-gonic/gin" | ||
9 | "net/http" | ||
10 | "water/api/internal/models" | ||
11 | |||
12 | _ "github.com/mattn/go-sqlite3" | ||
13 | "golang.org/x/crypto/bcrypt" | ||
14 | "water/api/internal/database" | ||
15 | ) | ||
16 | |||
17 | |||
18 | |||
19 | // AuthHandler is a function that handles users' authentication. It checks if the request | ||
20 | // has valid credentials, authenticates the user and sets the user's session. | ||
21 | // If the authentication is successful, it will allow the user to access protected routes. | ||
22 | func AuthHandler (c *gin.Context) { | ||
23 | username, password, ok := c.Request.BasicAuth() | ||
24 | if !ok { | ||
25 | c.Header("WWW-Authenticate", `Basic realm="Please enter your username and password."`) | ||
26 | c.AbortWithStatus(http.StatusUnauthorized) | ||
27 | return | ||
28 | } | ||
29 | |||
30 | db := database.EstablishDBConnection() | ||
31 | defer func(db *sql.DB) { | ||
32 | err := db.Close() | ||
33 | if err != nil { | ||
34 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
35 | return | ||
36 | } | ||
37 | }(db) | ||
38 | |||
39 | var user models.User | ||
40 | var preference models.Preference | ||
41 | |||
42 | row := db.QueryRow("SELECT id as 'id', name, uuid, password FROM Users WHERE name = ?", username) | ||
43 | if err := row.Scan(&user.ID, &user.Name, &user.UUID, &user.Password); err != nil { | ||
44 | if errors.Is(err, sql.ErrNoRows) { | ||
45 | c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) | ||
46 | return | ||
47 | } | ||
48 | } | ||
49 | |||
50 | row = db.QueryRow("SELECT id, color, size_id, user_id FROM Preferences where user_id = ?", user.ID) | ||
51 | if err := row.Scan(&preference.ID, &preference.Color, &preference.SizeID, &preference.UserID); err != nil { | ||
52 | if errors.Is(err, sql.ErrNoRows) { | ||
53 | c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) | ||
54 | } | ||
55 | } | ||
56 | |||
57 | if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { | ||
58 | c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()}) | ||
59 | return | ||
60 | } | ||
61 | |||
62 | // Generate a simple API token | ||
63 | apiToken := generateToken() | ||
64 | c.JSON(http.StatusOK, gin.H{"token": apiToken, "user": user, "preferences": preference}) | ||
65 | } | ||
66 | |||
67 | |||
68 | // generateToken is a helper function used in the AuthHandler. It generates a random token for API authentication. | ||
69 | // This function creates an empty byte slice of length 32 and fills it with cryptographic random data using the rand.Read function. | ||
70 | // If an error occurs during the generation, it will return an empty string. | ||
71 | // The generated cryptographic random data is then encoded into a base64 string and returned. | ||
72 | func generateToken() string { | ||
73 | token := make([]byte, 32) | ||
74 | _, err := rand.Read(token) | ||
75 | if err != nil { | ||
76 | return "" | ||
77 | } | ||
78 | return base64.StdEncoding.EncodeToString(token) | ||
79 | } \ No newline at end of file | ||
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 @@ | |||
1 | package controllers | ||
2 | |||
3 | import ( | ||
4 | "github.com/gin-gonic/gin" | ||
5 | "net/http" | ||
6 | "database/sql" | ||
7 | "water/api/internal/database" | ||
8 | "water/api/internal/models" | ||
9 | ) | ||
10 | |||
11 | func GetSizes(c *gin.Context) { | ||
12 | db := database.EstablishDBConnection() | ||
13 | defer func(db *sql.DB) { | ||
14 | err := db.Close() | ||
15 | if err != nil { | ||
16 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
17 | } | ||
18 | }(db) | ||
19 | |||
20 | rows, err := db.Query("SELECT id, size, unit FROM Sizes") | ||
21 | if err != nil { | ||
22 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
23 | return | ||
24 | } | ||
25 | defer func(rows *sql.Rows) { | ||
26 | err := rows.Close() | ||
27 | if err != nil { | ||
28 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
29 | return | ||
30 | } | ||
31 | }(rows) | ||
32 | |||
33 | var data []models.Size | ||
34 | |||
35 | for rows.Next() { | ||
36 | var size models.Size | ||
37 | if err := rows.Scan(&size.ID, &size.Size, &size.Unit); err != nil { | ||
38 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
39 | return | ||
40 | } | ||
41 | data = append(data, size) | ||
42 | } | ||
43 | |||
44 | c.JSON(http.StatusOK, data) | ||
45 | } | ||
diff --git a/api/internal/controllers/stats.go b/api/internal/controllers/stats.go new file mode 100644 index 0000000..2234787 --- /dev/null +++ b/api/internal/controllers/stats.go | |||
@@ -0,0 +1,168 @@ | |||
1 | package controllers | ||
2 | |||
3 | import ( | ||
4 | "database/sql" | ||
5 | "github.com/gin-gonic/gin" | ||
6 | "net/http" | ||
7 | "water/api/internal/database" | ||
8 | "water/api/internal/models" | ||
9 | ) | ||
10 | |||
11 | // TODO: add comments to all exported members of package. | ||
12 | |||
13 | // GetAllStatistics connects to the database and queries for all statistics in the database. | ||
14 | // If none have been found it will return an error, otherwise a 200 code is sent along with the list of statistics. | ||
15 | func GetAllStatistics(c *gin.Context) { | ||
16 | db := database.EstablishDBConnection() | ||
17 | defer func(db *sql.DB) { | ||
18 | err := db.Close() | ||
19 | if err != nil { | ||
20 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
21 | return | ||
22 | } | ||
23 | }(db) | ||
24 | |||
25 | 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") | ||
26 | if err != nil { | ||
27 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
28 | return | ||
29 | } | ||
30 | defer func(rows *sql.Rows) { | ||
31 | err := rows.Close() | ||
32 | if err != nil { | ||
33 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
34 | return | ||
35 | } | ||
36 | }(rows) | ||
37 | |||
38 | var data []models.Statistic | ||
39 | |||
40 | for rows.Next() { | ||
41 | var stat models.Statistic | ||
42 | var user models.User | ||
43 | if err := rows.Scan(&stat.Date, &stat.Quantity, &user.UUID, &user.Name); err != nil { | ||
44 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
45 | return | ||
46 | } | ||
47 | stat.User = user | ||
48 | data = append(data, stat) | ||
49 | } | ||
50 | |||
51 | c.JSON(http.StatusOK, data) | ||
52 | } | ||
53 | |||
54 | func PostNewStatistic(c *gin.Context) { | ||
55 | var stat models.StatisticPost | ||
56 | |||
57 | if err := c.BindJSON(&stat); err != nil { | ||
58 | c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) | ||
59 | return | ||
60 | } | ||
61 | |||
62 | db := database.EstablishDBConnection() | ||
63 | defer func(db *sql.DB) { | ||
64 | err := db.Close() | ||
65 | if err != nil { | ||
66 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
67 | return | ||
68 | } | ||
69 | }(db) | ||
70 | |||
71 | result, err := db.Exec("INSERT INTO statistics (date, user_id, quantity) values (?, ?, ?)", stat.Date, stat.UserID, stat.Quantity) | ||
72 | |||
73 | if err != nil { | ||
74 | c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) | ||
75 | } | ||
76 | |||
77 | id, err := result.LastInsertId() | ||
78 | if err != nil { | ||
79 | c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) | ||
80 | } | ||
81 | |||
82 | c.JSON(http.StatusCreated, gin.H{"status": "created", "id": id}) | ||
83 | } | ||
84 | |||
85 | func GetWeeklyStatistics(c *gin.Context) { | ||
86 | db := database.EstablishDBConnection() | ||
87 | defer func(db *sql.DB) { | ||
88 | err := db.Close() | ||
89 | if err != nil { | ||
90 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
91 | return | ||
92 | } | ||
93 | }(db) | ||
94 | |||
95 | rows, err := db.Query("SELECT date, total FROM `WeeklyStatisticsView`") | ||
96 | if err != nil { | ||
97 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
98 | return | ||
99 | } | ||
100 | defer func(rows *sql.Rows) { | ||
101 | err := rows.Close() | ||
102 | if err != nil { | ||
103 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
104 | return | ||
105 | } | ||
106 | }(rows) | ||
107 | |||
108 | var data []models.WeeklyStatistic | ||
109 | for rows.Next() { | ||
110 | var weeklyStat models.WeeklyStatistic | ||
111 | if err := rows.Scan(&weeklyStat.Date, &weeklyStat.Total); err != nil { | ||
112 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
113 | } | ||
114 | data = append(data, weeklyStat) | ||
115 | } | ||
116 | |||
117 | c.JSON(http.StatusOK, data) | ||
118 | } | ||
119 | |||
120 | func GetDailyUserStatistics(c *gin.Context) { | ||
121 | db := database.EstablishDBConnection() | ||
122 | defer func(db *sql.DB) { | ||
123 | err := db.Close() | ||
124 | if err != nil { | ||
125 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
126 | return | ||
127 | } | ||
128 | }(db) | ||
129 | |||
130 | rows, err := db.Query("SELECT name, total FROM DailyUserStatistics") | ||
131 | |||
132 | if err != nil { | ||
133 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
134 | return | ||
135 | } | ||
136 | defer func(rows *sql.Rows) { | ||
137 | err := rows.Close() | ||
138 | if err != nil { | ||
139 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
140 | return | ||
141 | } | ||
142 | }(rows) | ||
143 | |||
144 | var data []models.DailyUserTotals | ||
145 | for rows.Next() { | ||
146 | var stat models.DailyUserTotals | ||
147 | if err := rows.Scan(&stat.Name, &stat.Total); err != nil { | ||
148 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
149 | return | ||
150 | } | ||
151 | data = append(data, stat) | ||
152 | } | ||
153 | |||
154 | c.JSON(http.StatusOK, data) | ||
155 | |||
156 | } | ||
157 | |||
158 | func GetUserStatistics(c *gin.Context) { | ||
159 | c.JSON(http.StatusOK, gin.H{"status": "ok", "uuid": c.Param("uuid")}) | ||
160 | } | ||
161 | |||
162 | func UpdateUserStatistic(c *gin.Context) { | ||
163 | c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) | ||
164 | } | ||
165 | |||
166 | func DeleteUserStatistic(c *gin.Context) { | ||
167 | c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) | ||
168 | } | ||
diff --git a/api/internal/controllers/user.go b/api/internal/controllers/user.go new file mode 100644 index 0000000..dbb09cf --- /dev/null +++ b/api/internal/controllers/user.go | |||
@@ -0,0 +1,68 @@ | |||
1 | package controllers | ||
2 | |||
3 | import ( | ||
4 | "database/sql" | ||
5 | "errors" | ||
6 | "log" | ||
7 | "net/http" | ||
8 | "water/api/internal/database" | ||
9 | "water/api/internal/models" | ||
10 | |||
11 | "github.com/gin-gonic/gin" | ||
12 | ) | ||
13 | |||
14 | func GetUser(c *gin.Context) { | ||
15 | c.JSON(http.StatusOK, gin.H{"message": "User found"}) | ||
16 | } | ||
17 | func GetUserPreferences(c *gin.Context) { | ||
18 | db := database.EstablishDBConnection() | ||
19 | defer func(db *sql.DB) { | ||
20 | err := db.Close() | ||
21 | if err != nil { | ||
22 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
23 | return | ||
24 | } | ||
25 | }(db) | ||
26 | |||
27 | var preference models.Preference | ||
28 | |||
29 | row := db.QueryRow("SELECT id, user_id, color, size_id FROM Preferences WHERE user_id = ?", c.Param("id")) | ||
30 | if err := row.Scan(&preference.ID, &preference.UserID, &preference.Color, &preference.SizeID); err != nil { | ||
31 | if errors.Is(err, sql.ErrNoRows) { | ||
32 | c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) | ||
33 | return | ||
34 | } else { | ||
35 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
36 | return | ||
37 | } | ||
38 | } | ||
39 | |||
40 | c.JSON(http.StatusOK, preference) | ||
41 | } | ||
42 | |||
43 | func UpdateUserPreferences(c *gin.Context) { | ||
44 | db := database.EstablishDBConnection() | ||
45 | defer func(db *sql.DB) { | ||
46 | err := db.Close() | ||
47 | if err != nil { | ||
48 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
49 | return | ||
50 | } | ||
51 | }(db) | ||
52 | |||
53 | var newPreferences models.Preference | ||
54 | if err := c.BindJSON(&newPreferences); err != nil { | ||
55 | c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()}) | ||
56 | return | ||
57 | } | ||
58 | |||
59 | log.Printf("newPreferences: %v", newPreferences) | ||
60 | |||
61 | _, err := db.Exec("UPDATE Preferences SET color = ?, size_id = ? WHERE id = ?", newPreferences.Color, newPreferences.SizeID, newPreferences.ID) | ||
62 | if err != nil { | ||
63 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
64 | return | ||
65 | } | ||
66 | |||
67 | c.Status(http.StatusNoContent) | ||
68 | } | ||
diff --git a/api/internal/database/database.go b/api/internal/database/database.go new file mode 100644 index 0000000..1866655 --- /dev/null +++ b/api/internal/database/database.go | |||
@@ -0,0 +1,24 @@ | |||
1 | package database | ||
2 | |||
3 | import ( | ||
4 | "database/sql" | ||
5 | _ "github.com/mattn/go-sqlite3" | ||
6 | "log" | ||
7 | "path/filepath" | ||
8 | "water/api/internal/config" | ||
9 | ) | ||
10 | |||
11 | func EstablishDBConnection() *sql.DB { | ||
12 | c, err := config.Load() | ||
13 | |||
14 | driver := c.GetString("DB_DRIVER") | ||
15 | path, err := filepath.Abs(c.GetString("DB_PATH")) | ||
16 | if err != nil { | ||
17 | log.Fatal("There was and error getting the absolute path of the database.") | ||
18 | } | ||
19 | db, err := sql.Open(driver, path) | ||
20 | if err != nil { | ||
21 | panic(err) | ||
22 | } | ||
23 | return db | ||
24 | } \ No newline at end of file | ||
diff --git a/api/internal/middleware/middleware.go b/api/internal/middleware/middleware.go new file mode 100644 index 0000000..aa27fb8 --- /dev/null +++ b/api/internal/middleware/middleware.go | |||
@@ -0,0 +1,56 @@ | |||
1 | package middleware | ||
2 | |||
3 | import ( | ||
4 | "errors" | ||
5 | "log" | ||
6 | "net/http" | ||
7 | "strings" | ||
8 | |||
9 | "github.com/gin-gonic/gin" | ||
10 | ) | ||
11 | |||
12 | func TokenRequired() gin.HandlerFunc { | ||
13 | return func(c *gin.Context) { | ||
14 | _, err := checkForTokenInContext(c) | ||
15 | |||
16 | if err != nil { | ||
17 | c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) | ||
18 | c.Abort() | ||
19 | return | ||
20 | } | ||
21 | |||
22 | c.Next() | ||
23 | } | ||
24 | } | ||
25 | |||
26 | func CORSMiddleware() gin.HandlerFunc { | ||
27 | return func(c *gin.Context) { | ||
28 | c.Writer.Header().Set("Access-Control-Allow-Origin", "*") | ||
29 | c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") | ||
30 | 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") | ||
31 | c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, PATCH") | ||
32 | |||
33 | if c.Request.Method == "OPTIONS" { | ||
34 | log.Println(c.Request.Header) | ||
35 | c.AbortWithStatus(http.StatusNoContent) | ||
36 | return | ||
37 | } | ||
38 | |||
39 | c.Next() | ||
40 | } | ||
41 | } | ||
42 | |||
43 | func checkForTokenInContext(c *gin.Context) (string, error) { | ||
44 | authorizationHeader := c.GetHeader("Authorization") | ||
45 | if authorizationHeader == "" { | ||
46 | return "", errors.New("authorization header is missing") | ||
47 | } | ||
48 | |||
49 | parts := strings.Split(authorizationHeader, " ") | ||
50 | |||
51 | if len(parts) != 2 || parts[0] != "Bearer" { | ||
52 | return "", errors.New("invalid Authorization header format") | ||
53 | } | ||
54 | |||
55 | return parts[1], nil | ||
56 | } | ||
diff --git a/api/internal/models/auth.go b/api/internal/models/auth.go new file mode 100644 index 0000000..fa7dbe4 --- /dev/null +++ b/api/internal/models/auth.go | |||
@@ -0,0 +1,11 @@ | |||
1 | package models | ||
2 | |||
3 | import "time" | ||
4 | |||
5 | type Token struct { | ||
6 | ID int64 `json:"id"` | ||
7 | UserID int64 `json:"user_id"` | ||
8 | Token string `json:"token"` | ||
9 | CreatedAt time.Time `json:"created_at"` | ||
10 | ExpiredAt time.Time `json:"expired_at"` | ||
11 | } | ||
diff --git a/api/internal/models/preferences.go b/api/internal/models/preferences.go new file mode 100644 index 0000000..8022099 --- /dev/null +++ b/api/internal/models/preferences.go | |||
@@ -0,0 +1,14 @@ | |||
1 | package models | ||
2 | |||
3 | type Preference struct { | ||
4 | ID int64 `json:"id"` | ||
5 | Color string `json:"color"` | ||
6 | UserID int64 `json:"user_id"` | ||
7 | SizeID int64 `json:"size_id"` | ||
8 | } | ||
9 | |||
10 | type Size struct { | ||
11 | ID int64 `json:"id"` | ||
12 | Size int64 `json:"size"` | ||
13 | Unit string `json:"unit"` | ||
14 | } | ||
diff --git a/api/internal/models/statistics.go b/api/internal/models/statistics.go new file mode 100644 index 0000000..7dceb3a --- /dev/null +++ b/api/internal/models/statistics.go | |||
@@ -0,0 +1,26 @@ | |||
1 | package models | ||
2 | |||
3 | import "time" | ||
4 | |||
5 | type Statistic struct { | ||
6 | ID int64 `json:"id"` | ||
7 | Date time.Time `json:"date"` | ||
8 | User User `json:"user"` | ||
9 | Quantity int `json:"quantity"` | ||
10 | } | ||
11 | |||
12 | type StatisticPost struct { | ||
13 | Date time.Time `json:"date"` | ||
14 | Quantity int64 `json:"quantity"` | ||
15 | UserID int64 `json:"user_id"` | ||
16 | } | ||
17 | |||
18 | type WeeklyStatistic struct { | ||
19 | Date string `json:"date"` | ||
20 | Total int64 `json:"total"` | ||
21 | } | ||
22 | |||
23 | type DailyUserTotals struct { | ||
24 | Name string `json:"name"` | ||
25 | Total int64 `json:"total"` | ||
26 | } | ||
diff --git a/api/internal/models/user.go b/api/internal/models/user.go new file mode 100644 index 0000000..ca5daa4 --- /dev/null +++ b/api/internal/models/user.go | |||
@@ -0,0 +1,10 @@ | |||
1 | package models | ||
2 | |||
3 | import "github.com/google/uuid" | ||
4 | |||
5 | type User struct { | ||
6 | ID int64 `json:"id"` | ||
7 | Name string `json:"name"` | ||
8 | UUID uuid.UUID `json:"uuid"` | ||
9 | Password string `json:"-"` | ||
10 | } | ||
diff --git a/api/internal/router/router.go b/api/internal/router/router.go new file mode 100644 index 0000000..a71c3e6 --- /dev/null +++ b/api/internal/router/router.go | |||
@@ -0,0 +1,43 @@ | |||
1 | package router | ||
2 | |||
3 | import ( | ||
4 | "github.com/gin-gonic/gin" | ||
5 | "water/api/internal/controllers" | ||
6 | "water/api/internal/middleware" | ||
7 | ) | ||
8 | |||
9 | func SetupRouter() *gin.Engine { | ||
10 | // Disable Console Color | ||
11 | // gin.DisableConsoleColor() | ||
12 | r := gin.Default() | ||
13 | r.Use(middleware.CORSMiddleware()) | ||
14 | r.Use(gin.Logger()) | ||
15 | r.Use(gin.Recovery()) | ||
16 | |||
17 | api := r.Group("api/v1") | ||
18 | |||
19 | api.POST("/auth", controllers.AuthHandler) | ||
20 | api.GET("/sizes", middleware.TokenRequired(), controllers.GetSizes) | ||
21 | api.PATCH("/user/preferences", controllers.UpdateUserPreferences) | ||
22 | |||
23 | user := api.Group("/user/:id") | ||
24 | user.Use(middleware.TokenRequired()) | ||
25 | { | ||
26 | user.GET("", controllers.GetUser) | ||
27 | user.GET("preferences", controllers.GetUserPreferences) | ||
28 | } | ||
29 | |||
30 | stats := api.Group("/stats") | ||
31 | stats.Use(middleware.TokenRequired()) | ||
32 | { | ||
33 | stats.GET("", controllers.GetAllStatistics) | ||
34 | stats.POST("", controllers.PostNewStatistic) | ||
35 | stats.GET("weekly", controllers.GetWeeklyStatistics) | ||
36 | stats.GET("daily", controllers.GetDailyUserStatistics) | ||
37 | stats.GET("user/:uuid", controllers.GetUserStatistics) | ||
38 | stats.PATCH("user/:uuid", controllers.UpdateUserStatistic) | ||
39 | stats.DELETE("user/:uuid", controllers.DeleteUserStatistic) | ||
40 | } | ||
41 | |||
42 | return r | ||
43 | } \ No newline at end of file | ||