Compare commits
58 Commits
2839a2c4c3
...
prod
| Author | SHA1 | Date | |
|---|---|---|---|
| fe5bf72a03 | |||
| 20ff57a24d | |||
| b2fb257a57 | |||
| 923726f6fa | |||
| 7c78091027 | |||
| 11914db84f | |||
|
05e63faf50
|
|||
|
28113d27d0
|
|||
|
0325fe101c
|
|||
|
ea2663a53d
|
|||
|
2b23700c84
|
|||
|
c927d917ec
|
|||
|
5e563f2c59
|
|||
|
75433834ed
|
|||
|
f9a5a9e5f9
|
|||
|
1e61b765ae
|
|||
| 677c6b795e | |||
| 3b0ba91b73 | |||
| 74b63bc494 | |||
| 480f311856 | |||
| 1a0524a24b | |||
| 2e641a1db5 | |||
| d952956a8d | |||
| b28b41aff4 | |||
| 18e651babf | |||
| 5e992873cc | |||
| 26b75d3db9 | |||
| 772e3e5c2e | |||
| fcba476a88 | |||
| d1bdf38227 | |||
| dea1b9027b | |||
| ee9ef98fa3 | |||
| 9a48f23a2c | |||
| 99d52aa505 | |||
| 8833147278 | |||
| 69727339aa | |||
| e97b7c3069 | |||
| 492baab18b | |||
| 263ea213cd | |||
| 6881a64691 | |||
| 5efd5f9bbc | |||
| 396c97516d | |||
| 88caf44fc5 | |||
| c8dce6f33a | |||
| 12affdff43 | |||
| 9f3fcc0171 | |||
| f5dd96cf9f | |||
| d3900957c9 | |||
| f90c5f83e1 | |||
| a5246e523c | |||
| 11a620b73a | |||
| 5db923d438 | |||
| e1c4eeb51d | |||
| cf728abe11 | |||
| 84f72a1e25 | |||
| 3d2dbaebc7 | |||
| 0b9d1d31e4 | |||
| d3daa4e5ba |
@@ -10,6 +10,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out repository code
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5
|
||||
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6
|
||||
- run: docker build . -t spend-sparrow-test
|
||||
- run: docker rmi spend-sparrow-test
|
||||
|
||||
@@ -9,7 +9,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out repository code
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5
|
||||
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6
|
||||
- run: docker login git.wundenbergs.de -u tim -p ${{ secrets.DOCKER_GITEA_TOKEN }}
|
||||
- run: docker build . -t git.wundenbergs.de/x/spend-sparrow:latest -t git.wundenbergs.de/x/spend-sparrow:$GITHUB_SHA
|
||||
- run: docker push git.wundenbergs.de/x/spend-sparrow:latest
|
||||
|
||||
@@ -3,11 +3,11 @@ dir: mocks/
|
||||
outpkg: mocks
|
||||
issue-845-fix: True
|
||||
packages:
|
||||
spend-sparrow/internal/service:
|
||||
spend-sparrow/internal/core:
|
||||
interfaces:
|
||||
Random:
|
||||
Clock:
|
||||
Mail:
|
||||
spend-sparrow/internal/db:
|
||||
spend-sparrow/internal/authentication:
|
||||
interfaces:
|
||||
Auth:
|
||||
Db:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.25.3@sha256:6d4e5e74f47db00f7f24da5f53c1b4198ae46862a47395e30477365458347bf2 AS builder_go
|
||||
FROM golang:1.25.5@sha256:6396b3d8039d2050ab7a3c5c6e1cbeed8bf6d2ddc0403e1ab39d78749227ca19 AS builder_go
|
||||
WORKDIR /spend-sparrow
|
||||
RUN go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest
|
||||
RUN go install github.com/a-h/templ/cmd/templ@latest
|
||||
@@ -13,7 +13,7 @@ RUN golangci-lint run ./...
|
||||
RUN go build -o /spend-sparrow/spend-sparrow .
|
||||
|
||||
|
||||
FROM node:24.11.0@sha256:e5bbac0e9b8a6e3b96a86a82bbbcf4c533a879694fd613ed616bae5116f6f243 AS builder_node
|
||||
FROM node:24.12.0@sha256:e7a6c521e0e133cb3f4d97c71a95f290fb3816dca1a3b002e49059e2095870e5 AS builder_node
|
||||
WORKDIR /spend-sparrow
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm clean-install
|
||||
@@ -21,7 +21,7 @@ COPY . ./
|
||||
RUN npm run build
|
||||
|
||||
|
||||
FROM debian:13.1@sha256:01a723bf5bfb21b9dda0c9a33e0538106e4d02cce8f557e118dd61259553d598
|
||||
FROM debian:13.2@sha256:c71b05eac0b20adb4cdcc9f7b052227efd7da381ad10bb92f972e8eae7c6cdc9
|
||||
WORKDIR /spend-sparrow
|
||||
RUN apt-get update && apt-get install -y ca-certificates && echo "" > .env
|
||||
COPY migration ./migration
|
||||
|
||||
59
go.mod
59
go.mod
@@ -2,11 +2,11 @@ module spend-sparrow
|
||||
|
||||
go 1.24.0
|
||||
|
||||
toolchain go1.25.3
|
||||
toolchain go1.25.5
|
||||
|
||||
require (
|
||||
github.com/a-h/templ v0.3.960
|
||||
github.com/golang-migrate/migrate/v4 v4.19.0
|
||||
github.com/golang-migrate/migrate/v4 v4.19.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jmoiron/sqlx v1.4.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
@@ -14,41 +14,40 @@ require (
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/uptrace/opentelemetry-go-extra/otelsql v0.3.2
|
||||
github.com/uptrace/opentelemetry-go-extra/otelsqlx v0.3.2
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.13.0
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0
|
||||
go.opentelemetry.io/otel v1.38.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.14.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.38.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.38.0
|
||||
go.opentelemetry.io/otel/log v0.14.0
|
||||
go.opentelemetry.io/otel/sdk v1.38.0
|
||||
go.opentelemetry.io/otel/sdk/log v0.14.0
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0
|
||||
go.opentelemetry.io/otel/trace v1.38.0
|
||||
golang.org/x/crypto v0.43.0
|
||||
golang.org/x/net v0.46.0
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.14.0
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0
|
||||
go.opentelemetry.io/otel v1.39.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.15.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.39.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.39.0
|
||||
go.opentelemetry.io/otel/log v0.15.0
|
||||
go.opentelemetry.io/otel/sdk v1.39.0
|
||||
go.opentelemetry.io/otel/sdk/log v0.15.0
|
||||
go.opentelemetry.io/otel/sdk/metric v1.39.0
|
||||
go.opentelemetry.io/otel/trace v1.39.0
|
||||
golang.org/x/crypto v0.46.0
|
||||
golang.org/x/net v0.48.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/felixge/httpsnoop v1.0.4 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/stretchr/objx v0.5.2 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.38.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.7.1 // indirect
|
||||
golang.org/x/sys v0.37.0 // indirect
|
||||
golang.org/x/text v0.30.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5 // indirect
|
||||
google.golang.org/grpc v1.75.0 // indirect
|
||||
google.golang.org/protobuf v1.36.8 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.39.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
golang.org/x/text v0.32.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect
|
||||
google.golang.org/grpc v1.77.0 // indirect
|
||||
google.golang.org/protobuf v1.36.10 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
119
go.sum
119
go.sum
@@ -4,8 +4,10 @@ github.com/a-h/templ v0.3.960 h1:trshEpGa8clF5cdI39iY4ZrZG8Z/QixyzEyUnA7feTM=
|
||||
github.com/a-h/templ v0.3.960/go.mod h1:oCZcnKRf5jjsGpf2yELzQfodLphd2mwecwG4Crk5HBo=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
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/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
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/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
@@ -15,21 +17,16 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/golang-migrate/migrate/v4 v4.19.0 h1:RcjOnCGz3Or6HQYEJ/EEVLfWnmw9KnoigPSjzhCuaSE=
|
||||
github.com/golang-migrate/migrate/v4 v4.19.0/go.mod h1:9dyEcu+hO+G9hPSw8AIg50yg622pXJsoHItQnDGZkI0=
|
||||
github.com/golang-migrate/migrate/v4 v4.19.1 h1:OCyb44lFuQfYXYLx1SCxPZQGU7mcaZ7gH9yH4jSFbBA=
|
||||
github.com/golang-migrate/migrate/v4 v4.19.1/go.mod h1:CTcgfjxhaUtsLipnLoQRWCrjYXycRz/g5+RWDuYgPrE=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
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/grpc-ecosystem/grpc-gateway/v2 v2.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs=
|
||||
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
|
||||
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
|
||||
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3/go.mod h1:zQrxl1YP88HQlA6i9c63DSVPFklWpGX4OWAc9bFuaH4=
|
||||
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
||||
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
@@ -43,10 +40,10 @@ github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.32 h1:JD12Ag3oLy1zQA+BNn74xRgaBbdhbNIDYvQUEuuErjs=
|
||||
github.com/mattn/go-sqlite3 v1.14.32/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
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/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
|
||||
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
|
||||
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.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
@@ -55,58 +52,58 @@ github.com/uptrace/opentelemetry-go-extra/otelsql v0.3.2 h1:ZjUj9BLYf9PEqBn8W/Oa
|
||||
github.com/uptrace/opentelemetry-go-extra/otelsql v0.3.2/go.mod h1:O8bHQfyinKwTXKkiKNGmLQS7vRsqRxIQTFZpYpHK3IQ=
|
||||
github.com/uptrace/opentelemetry-go-extra/otelsqlx v0.3.2 h1:zA9ZXfdtowo0EKt+t7uqXNlHxPeygrxuFSIroiBVgPU=
|
||||
github.com/uptrace/opentelemetry-go-extra/otelsqlx v0.3.2/go.mod h1:ySXmuW9JLCm/TjsQksuMY/7MNiWqfHnhH2xeT34uOLU=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.13.0 h1:bwnLpizECbPr1RrQ27waeY2SPIPeccCx/xLuoYADZ9s=
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.13.0/go.mod h1:3nWlOiiqA9UtUnrcNk82mYasNxD8ehOspL0gOfEo6Y4=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg=
|
||||
go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
|
||||
go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.14.0 h1:OMqPldHt79PqWKOMYIAQs3CxAi7RLgPxwfFSwr4ZxtM=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.14.0/go.mod h1:1biG4qiqTxKiUCtoWDPpL3fB3KxVwCiGw81j3nKMuHE=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.38.0 h1:vl9obrcoWVKp/lwl8tRE33853I8Xru9HFbw/skNeLs8=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.38.0/go.mod h1:GAXRxmLJcVM3u22IjTg74zWBrRCKq8BnOqUVLodpcpw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 h1:GqRJVj7UmLjCVyVJ3ZFLdPRmhDUp2zFmQe3RHIOsw24=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0/go.mod h1:ri3aaHSmCTVYu2AWv44YMauwAQc0aqI9gHKIcSbI1pU=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.38.0 h1:lwI4Dc5leUqENgGuQImwLo4WnuXFPetmPpkLi2IrX54=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.38.0/go.mod h1:Kz/oCE7z5wuyhPxsXDuaPteSWqjSBD5YaSdbxZYGbGk=
|
||||
go.opentelemetry.io/otel/log v0.14.0 h1:2rzJ+pOAZ8qmZ3DDHg73NEKzSZkhkGIua9gXtxNGgrM=
|
||||
go.opentelemetry.io/otel/log v0.14.0/go.mod h1:5jRG92fEAgx0SU/vFPxmJvhIuDU9E1SUnEQrMlJpOno=
|
||||
go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
|
||||
go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
|
||||
go.opentelemetry.io/otel/sdk/log v0.14.0 h1:JU/U3O7N6fsAXj0+CXz21Czg532dW2V4gG1HE/e8Zrg=
|
||||
go.opentelemetry.io/otel/sdk/log v0.14.0/go.mod h1:imQvII+0ZylXfKU7/wtOND8Hn4OpT3YUoIgqJVksUkM=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.14.0 h1:eypSOd+0txRKCXPNyqLPsbSfA0jULgJcGmSAdFAnrCM=
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.14.0/go.mod h1:CRGvIBL/aAxpQU34ZxyQVFlovVcp67s4cAmQu8Jh9mc=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 h1:ssfIgGNANqpVFCndZvcuyKbl0g+UAVcbBcqGkG28H0Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0/go.mod h1:GQ/474YrbE4Jx8gZ4q5I4hrhUzM6UPzyrqJYV2AqPoQ=
|
||||
go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=
|
||||
go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.15.0 h1:W+m0g+/6v3pa5PgVf2xoFMi5YtNR06WtS7ve5pcvLtM=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.15.0/go.mod h1:JM31r0GGZ/GU94mX8hN4D8v6e40aFlUECSQ48HaLgHM=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.39.0 h1:cEf8jF6WbuGQWUVcqgyWtTR0kOOAWY1DYZ+UhvdmQPw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.39.0/go.mod h1:k1lzV5n5U3HkGvTCJHraTAGJ7MqsgL1wrGwTj1Isfiw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0 h1:f0cb2XPmrqn4XMy9PNliTgRKJgS5WcL/u0/WRYGz4t0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0/go.mod h1:vnakAaFckOMiMtOIhFI2MNH4FYrZzXCYxmb1LlhoGz8=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.39.0 h1:in9O8ESIOlwJAEGTkkf34DesGRAc/Pn8qJ7k3r/42LM=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.39.0/go.mod h1:Rp0EXBm5tfnv0WL+ARyO/PHBEaEAT8UUHQ6AGJcSq6c=
|
||||
go.opentelemetry.io/otel/log v0.15.0 h1:0VqVnc3MgyYd7QqNVIldC3dsLFKgazR6P3P3+ypkyDY=
|
||||
go.opentelemetry.io/otel/log v0.15.0/go.mod h1:9c/G1zbyZfgu1HmQD7Qj84QMmwTp2QCQsZH1aeoWDE4=
|
||||
go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0=
|
||||
go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs=
|
||||
go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18=
|
||||
go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=
|
||||
go.opentelemetry.io/otel/sdk/log v0.15.0 h1:WgMEHOUt5gjJE93yqfqJOkRflApNif84kxoHWS9VVHE=
|
||||
go.opentelemetry.io/otel/sdk/log v0.15.0/go.mod h1:qDC/FlKQCXfH5hokGsNg9aUBGMJQsrUyeOiW5u+dKBQ=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.14.0 h1:Ijbtz+JKXl8T2MngiwqBlPaHqc4YCaP/i13Qrow6gAM=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.14.0/go.mod h1:dCU8aEL6q+L9cYTqcVOk8rM9Tp8WdnHOPLiBgp0SGOA=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=
|
||||
go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
|
||||
go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
|
||||
go.opentelemetry.io/proto/otlp v1.7.1 h1:gTOMpGDb0WTBOP8JaO72iL3auEZhVmAQg4ipjOVAtj4=
|
||||
go.opentelemetry.io/proto/otlp v1.7.1/go.mod h1:b2rVh6rfI/s2pHWNlB7ILJcRALpcNDzKhACevjI+ZnE=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=
|
||||
go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI=
|
||||
go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04=
|
||||
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
|
||||
golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4=
|
||||
golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210=
|
||||
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
|
||||
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k=
|
||||
golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 h1:BIRfGDEjiHRrk0QKZe3Xv2ieMhtgRGeLcZQ0mIVn4EY=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5/go.mod h1:j3QtIyytwqGr1JUDtYXwtMXWPKsEa5LtzIFN1Wn5WvE=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5 h1:eaY8u2EuxbRv7c3NiGK0/NedzVsCcV6hDuU5qPX5EGE=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5/go.mod h1:M4/wBTSeyLxupu3W3tJtOgB14jILAS/XWPSSa3TAlJc=
|
||||
google.golang.org/grpc v1.75.0 h1:+TW+dqTd2Biwe6KKfhE5JpiYIBWq865PhKGSXiivqt4=
|
||||
google.golang.org/grpc v1.75.0/go.mod h1:JtPAzKiq4v1xcAB2hydNlWI2RnF85XXcV0mhKXr2ecQ=
|
||||
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
|
||||
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:+rXWjjaukWZun3mLfjmVnQi18E1AsFbDN9QdJ5YXLto=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=
|
||||
google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM=
|
||||
google.golang.org/grpc v1.77.0/go.mod h1:z0BY1iVj0q8E1uSQCjL9cppRj+gnZjzDnzV0dHhrNig=
|
||||
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
|
||||
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
|
||||
@@ -1,44 +1,36 @@
|
||||
package handler
|
||||
package account
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"spend-sparrow/internal/handler/middleware"
|
||||
"spend-sparrow/internal/service"
|
||||
t "spend-sparrow/internal/template/account"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/utils"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
"net/http"
|
||||
"spend-sparrow/internal/core"
|
||||
"spend-sparrow/internal/utils"
|
||||
)
|
||||
|
||||
type Account interface {
|
||||
Handle(router *http.ServeMux)
|
||||
type Handler struct {
|
||||
s Service
|
||||
r *core.Render
|
||||
}
|
||||
|
||||
type AccountImpl struct {
|
||||
s service.Account
|
||||
r *Render
|
||||
}
|
||||
|
||||
func NewAccount(s service.Account, r *Render) Account {
|
||||
return AccountImpl{
|
||||
func NewHandler(s Service, r *core.Render) Handler {
|
||||
return Handler{
|
||||
s: s,
|
||||
r: r,
|
||||
}
|
||||
}
|
||||
|
||||
func (h AccountImpl) Handle(r *http.ServeMux) {
|
||||
func (h Handler) Handle(r *http.ServeMux) {
|
||||
r.Handle("GET /account", h.handleAccountPage())
|
||||
r.Handle("GET /account/{id}", h.handleAccountItemComp())
|
||||
r.Handle("POST /account/{id}", h.handleUpdateAccount())
|
||||
r.Handle("DELETE /account/{id}", h.handleDeleteAccount())
|
||||
}
|
||||
|
||||
func (h AccountImpl) handleAccountPage() http.HandlerFunc {
|
||||
func (h Handler) handleAccountPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -46,20 +38,20 @@ func (h AccountImpl) handleAccountPage() http.HandlerFunc {
|
||||
|
||||
accounts, err := h.s.GetAll(r.Context(), user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
comp := t.Account(accounts)
|
||||
comp := template(accounts)
|
||||
h.r.RenderLayout(r, w, comp, user)
|
||||
}
|
||||
}
|
||||
|
||||
func (h AccountImpl) handleAccountItemComp() http.HandlerFunc {
|
||||
func (h Handler) handleAccountItemComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -67,39 +59,39 @@ func (h AccountImpl) handleAccountItemComp() http.HandlerFunc {
|
||||
|
||||
id := r.PathValue("id")
|
||||
if id == "new" {
|
||||
comp := t.EditAccount(nil)
|
||||
comp := editAccount(nil)
|
||||
h.r.Render(r, w, comp)
|
||||
return
|
||||
}
|
||||
|
||||
account, err := h.s.Get(r.Context(), user, id)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var comp templ.Component
|
||||
if r.URL.Query().Get("edit") == "true" {
|
||||
comp = t.EditAccount(account)
|
||||
comp = editAccount(account)
|
||||
} else {
|
||||
comp = t.AccountItem(account)
|
||||
comp = accountItem(account)
|
||||
}
|
||||
h.r.Render(r, w, comp)
|
||||
}
|
||||
}
|
||||
|
||||
func (h AccountImpl) handleUpdateAccount() http.HandlerFunc {
|
||||
func (h Handler) handleUpdateAccount() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
account *types.Account
|
||||
account *Account
|
||||
err error
|
||||
)
|
||||
id := r.PathValue("id")
|
||||
@@ -107,27 +99,27 @@ func (h AccountImpl) handleUpdateAccount() http.HandlerFunc {
|
||||
if id == "new" {
|
||||
account, err = h.s.Add(r.Context(), user, name)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
account, err = h.s.UpdateName(r.Context(), user, id, name)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
comp := t.AccountItem(account)
|
||||
comp := accountItem(account)
|
||||
h.r.Render(r, w, comp)
|
||||
}
|
||||
}
|
||||
|
||||
func (h AccountImpl) handleDeleteAccount() http.HandlerFunc {
|
||||
func (h Handler) handleDeleteAccount() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -137,7 +129,7 @@ func (h AccountImpl) handleDeleteAccount() http.HandlerFunc {
|
||||
|
||||
err := h.s.Delete(r.Context(), user, id)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -1,55 +1,55 @@
|
||||
package service
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"spend-sparrow/internal/db"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/auth_types"
|
||||
"spend-sparrow/internal/core"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
type Account interface {
|
||||
Add(ctx context.Context, user *types.User, name string) (*types.Account, error)
|
||||
UpdateName(ctx context.Context, user *types.User, id string, name string) (*types.Account, error)
|
||||
Get(ctx context.Context, user *types.User, id string) (*types.Account, error)
|
||||
GetAll(ctx context.Context, user *types.User) ([]*types.Account, error)
|
||||
Delete(ctx context.Context, user *types.User, id string) error
|
||||
type Service interface {
|
||||
Add(ctx context.Context, user *auth_types.User, name string) (*Account, error)
|
||||
UpdateName(ctx context.Context, user *auth_types.User, id string, name string) (*Account, error)
|
||||
Get(ctx context.Context, user *auth_types.User, id string) (*Account, error)
|
||||
GetAll(ctx context.Context, user *auth_types.User) ([]*Account, error)
|
||||
Delete(ctx context.Context, user *auth_types.User, id string) error
|
||||
}
|
||||
|
||||
type AccountImpl struct {
|
||||
type ServiceImpl struct {
|
||||
db *sqlx.DB
|
||||
clock Clock
|
||||
random Random
|
||||
clock core.Clock
|
||||
random core.Random
|
||||
}
|
||||
|
||||
func NewAccount(db *sqlx.DB, random Random, clock Clock) Account {
|
||||
return AccountImpl{
|
||||
func NewServiceImpl(db *sqlx.DB, random core.Random, clock core.Clock) Service {
|
||||
return ServiceImpl{
|
||||
db: db,
|
||||
clock: clock,
|
||||
random: random,
|
||||
}
|
||||
}
|
||||
|
||||
func (s AccountImpl) Add(ctx context.Context, user *types.User, name string) (*types.Account, error) {
|
||||
func (s ServiceImpl) Add(ctx context.Context, user *auth_types.User, name string) (*Account, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
|
||||
newId, err := s.random.UUID(ctx)
|
||||
if err != nil {
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
err = validateString(name, "name")
|
||||
err = core.ValidateString(name, "name")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
account := &types.Account{
|
||||
account := &Account{
|
||||
Id: newId,
|
||||
UserId: user.Id,
|
||||
|
||||
@@ -68,7 +68,7 @@ func (s AccountImpl) Add(ctx context.Context, user *types.User, name string) (*t
|
||||
r, err := s.db.NamedExecContext(ctx, `
|
||||
INSERT INTO account (id, user_id, name, current_balance, oink_balance, created_at, created_by)
|
||||
VALUES (:id, :user_id, :name, :current_balance, :oink_balance, :created_at, :created_by)`, account)
|
||||
err = db.TransformAndLogDbError(ctx, "account Insert", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "account Insert", r, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -76,22 +76,22 @@ func (s AccountImpl) Add(ctx context.Context, user *types.User, name string) (*t
|
||||
return account, nil
|
||||
}
|
||||
|
||||
func (s AccountImpl) UpdateName(ctx context.Context, user *types.User, id string, name string) (*types.Account, error) {
|
||||
func (s ServiceImpl) UpdateName(ctx context.Context, user *auth_types.User, id string, name string) (*Account, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
err := validateString(name, "name")
|
||||
err := core.ValidateString(name, "name")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
uuid, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "account update", "err", err)
|
||||
return nil, fmt.Errorf("could not parse Id: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("could not parse Id: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
err = db.TransformAndLogDbError(ctx, "account Update", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "account Update", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -99,14 +99,14 @@ func (s AccountImpl) UpdateName(ctx context.Context, user *types.User, id string
|
||||
_ = tx.Rollback()
|
||||
}()
|
||||
|
||||
var account types.Account
|
||||
var account Account
|
||||
err = tx.GetContext(ctx, &account, `SELECT * FROM account WHERE user_id = ? AND id = ?`, user.Id, uuid)
|
||||
err = db.TransformAndLogDbError(ctx, "account Update", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "account Update", nil, err)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return nil, fmt.Errorf("account %v not found: %w", id, ErrBadRequest)
|
||||
if errors.Is(err, core.ErrNotFound) {
|
||||
return nil, fmt.Errorf("account %v not found: %w", id, core.ErrBadRequest)
|
||||
}
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
timestamp := s.clock.Now()
|
||||
@@ -122,13 +122,13 @@ func (s AccountImpl) UpdateName(ctx context.Context, user *types.User, id string
|
||||
updated_by = :updated_by
|
||||
WHERE id = :id
|
||||
AND user_id = :user_id`, account)
|
||||
err = db.TransformAndLogDbError(ctx, "account Update", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "account Update", r, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
err = db.TransformAndLogDbError(ctx, "account Update", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "account Update", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -136,20 +136,20 @@ func (s AccountImpl) UpdateName(ctx context.Context, user *types.User, id string
|
||||
return &account, nil
|
||||
}
|
||||
|
||||
func (s AccountImpl) Get(ctx context.Context, user *types.User, id string) (*types.Account, error) {
|
||||
func (s ServiceImpl) Get(ctx context.Context, user *auth_types.User, id string) (*Account, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
uuid, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "account get", "err", err)
|
||||
return nil, fmt.Errorf("could not parse Id: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("could not parse Id: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
var account types.Account
|
||||
var account Account
|
||||
err = s.db.GetContext(ctx, &account, `
|
||||
SELECT * FROM account WHERE user_id = ? AND id = ?`, user.Id, uuid)
|
||||
err = db.TransformAndLogDbError(ctx, "account Get", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "account Get", nil, err)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "account get", "err", err)
|
||||
return nil, err
|
||||
@@ -158,15 +158,15 @@ func (s AccountImpl) Get(ctx context.Context, user *types.User, id string) (*typ
|
||||
return &account, nil
|
||||
}
|
||||
|
||||
func (s AccountImpl) GetAll(ctx context.Context, user *types.User) ([]*types.Account, error) {
|
||||
func (s ServiceImpl) GetAll(ctx context.Context, user *auth_types.User) ([]*Account, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
|
||||
accounts := make([]*types.Account, 0)
|
||||
accounts := make([]*Account, 0)
|
||||
err := s.db.SelectContext(ctx, &accounts, `
|
||||
SELECT * FROM account WHERE user_id = ? ORDER BY name`, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "account GetAll", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "account GetAll", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -174,18 +174,18 @@ func (s AccountImpl) GetAll(ctx context.Context, user *types.User) ([]*types.Acc
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
func (s AccountImpl) Delete(ctx context.Context, user *types.User, id string) error {
|
||||
func (s ServiceImpl) Delete(ctx context.Context, user *auth_types.User, id string) error {
|
||||
if user == nil {
|
||||
return ErrUnauthorized
|
||||
return core.ErrUnauthorized
|
||||
}
|
||||
uuid, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "account delete", "err", err)
|
||||
return fmt.Errorf("could not parse Id: %w", ErrBadRequest)
|
||||
return fmt.Errorf("could not parse Id: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
err = db.TransformAndLogDbError(ctx, "account Delete", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "account Delete", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -195,22 +195,22 @@ func (s AccountImpl) Delete(ctx context.Context, user *types.User, id string) er
|
||||
|
||||
transactionsCount := 0
|
||||
err = tx.GetContext(ctx, &transactionsCount, `SELECT COUNT(*) FROM "transaction" WHERE user_id = ? AND account_id = ?`, user.Id, uuid)
|
||||
err = db.TransformAndLogDbError(ctx, "account Delete", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "account Delete", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if transactionsCount > 0 {
|
||||
return fmt.Errorf("account has transactions, cannot delete: %w", ErrBadRequest)
|
||||
return fmt.Errorf("account has transactions, cannot delete: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
res, err := tx.ExecContext(ctx, "DELETE FROM account WHERE id = ? and user_id = ?", uuid, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "account Delete", res, err)
|
||||
err = core.TransformAndLogDbError(ctx, "account Delete", res, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
err = db.TransformAndLogDbError(ctx, "account Delete", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "account Delete", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -3,7 +3,7 @@ package account
|
||||
import "spend-sparrow/internal/template/svg"
|
||||
import "spend-sparrow/internal/types"
|
||||
|
||||
templ Account(accounts []*types.Account) {
|
||||
templ template(accounts []*Account) {
|
||||
<div class="max-w-6xl mt-10 mx-auto">
|
||||
<button
|
||||
hx-get="/account/new"
|
||||
@@ -16,28 +16,28 @@ templ Account(accounts []*types.Account) {
|
||||
</button>
|
||||
<div id="account-items" class="my-6 flex flex-col items-center">
|
||||
for _, account := range accounts {
|
||||
@AccountItem(account)
|
||||
@accountItem(account)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
templ EditAccount(account *types.Account) {
|
||||
templ editAccount(account *Account) {
|
||||
{{
|
||||
var (
|
||||
name string
|
||||
id string
|
||||
cancelUrl string
|
||||
)
|
||||
if account == nil {
|
||||
name = ""
|
||||
id = "new"
|
||||
cancelUrl = "/empty"
|
||||
} else {
|
||||
name = account.Name
|
||||
id = account.Id.String()
|
||||
cancelUrl = "/account/" + id
|
||||
}
|
||||
var (
|
||||
name string
|
||||
id string
|
||||
cancelUrl string
|
||||
)
|
||||
if account == nil {
|
||||
name = ""
|
||||
id = "new"
|
||||
cancelUrl = "/empty"
|
||||
} else {
|
||||
name = account.Name
|
||||
id = account.Id.String()
|
||||
cancelUrl = "/account/" + id
|
||||
}
|
||||
}}
|
||||
<div id="account" class="border-1 border-gray-300 w-full my-4 p-4 bg-gray-50 rounded-lg">
|
||||
<form
|
||||
@@ -77,7 +77,7 @@ templ EditAccount(account *types.Account) {
|
||||
</div>
|
||||
}
|
||||
|
||||
templ AccountItem(account *types.Account) {
|
||||
templ accountItem(account *Account) {
|
||||
<div id="account" class="border-1 border-gray-300 w-full my-4 p-4 bg-gray-50 rounded-lg">
|
||||
<div class="text-xl flex justify-end gap-4">
|
||||
<p class="mr-auto">{ account.Name }</p>
|
||||
@@ -1,9 +1,8 @@
|
||||
package types
|
||||
package account
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The Account holds money.
|
||||
@@ -1,4 +1,4 @@
|
||||
package types
|
||||
package auth_types
|
||||
|
||||
import (
|
||||
"time"
|
||||
@@ -1,11 +1,12 @@
|
||||
package db
|
||||
package authentication
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/auth_types"
|
||||
"spend-sparrow/internal/core"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -13,36 +14,36 @@ import (
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
type Auth interface {
|
||||
InsertUser(ctx context.Context, user *types.User) error
|
||||
UpdateUser(ctx context.Context, user *types.User) error
|
||||
GetUserByEmail(ctx context.Context, email string) (*types.User, error)
|
||||
GetUser(ctx context.Context, userId uuid.UUID) (*types.User, error)
|
||||
type Db interface {
|
||||
InsertUser(ctx context.Context, user *auth_types.User) error
|
||||
UpdateUser(ctx context.Context, user *auth_types.User) error
|
||||
GetUserByEmail(ctx context.Context, email string) (*auth_types.User, error)
|
||||
GetUser(ctx context.Context, userId uuid.UUID) (*auth_types.User, error)
|
||||
DeleteUser(ctx context.Context, userId uuid.UUID) error
|
||||
|
||||
InsertToken(ctx context.Context, token *types.Token) error
|
||||
GetToken(ctx context.Context, token string) (*types.Token, error)
|
||||
GetTokensByUserIdAndType(ctx context.Context, userId uuid.UUID, tokenType types.TokenType) ([]*types.Token, error)
|
||||
GetTokensBySessionIdAndType(ctx context.Context, sessionId string, tokenType types.TokenType) ([]*types.Token, error)
|
||||
InsertToken(ctx context.Context, token *auth_types.Token) error
|
||||
GetToken(ctx context.Context, token string) (*auth_types.Token, error)
|
||||
GetTokensByUserIdAndType(ctx context.Context, userId uuid.UUID, tokenType auth_types.TokenType) ([]*auth_types.Token, error)
|
||||
GetTokensBySessionIdAndType(ctx context.Context, sessionId string, tokenType auth_types.TokenType) ([]*auth_types.Token, error)
|
||||
DeleteToken(ctx context.Context, token string) error
|
||||
|
||||
InsertSession(ctx context.Context, session *types.Session) error
|
||||
GetSession(ctx context.Context, sessionId string) (*types.Session, error)
|
||||
GetSessions(ctx context.Context, userId uuid.UUID) ([]*types.Session, error)
|
||||
InsertSession(ctx context.Context, session *auth_types.Session) error
|
||||
GetSession(ctx context.Context, sessionId string) (*auth_types.Session, error)
|
||||
GetSessions(ctx context.Context, userId uuid.UUID) ([]*auth_types.Session, error)
|
||||
DeleteSession(ctx context.Context, sessionId string) error
|
||||
DeleteOldSessions(ctx context.Context) error
|
||||
DeleteOldTokens(ctx context.Context) error
|
||||
}
|
||||
|
||||
type AuthSqlite struct {
|
||||
type DbSqlite struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewAuthSqlite(db *sqlx.DB) *AuthSqlite {
|
||||
return &AuthSqlite{db: db}
|
||||
func NewDbSqlite(db *sqlx.DB) *DbSqlite {
|
||||
return &DbSqlite{db: db}
|
||||
}
|
||||
|
||||
func (db AuthSqlite) InsertUser(ctx context.Context, user *types.User) error {
|
||||
func (db DbSqlite) InsertUser(ctx context.Context, user *auth_types.User) error {
|
||||
_, err := db.db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, email_verified_at, is_admin, password, salt, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
@@ -50,17 +51,17 @@ func (db AuthSqlite) InsertUser(ctx context.Context, user *types.User) error {
|
||||
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "email") {
|
||||
return ErrAlreadyExists
|
||||
return core.ErrAlreadyExists
|
||||
}
|
||||
|
||||
slog.ErrorContext(ctx, "SQL error InsertUser", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (db AuthSqlite) UpdateUser(ctx context.Context, user *types.User) error {
|
||||
func (db DbSqlite) UpdateUser(ctx context.Context, user *auth_types.User) error {
|
||||
_, err := db.db.ExecContext(ctx, `
|
||||
UPDATE user
|
||||
SET email_verified = ?, email_verified_at = ?, password = ?
|
||||
@@ -69,13 +70,13 @@ func (db AuthSqlite) UpdateUser(ctx context.Context, user *types.User) error {
|
||||
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "SQL error UpdateUser", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (db AuthSqlite) GetUserByEmail(ctx context.Context, email string) (*types.User, error) {
|
||||
func (db DbSqlite) GetUserByEmail(ctx context.Context, email string) (*auth_types.User, error) {
|
||||
var (
|
||||
userId uuid.UUID
|
||||
emailVerified bool
|
||||
@@ -92,17 +93,17 @@ func (db AuthSqlite) GetUserByEmail(ctx context.Context, email string) (*types.U
|
||||
WHERE email = ?`, email).Scan(&userId, &emailVerified, &emailVerifiedAt, &password, &salt, &createdAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
return nil, core.ErrNotFound
|
||||
} else {
|
||||
slog.ErrorContext(ctx, "SQL error GetUser", "err", err)
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
}
|
||||
|
||||
return types.NewUser(userId, email, emailVerified, emailVerifiedAt, isAdmin, password, salt, createdAt), nil
|
||||
return auth_types.NewUser(userId, email, emailVerified, emailVerifiedAt, isAdmin, password, salt, createdAt), nil
|
||||
}
|
||||
|
||||
func (db AuthSqlite) GetUser(ctx context.Context, userId uuid.UUID) (*types.User, error) {
|
||||
func (db DbSqlite) GetUser(ctx context.Context, userId uuid.UUID) (*auth_types.User, error) {
|
||||
var (
|
||||
email string
|
||||
emailVerified bool
|
||||
@@ -119,92 +120,92 @@ func (db AuthSqlite) GetUser(ctx context.Context, userId uuid.UUID) (*types.User
|
||||
WHERE user_id = ?`, userId).Scan(&email, &emailVerified, &emailVerifiedAt, &password, &salt, &createdAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
return nil, core.ErrNotFound
|
||||
} else {
|
||||
slog.ErrorContext(ctx, "SQL error GetUser", "err", err)
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
}
|
||||
|
||||
return types.NewUser(userId, email, emailVerified, emailVerifiedAt, isAdmin, password, salt, createdAt), nil
|
||||
return auth_types.NewUser(userId, email, emailVerified, emailVerifiedAt, isAdmin, password, salt, createdAt), nil
|
||||
}
|
||||
|
||||
func (db AuthSqlite) DeleteUser(ctx context.Context, userId uuid.UUID) error {
|
||||
func (db DbSqlite) DeleteUser(ctx context.Context, userId uuid.UUID) error {
|
||||
tx, err := db.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not start transaction", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
_, err = tx.ExecContext(ctx, "DELETE FROM account WHERE user_id = ?", userId)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
slog.ErrorContext(ctx, "Could not delete accounts", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
_, err = tx.ExecContext(ctx, "DELETE FROM token WHERE user_id = ?", userId)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
slog.ErrorContext(ctx, "Could not delete user tokens", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
_, err = tx.ExecContext(ctx, "DELETE FROM session WHERE user_id = ?", userId)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
slog.ErrorContext(ctx, "Could not delete sessions", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
_, err = tx.ExecContext(ctx, "DELETE FROM user WHERE user_id = ?", userId)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
slog.ErrorContext(ctx, "Could not delete user", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
_, err = tx.ExecContext(ctx, "DELETE FROM treasure_chest WHERE user_id = ?", userId)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
slog.ErrorContext(ctx, "Could not delete user", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
_, err = tx.ExecContext(ctx, "DELETE FROM \"transaction\" WHERE user_id = ?", userId)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
slog.ErrorContext(ctx, "Could not delete user", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not commit transaction", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (db AuthSqlite) InsertToken(ctx context.Context, token *types.Token) error {
|
||||
func (db DbSqlite) InsertToken(ctx context.Context, token *auth_types.Token) error {
|
||||
_, err := db.db.ExecContext(ctx, `
|
||||
INSERT INTO token (user_id, session_id, type, token, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`, token.UserId, token.SessionId, token.Type, token.Token, token.CreatedAt, token.ExpiresAt)
|
||||
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not insert token", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (db AuthSqlite) GetToken(ctx context.Context, token string) (*types.Token, error) {
|
||||
func (db DbSqlite) GetToken(ctx context.Context, token string) (*auth_types.Token, error) {
|
||||
var (
|
||||
userId uuid.UUID
|
||||
sessionId string
|
||||
tokenType types.TokenType
|
||||
tokenType auth_types.TokenType
|
||||
createdAtStr string
|
||||
expiresAtStr string
|
||||
createdAt time.Time
|
||||
@@ -219,29 +220,29 @@ func (db AuthSqlite) GetToken(ctx context.Context, token string) (*types.Token,
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
slog.InfoContext(ctx, "Token not found", "token", token)
|
||||
return nil, ErrNotFound
|
||||
return nil, core.ErrNotFound
|
||||
} else {
|
||||
slog.ErrorContext(ctx, "Could not get token", "err", err)
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
}
|
||||
|
||||
createdAt, err = time.Parse(time.RFC3339, createdAtStr)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not parse token.created_at", "err", err)
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
expiresAt, err = time.Parse(time.RFC3339, expiresAtStr)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not parse token.expires_at", "err", err)
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
return types.NewToken(userId, sessionId, token, tokenType, createdAt, expiresAt), nil
|
||||
return auth_types.NewToken(userId, sessionId, token, tokenType, createdAt, expiresAt), nil
|
||||
}
|
||||
|
||||
func (db AuthSqlite) GetTokensByUserIdAndType(ctx context.Context, userId uuid.UUID, tokenType types.TokenType) ([]*types.Token, error) {
|
||||
func (db DbSqlite) GetTokensByUserIdAndType(ctx context.Context, userId uuid.UUID, tokenType auth_types.TokenType) ([]*auth_types.Token, error) {
|
||||
query, err := db.db.QueryContext(ctx, `
|
||||
SELECT token, created_at, expires_at
|
||||
FROM token
|
||||
@@ -250,13 +251,13 @@ func (db AuthSqlite) GetTokensByUserIdAndType(ctx context.Context, userId uuid.U
|
||||
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not get token", "err", err)
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
return getTokensFromQuery(ctx, query, userId, "", tokenType)
|
||||
}
|
||||
|
||||
func (db AuthSqlite) GetTokensBySessionIdAndType(ctx context.Context, sessionId string, tokenType types.TokenType) ([]*types.Token, error) {
|
||||
func (db DbSqlite) GetTokensBySessionIdAndType(ctx context.Context, sessionId string, tokenType auth_types.TokenType) ([]*auth_types.Token, error) {
|
||||
query, err := db.db.QueryContext(ctx, `
|
||||
SELECT token, created_at, expires_at
|
||||
FROM token
|
||||
@@ -265,14 +266,14 @@ func (db AuthSqlite) GetTokensBySessionIdAndType(ctx context.Context, sessionId
|
||||
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not get token", "err", err)
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
return getTokensFromQuery(ctx, query, uuid.Nil, sessionId, tokenType)
|
||||
}
|
||||
|
||||
func getTokensFromQuery(ctx context.Context, query *sql.Rows, userId uuid.UUID, sessionId string, tokenType types.TokenType) ([]*types.Token, error) {
|
||||
var tokens []*types.Token
|
||||
func getTokensFromQuery(ctx context.Context, query *sql.Rows, userId uuid.UUID, sessionId string, tokenType auth_types.TokenType) ([]*auth_types.Token, error) {
|
||||
var tokens []*auth_types.Token
|
||||
|
||||
hasRows := false
|
||||
for query.Next() {
|
||||
@@ -289,54 +290,54 @@ func getTokensFromQuery(ctx context.Context, query *sql.Rows, userId uuid.UUID,
|
||||
err := query.Scan(&token, &createdAtStr, &expiresAtStr)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not scan token", "err", err)
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
createdAt, err = time.Parse(time.RFC3339, createdAtStr)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not parse token.created_at", "err", err)
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
expiresAt, err = time.Parse(time.RFC3339, expiresAtStr)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not parse token.expires_at", "err", err)
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
tokens = append(tokens, types.NewToken(userId, sessionId, token, tokenType, createdAt, expiresAt))
|
||||
tokens = append(tokens, auth_types.NewToken(userId, sessionId, token, tokenType, createdAt, expiresAt))
|
||||
}
|
||||
|
||||
if !hasRows {
|
||||
return nil, ErrNotFound
|
||||
return nil, core.ErrNotFound
|
||||
}
|
||||
|
||||
return tokens, nil
|
||||
}
|
||||
|
||||
func (db AuthSqlite) DeleteToken(ctx context.Context, token string) error {
|
||||
func (db DbSqlite) DeleteToken(ctx context.Context, token string) error {
|
||||
_, err := db.db.ExecContext(ctx, "DELETE FROM token WHERE token = ?", token)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not delete token", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (db AuthSqlite) InsertSession(ctx context.Context, session *types.Session) error {
|
||||
func (db DbSqlite) InsertSession(ctx context.Context, session *auth_types.Session) error {
|
||||
_, err := db.db.ExecContext(ctx, `
|
||||
INSERT INTO session (session_id, user_id, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?)`, session.Id, session.UserId, session.CreatedAt, session.ExpiresAt)
|
||||
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not insert new session", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (db AuthSqlite) GetSession(ctx context.Context, sessionId string) (*types.Session, error) {
|
||||
func (db DbSqlite) GetSession(ctx context.Context, sessionId string) (*auth_types.Session, error) {
|
||||
var (
|
||||
userId uuid.UUID
|
||||
createdAt time.Time
|
||||
@@ -350,56 +351,56 @@ func (db AuthSqlite) GetSession(ctx context.Context, sessionId string) (*types.S
|
||||
|
||||
if err != nil {
|
||||
slog.WarnContext(ctx, "Session not found", "session-id", sessionId, "err", err)
|
||||
return nil, ErrNotFound
|
||||
return nil, core.ErrNotFound
|
||||
}
|
||||
|
||||
return types.NewSession(sessionId, userId, createdAt, expiresAt), nil
|
||||
return auth_types.NewSession(sessionId, userId, createdAt, expiresAt), nil
|
||||
}
|
||||
|
||||
func (db AuthSqlite) GetSessions(ctx context.Context, userId uuid.UUID) ([]*types.Session, error) {
|
||||
var sessions []*types.Session
|
||||
func (db DbSqlite) GetSessions(ctx context.Context, userId uuid.UUID) ([]*auth_types.Session, error) {
|
||||
var sessions []*auth_types.Session
|
||||
err := db.db.SelectContext(ctx, &sessions, `
|
||||
SELECT *
|
||||
FROM session
|
||||
WHERE user_id = ?`, userId)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not get sessions", "err", err)
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
return sessions, nil
|
||||
}
|
||||
|
||||
func (db AuthSqlite) DeleteSession(ctx context.Context, sessionId string) error {
|
||||
func (db DbSqlite) DeleteSession(ctx context.Context, sessionId string) error {
|
||||
if sessionId != "" {
|
||||
_, err := db.db.ExecContext(ctx, "DELETE FROM session WHERE session_id = ?", sessionId)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not delete session", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (db AuthSqlite) DeleteOldSessions(ctx context.Context) error {
|
||||
func (db DbSqlite) DeleteOldSessions(ctx context.Context) error {
|
||||
_, err := db.db.ExecContext(ctx, `
|
||||
DELETE FROM session
|
||||
WHERE expires_at < datetime('now')`)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not delete old sessions", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (db AuthSqlite) DeleteOldTokens(ctx context.Context) error {
|
||||
func (db DbSqlite) DeleteOldTokens(ctx context.Context) error {
|
||||
_, err := db.db.ExecContext(ctx, `
|
||||
DELETE FROM token
|
||||
WHERE expires_at < datetime('now')`)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not delete old tokens", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,35 +1,34 @@
|
||||
package handler
|
||||
package authentication
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"spend-sparrow/internal/handler/middleware"
|
||||
"spend-sparrow/internal/service"
|
||||
"spend-sparrow/internal/template/auth"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/auth_types"
|
||||
"spend-sparrow/internal/authentication/template"
|
||||
"spend-sparrow/internal/core"
|
||||
"spend-sparrow/internal/utils"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Auth interface {
|
||||
type Handler interface {
|
||||
Handle(router *http.ServeMux)
|
||||
}
|
||||
|
||||
type AuthImpl struct {
|
||||
service service.Auth
|
||||
render *Render
|
||||
type HandlerImpl struct {
|
||||
service Service
|
||||
render *core.Render
|
||||
}
|
||||
|
||||
func NewAuth(service service.Auth, render *Render) Auth {
|
||||
return AuthImpl{
|
||||
func NewHandler(service Service, render *core.Render) Handler {
|
||||
return HandlerImpl{
|
||||
service: service,
|
||||
render: render,
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) Handle(router *http.ServeMux) {
|
||||
func (handler HandlerImpl) Handle(router *http.ServeMux) {
|
||||
router.Handle("GET /auth/signin", handler.handleSignInPage())
|
||||
router.Handle("POST /api/auth/signin", handler.handleSignIn())
|
||||
|
||||
@@ -56,11 +55,11 @@ var (
|
||||
securityWaitDuration = 250 * time.Millisecond
|
||||
)
|
||||
|
||||
func (handler AuthImpl) handleSignInPage() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleSignInPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user != nil {
|
||||
if !user.EmailVerified {
|
||||
utils.DoRedirect(w, r, "/auth/verify")
|
||||
@@ -70,18 +69,18 @@ func (handler AuthImpl) handleSignInPage() http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
comp := auth.SignInOrUpComp(true)
|
||||
comp := template.SignInOrUpComp(true)
|
||||
|
||||
handler.render.RenderLayout(r, w, comp, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleSignIn() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleSignIn() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user, err := utils.WaitMinimumTime(securityWaitDuration, func() (*types.User, error) {
|
||||
session := middleware.GetSession(r)
|
||||
user, err := utils.WaitMinimumTime(securityWaitDuration, func() (*auth_types.User, error) {
|
||||
session := core.GetSession(r)
|
||||
email := r.FormValue("email")
|
||||
password := r.FormValue("password")
|
||||
|
||||
@@ -90,14 +89,14 @@ func (handler AuthImpl) handleSignIn() http.HandlerFunc {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cookie := middleware.CreateSessionCookie(session.Id)
|
||||
cookie := core.CreateSessionCookie(session.Id)
|
||||
http.SetCookie(w, &cookie)
|
||||
|
||||
return user, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrInvalidCredentials) {
|
||||
if errors.Is(err, ErrInvalidCredentials) {
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", "Invalid email or password", http.StatusUnauthorized)
|
||||
} else {
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", "An error occurred", http.StatusInternalServerError)
|
||||
@@ -113,11 +112,11 @@ func (handler AuthImpl) handleSignIn() http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleSignUpPage() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleSignUpPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
|
||||
if user != nil {
|
||||
if !user.EmailVerified {
|
||||
@@ -128,16 +127,16 @@ func (handler AuthImpl) handleSignUpPage() http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
signUpComp := auth.SignInOrUpComp(false)
|
||||
signUpComp := template.SignInOrUpComp(false)
|
||||
handler.render.RenderLayout(r, w, signUpComp, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleSignUpVerifyPage() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleSignUpVerifyPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -148,16 +147,16 @@ func (handler AuthImpl) handleSignUpVerifyPage() http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
signIn := auth.VerifyComp()
|
||||
signIn := template.VerifyComp()
|
||||
handler.render.RenderLayout(r, w, signIn, user)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleVerifyResendComp() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleVerifyResendComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -172,16 +171,16 @@ func (handler AuthImpl) handleVerifyResendComp() http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleSignUpVerifyResponsePage() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleSignUpVerifyResponsePage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
token := r.URL.Query().Get("token")
|
||||
|
||||
err := handler.service.VerifyUserEmail(r.Context(), token)
|
||||
|
||||
isVerified := err == nil
|
||||
comp := auth.VerifyResponseComp(isVerified)
|
||||
comp := template.VerifyResponseComp(isVerified)
|
||||
|
||||
var status int
|
||||
if isVerified {
|
||||
@@ -194,9 +193,9 @@ func (handler AuthImpl) handleSignUpVerifyResponsePage() http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleSignUp() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleSignUp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
var email = r.FormValue("email")
|
||||
var password = r.FormValue("password")
|
||||
@@ -215,14 +214,14 @@ func (handler AuthImpl) handleSignUp() http.HandlerFunc {
|
||||
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, types.ErrInternal):
|
||||
case errors.Is(err, core.ErrInternal):
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", "An error occurred", http.StatusInternalServerError)
|
||||
return
|
||||
case errors.Is(err, service.ErrInvalidEmail):
|
||||
case errors.Is(err, ErrInvalidEmail):
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", "The email provided is invalid", http.StatusBadRequest)
|
||||
return
|
||||
case errors.Is(err, service.ErrInvalidPassword):
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", service.ErrInvalidPassword.Error(), http.StatusBadRequest)
|
||||
case errors.Is(err, ErrInvalidPassword):
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", ErrInvalidPassword.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// If err is "service.ErrAccountExists", then just continue
|
||||
@@ -232,11 +231,11 @@ func (handler AuthImpl) handleSignUp() http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleSignOut() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleSignOut() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
session := middleware.GetSession(r)
|
||||
session := core.GetSession(r)
|
||||
|
||||
if session != nil {
|
||||
err := handler.service.SignOut(r.Context(), session.Id)
|
||||
@@ -261,26 +260,26 @@ func (handler AuthImpl) handleSignOut() http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleDeleteAccountPage() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleDeleteAccountPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
comp := auth.DeleteAccountComp()
|
||||
comp := template.DeleteAccountComp()
|
||||
handler.render.RenderLayout(r, w, comp, user)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleDeleteAccountComp() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleDeleteAccountComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -290,7 +289,7 @@ func (handler AuthImpl) handleDeleteAccountComp() http.HandlerFunc {
|
||||
|
||||
err := handler.service.DeleteAccount(r.Context(), user, password)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrInvalidCredentials) {
|
||||
if errors.Is(err, ErrInvalidCredentials) {
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", "Password not correct", http.StatusBadRequest)
|
||||
} else {
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", "Internal Server Error", http.StatusInternalServerError)
|
||||
@@ -302,30 +301,30 @@ func (handler AuthImpl) handleDeleteAccountComp() http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleChangePasswordPage() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleChangePasswordPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
isPasswordReset := r.URL.Query().Has("token")
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
|
||||
if user == nil && !isPasswordReset {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
comp := auth.ChangePasswordComp(isPasswordReset)
|
||||
comp := template.ChangePasswordComp(isPasswordReset)
|
||||
handler.render.RenderLayout(r, w, comp, user)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleChangePasswordComp() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleChangePasswordComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
session := middleware.GetSession(r)
|
||||
user := middleware.GetUser(r)
|
||||
session := core.GetSession(r)
|
||||
user := core.GetUser(r)
|
||||
if session == nil || user == nil {
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", "Unathorized", http.StatusUnauthorized)
|
||||
return
|
||||
@@ -344,24 +343,24 @@ func (handler AuthImpl) handleChangePasswordComp() http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleForgotPasswordPage() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleForgotPasswordPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user != nil {
|
||||
utils.DoRedirect(w, r, "/")
|
||||
return
|
||||
}
|
||||
|
||||
comp := auth.ResetPasswordComp()
|
||||
comp := template.ResetPasswordComp()
|
||||
handler.render.RenderLayout(r, w, comp, user)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleForgotPasswordComp() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleForgotPasswordComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
email := r.FormValue("email")
|
||||
if email == "" {
|
||||
@@ -382,9 +381,9 @@ func (handler AuthImpl) handleForgotPasswordComp() http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleForgotPasswordResponseComp() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleForgotPasswordResponseComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
pageUrl, err := url.Parse(r.Header.Get("Hx-Current-Url"))
|
||||
if err != nil {
|
||||
@@ -1,4 +1,4 @@
|
||||
package service
|
||||
package authentication
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -6,7 +6,8 @@ import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/mail"
|
||||
"spend-sparrow/internal/db"
|
||||
"spend-sparrow/internal/auth_types"
|
||||
"spend-sparrow/internal/core"
|
||||
mailTemplate "spend-sparrow/internal/template/mail"
|
||||
"spend-sparrow/internal/types"
|
||||
"strings"
|
||||
@@ -25,39 +26,39 @@ var (
|
||||
ErrTokenInvalid = errors.New("token is invalid")
|
||||
)
|
||||
|
||||
type Auth interface {
|
||||
SignUp(ctx context.Context, email string, password string) (*types.User, error)
|
||||
type Service interface {
|
||||
SignUp(ctx context.Context, email string, password string) (*auth_types.User, error)
|
||||
SendVerificationMail(ctx context.Context, userId uuid.UUID, email string)
|
||||
VerifyUserEmail(ctx context.Context, token string) error
|
||||
|
||||
SignIn(ctx context.Context, session *types.Session, email string, password string) (*types.Session, *types.User, error)
|
||||
SignInSession(ctx context.Context, sessionId string) (*types.Session, *types.User, error)
|
||||
SignInAnonymous(ctx context.Context) (*types.Session, error)
|
||||
SignIn(ctx context.Context, session *auth_types.Session, email string, password string) (*auth_types.Session, *auth_types.User, error)
|
||||
SignInSession(ctx context.Context, sessionId string) (*auth_types.Session, *auth_types.User, error)
|
||||
SignInAnonymous(ctx context.Context) (*auth_types.Session, error)
|
||||
SignOut(ctx context.Context, sessionId string) error
|
||||
|
||||
DeleteAccount(ctx context.Context, user *types.User, currPass string) error
|
||||
DeleteAccount(ctx context.Context, user *auth_types.User, currPass string) error
|
||||
|
||||
ChangePassword(ctx context.Context, user *types.User, sessionId string, currPass, newPass string) error
|
||||
ChangePassword(ctx context.Context, user *auth_types.User, sessionId string, currPass, newPass string) error
|
||||
|
||||
SendForgotPasswordMail(ctx context.Context, email string) error
|
||||
ForgotPassword(ctx context.Context, token string, newPass string) error
|
||||
|
||||
IsCsrfTokenValid(ctx context.Context, tokenStr string, sessionId string) bool
|
||||
GetCsrfToken(ctx context.Context, session *types.Session) (string, error)
|
||||
GetCsrfToken(ctx context.Context, session *auth_types.Session) (string, error)
|
||||
|
||||
CleanupSessionsAndTokens(ctx context.Context) error
|
||||
}
|
||||
|
||||
type AuthImpl struct {
|
||||
db db.Auth
|
||||
random Random
|
||||
clock Clock
|
||||
mail Mail
|
||||
type ServiceImpl struct {
|
||||
db Db
|
||||
random core.Random
|
||||
clock core.Clock
|
||||
mail core.Mail
|
||||
serverSettings *types.Settings
|
||||
}
|
||||
|
||||
func NewAuth(db db.Auth, random Random, clock Clock, mail Mail, serverSettings *types.Settings) *AuthImpl {
|
||||
return &AuthImpl{
|
||||
func NewService(db Db, random core.Random, clock core.Clock, mail core.Mail, serverSettings *types.Settings) *ServiceImpl {
|
||||
return &ServiceImpl{
|
||||
db: db,
|
||||
random: random,
|
||||
clock: clock,
|
||||
@@ -66,13 +67,13 @@ func NewAuth(db db.Auth, random Random, clock Clock, mail Mail, serverSettings *
|
||||
}
|
||||
}
|
||||
|
||||
func (service AuthImpl) SignIn(ctx context.Context, session *types.Session, email string, password string) (*types.Session, *types.User, error) {
|
||||
func (service ServiceImpl) SignIn(ctx context.Context, session *auth_types.Session, email string, password string) (*auth_types.Session, *auth_types.User, error) {
|
||||
user, err := service.db.GetUserByEmail(ctx, email)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
if errors.Is(err, core.ErrNotFound) {
|
||||
return nil, nil, ErrInvalidCredentials
|
||||
} else {
|
||||
return nil, nil, types.ErrInternal
|
||||
return nil, nil, core.ErrInternal
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,36 +85,36 @@ func (service AuthImpl) SignIn(ctx context.Context, session *types.Session, emai
|
||||
|
||||
newSession, err := service.createSession(ctx, user.Id)
|
||||
if err != nil {
|
||||
return nil, nil, types.ErrInternal
|
||||
return nil, nil, core.ErrInternal
|
||||
}
|
||||
|
||||
err = service.db.DeleteSession(ctx, session.Id)
|
||||
if err != nil {
|
||||
return nil, nil, types.ErrInternal
|
||||
return nil, nil, core.ErrInternal
|
||||
}
|
||||
|
||||
tokens, err := service.db.GetTokensBySessionIdAndType(ctx, session.Id, types.TokenTypeCsrf)
|
||||
tokens, err := service.db.GetTokensBySessionIdAndType(ctx, session.Id, auth_types.TokenTypeCsrf)
|
||||
if err != nil {
|
||||
return nil, nil, types.ErrInternal
|
||||
return nil, nil, core.ErrInternal
|
||||
}
|
||||
for _, token := range tokens {
|
||||
err = service.db.DeleteToken(ctx, token.Token)
|
||||
if err != nil {
|
||||
return nil, nil, types.ErrInternal
|
||||
return nil, nil, core.ErrInternal
|
||||
}
|
||||
}
|
||||
|
||||
return newSession, user, nil
|
||||
}
|
||||
|
||||
func (service AuthImpl) SignInSession(ctx context.Context, sessionId string) (*types.Session, *types.User, error) {
|
||||
func (service ServiceImpl) SignInSession(ctx context.Context, sessionId string) (*auth_types.Session, *auth_types.User, error) {
|
||||
if sessionId == "" {
|
||||
return nil, nil, ErrSessionIdInvalid
|
||||
}
|
||||
|
||||
session, err := service.db.GetSession(ctx, sessionId)
|
||||
if err != nil {
|
||||
return nil, nil, types.ErrInternal
|
||||
return nil, nil, core.ErrInternal
|
||||
}
|
||||
if session.ExpiresAt.Before(service.clock.Now()) {
|
||||
_ = service.db.DeleteSession(ctx, sessionId)
|
||||
@@ -126,16 +127,16 @@ func (service AuthImpl) SignInSession(ctx context.Context, sessionId string) (*t
|
||||
|
||||
user, err := service.db.GetUser(ctx, session.UserId)
|
||||
if err != nil {
|
||||
return nil, nil, types.ErrInternal
|
||||
return nil, nil, core.ErrInternal
|
||||
}
|
||||
|
||||
return session, user, nil
|
||||
}
|
||||
|
||||
func (service AuthImpl) SignInAnonymous(ctx context.Context) (*types.Session, error) {
|
||||
func (service ServiceImpl) SignInAnonymous(ctx context.Context) (*auth_types.Session, error) {
|
||||
session, err := service.createSession(ctx, uuid.Nil)
|
||||
if err != nil {
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
slog.InfoContext(ctx, "anonymous session created", "session-id", session.Id)
|
||||
@@ -143,7 +144,7 @@ func (service AuthImpl) SignInAnonymous(ctx context.Context) (*types.Session, er
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (service AuthImpl) SignUp(ctx context.Context, email string, password string) (*types.User, error) {
|
||||
func (service ServiceImpl) SignUp(ctx context.Context, email string, password string) (*auth_types.User, error) {
|
||||
_, err := mail.ParseAddress(email)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidEmail
|
||||
@@ -155,37 +156,37 @@ func (service AuthImpl) SignUp(ctx context.Context, email string, password strin
|
||||
|
||||
userId, err := service.random.UUID(ctx)
|
||||
if err != nil {
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
salt, err := service.random.Bytes(ctx, 16)
|
||||
if err != nil {
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
hash := GetHashPassword(password, salt)
|
||||
|
||||
user := types.NewUser(userId, email, false, nil, false, hash, salt, service.clock.Now())
|
||||
user := auth_types.NewUser(userId, email, false, nil, false, hash, salt, service.clock.Now())
|
||||
|
||||
err = service.db.InsertUser(ctx, user)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrAlreadyExists) {
|
||||
if errors.Is(err, core.ErrAlreadyExists) {
|
||||
return nil, ErrAccountExists
|
||||
} else {
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (service AuthImpl) SendVerificationMail(ctx context.Context, userId uuid.UUID, email string) {
|
||||
tokens, err := service.db.GetTokensByUserIdAndType(ctx, userId, types.TokenTypeEmailVerify)
|
||||
if err != nil && !errors.Is(err, db.ErrNotFound) {
|
||||
func (service ServiceImpl) SendVerificationMail(ctx context.Context, userId uuid.UUID, email string) {
|
||||
tokens, err := service.db.GetTokensByUserIdAndType(ctx, userId, auth_types.TokenTypeEmailVerify)
|
||||
if err != nil && !errors.Is(err, core.ErrNotFound) {
|
||||
return
|
||||
}
|
||||
|
||||
var token *types.Token
|
||||
var token *auth_types.Token
|
||||
|
||||
if len(tokens) > 0 {
|
||||
token = tokens[0]
|
||||
@@ -197,11 +198,11 @@ func (service AuthImpl) SendVerificationMail(ctx context.Context, userId uuid.UU
|
||||
return
|
||||
}
|
||||
|
||||
token = types.NewToken(
|
||||
token = auth_types.NewToken(
|
||||
userId,
|
||||
"",
|
||||
newTokenStr,
|
||||
types.TokenTypeEmailVerify,
|
||||
auth_types.TokenTypeEmailVerify,
|
||||
service.clock.Now(),
|
||||
service.clock.Now().Add(24*time.Hour))
|
||||
|
||||
@@ -221,29 +222,29 @@ func (service AuthImpl) SendVerificationMail(ctx context.Context, userId uuid.UU
|
||||
service.mail.SendMail(ctx, email, "Welcome to spend-sparrow", w.String())
|
||||
}
|
||||
|
||||
func (service AuthImpl) VerifyUserEmail(ctx context.Context, tokenStr string) error {
|
||||
func (service ServiceImpl) VerifyUserEmail(ctx context.Context, tokenStr string) error {
|
||||
if tokenStr == "" {
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
token, err := service.db.GetToken(ctx, tokenStr)
|
||||
if err != nil {
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
user, err := service.db.GetUser(ctx, token.UserId)
|
||||
if err != nil {
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
if token.Type != types.TokenTypeEmailVerify {
|
||||
return types.ErrInternal
|
||||
if token.Type != auth_types.TokenTypeEmailVerify {
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
now := service.clock.Now()
|
||||
|
||||
if token.ExpiresAt.Before(now) {
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
user.EmailVerified = true
|
||||
@@ -251,21 +252,21 @@ func (service AuthImpl) VerifyUserEmail(ctx context.Context, tokenStr string) er
|
||||
|
||||
err = service.db.UpdateUser(ctx, user)
|
||||
if err != nil {
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
_ = service.db.DeleteToken(ctx, token.Token)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service AuthImpl) SignOut(ctx context.Context, sessionId string) error {
|
||||
func (service ServiceImpl) SignOut(ctx context.Context, sessionId string) error {
|
||||
return service.db.DeleteSession(ctx, sessionId)
|
||||
}
|
||||
|
||||
func (service AuthImpl) DeleteAccount(ctx context.Context, user *types.User, currPass string) error {
|
||||
func (service ServiceImpl) DeleteAccount(ctx context.Context, user *auth_types.User, currPass string) error {
|
||||
userDb, err := service.db.GetUser(ctx, user.Id)
|
||||
if err != nil {
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
currHash := GetHashPassword(currPass, userDb.Salt)
|
||||
@@ -283,7 +284,7 @@ func (service AuthImpl) DeleteAccount(ctx context.Context, user *types.User, cur
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service AuthImpl) ChangePassword(ctx context.Context, user *types.User, sessionId string, currPass, newPass string) error {
|
||||
func (service ServiceImpl) ChangePassword(ctx context.Context, user *auth_types.User, sessionId string, currPass, newPass string) error {
|
||||
if !isPasswordValid(newPass) {
|
||||
return ErrInvalidPassword
|
||||
}
|
||||
@@ -308,13 +309,13 @@ func (service AuthImpl) ChangePassword(ctx context.Context, user *types.User, se
|
||||
|
||||
sessions, err := service.db.GetSessions(ctx, user.Id)
|
||||
if err != nil {
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
for _, s := range sessions {
|
||||
if s.Id != sessionId {
|
||||
err = service.db.DeleteSession(ctx, s.Id)
|
||||
if err != nil {
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -322,7 +323,7 @@ func (service AuthImpl) ChangePassword(ctx context.Context, user *types.User, se
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service AuthImpl) SendForgotPasswordMail(ctx context.Context, email string) error {
|
||||
func (service ServiceImpl) SendForgotPasswordMail(ctx context.Context, email string) error {
|
||||
tokenStr, err := service.random.String(ctx, 32)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -330,38 +331,38 @@ func (service AuthImpl) SendForgotPasswordMail(ctx context.Context, email string
|
||||
|
||||
user, err := service.db.GetUserByEmail(ctx, email)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
if errors.Is(err, core.ErrNotFound) {
|
||||
return nil
|
||||
} else {
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
}
|
||||
|
||||
token := types.NewToken(
|
||||
token := auth_types.NewToken(
|
||||
user.Id,
|
||||
"",
|
||||
tokenStr,
|
||||
types.TokenTypePasswordReset,
|
||||
auth_types.TokenTypePasswordReset,
|
||||
service.clock.Now(),
|
||||
service.clock.Now().Add(15*time.Minute))
|
||||
|
||||
err = service.db.InsertToken(ctx, token)
|
||||
if err != nil {
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
var mail strings.Builder
|
||||
err = mailTemplate.ResetPassword(service.serverSettings.BaseUrl, token.Token).Render(context.Background(), &mail)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not render reset password email", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
service.mail.SendMail(ctx, email, "Reset Password", mail.String())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service AuthImpl) ForgotPassword(ctx context.Context, tokenStr string, newPass string) error {
|
||||
func (service ServiceImpl) ForgotPassword(ctx context.Context, tokenStr string, newPass string) error {
|
||||
if !isPasswordValid(newPass) {
|
||||
return ErrInvalidPassword
|
||||
}
|
||||
@@ -376,7 +377,7 @@ func (service AuthImpl) ForgotPassword(ctx context.Context, tokenStr string, new
|
||||
return err
|
||||
}
|
||||
|
||||
if token.Type != types.TokenTypePasswordReset ||
|
||||
if token.Type != auth_types.TokenTypePasswordReset ||
|
||||
token.ExpiresAt.Before(service.clock.Now()) {
|
||||
return ErrTokenInvalid
|
||||
}
|
||||
@@ -384,7 +385,7 @@ func (service AuthImpl) ForgotPassword(ctx context.Context, tokenStr string, new
|
||||
user, err := service.db.GetUser(ctx, token.UserId)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not get user from token", "err", err)
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
passHash := GetHashPassword(newPass, user.Salt)
|
||||
@@ -397,26 +398,26 @@ func (service AuthImpl) ForgotPassword(ctx context.Context, tokenStr string, new
|
||||
|
||||
sessions, err := service.db.GetSessions(ctx, user.Id)
|
||||
if err != nil {
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
for _, session := range sessions {
|
||||
err = service.db.DeleteSession(ctx, session.Id)
|
||||
if err != nil {
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service AuthImpl) IsCsrfTokenValid(ctx context.Context, tokenStr string, sessionId string) bool {
|
||||
func (service ServiceImpl) IsCsrfTokenValid(ctx context.Context, tokenStr string, sessionId string) bool {
|
||||
token, err := service.db.GetToken(ctx, tokenStr)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if token.Type != types.TokenTypeCsrf ||
|
||||
if token.Type != auth_types.TokenTypeCsrf ||
|
||||
token.SessionId != sessionId ||
|
||||
token.ExpiresAt.Before(service.clock.Now()) {
|
||||
return false
|
||||
@@ -425,12 +426,12 @@ func (service AuthImpl) IsCsrfTokenValid(ctx context.Context, tokenStr string, s
|
||||
return true
|
||||
}
|
||||
|
||||
func (service AuthImpl) GetCsrfToken(ctx context.Context, session *types.Session) (string, error) {
|
||||
func (service ServiceImpl) GetCsrfToken(ctx context.Context, session *auth_types.Session) (string, error) {
|
||||
if session == nil {
|
||||
return "", types.ErrInternal
|
||||
return "", core.ErrInternal
|
||||
}
|
||||
|
||||
tokens, _ := service.db.GetTokensBySessionIdAndType(ctx, session.Id, types.TokenTypeCsrf)
|
||||
tokens, _ := service.db.GetTokensBySessionIdAndType(ctx, session.Id, auth_types.TokenTypeCsrf)
|
||||
|
||||
if len(tokens) > 0 {
|
||||
return tokens[0].Token, nil
|
||||
@@ -438,19 +439,19 @@ func (service AuthImpl) GetCsrfToken(ctx context.Context, session *types.Session
|
||||
|
||||
tokenStr, err := service.random.String(ctx, 32)
|
||||
if err != nil {
|
||||
return "", types.ErrInternal
|
||||
return "", core.ErrInternal
|
||||
}
|
||||
|
||||
token := types.NewToken(
|
||||
token := auth_types.NewToken(
|
||||
session.UserId,
|
||||
session.Id,
|
||||
tokenStr,
|
||||
types.TokenTypeCsrf,
|
||||
auth_types.TokenTypeCsrf,
|
||||
service.clock.Now(),
|
||||
service.clock.Now().Add(8*time.Hour))
|
||||
err = service.db.InsertToken(ctx, token)
|
||||
if err != nil {
|
||||
return "", types.ErrInternal
|
||||
return "", core.ErrInternal
|
||||
}
|
||||
|
||||
slog.InfoContext(ctx, "CSRF-Token created", "token", tokenStr)
|
||||
@@ -458,34 +459,34 @@ func (service AuthImpl) GetCsrfToken(ctx context.Context, session *types.Session
|
||||
return tokenStr, nil
|
||||
}
|
||||
|
||||
func (service AuthImpl) CleanupSessionsAndTokens(ctx context.Context) error {
|
||||
func (service ServiceImpl) CleanupSessionsAndTokens(ctx context.Context) error {
|
||||
err := service.db.DeleteOldSessions(ctx)
|
||||
if err != nil {
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
err = service.db.DeleteOldTokens(ctx)
|
||||
if err != nil {
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service AuthImpl) createSession(ctx context.Context, userId uuid.UUID) (*types.Session, error) {
|
||||
func (service ServiceImpl) createSession(ctx context.Context, userId uuid.UUID) (*auth_types.Session, error) {
|
||||
sessionId, err := service.random.String(ctx, 32)
|
||||
if err != nil {
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
createAt := service.clock.Now()
|
||||
expiresAt := createAt.Add(24 * time.Hour)
|
||||
|
||||
session := types.NewSession(sessionId, userId, createAt, expiresAt)
|
||||
session := auth_types.NewSession(sessionId, userId, createAt, expiresAt)
|
||||
|
||||
err = service.db.InsertSession(ctx, session)
|
||||
if err != nil {
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
return session, nil
|
||||
@@ -1,4 +1,4 @@
|
||||
package auth
|
||||
package template
|
||||
|
||||
templ ChangePasswordComp(isPasswordReset bool) {
|
||||
<form
|
||||
1
internal/authentication/template/default.go
Normal file
1
internal/authentication/template/default.go
Normal file
@@ -0,0 +1 @@
|
||||
package template
|
||||
@@ -1,4 +1,4 @@
|
||||
package auth
|
||||
package template
|
||||
|
||||
templ DeleteAccountComp() {
|
||||
<form
|
||||
@@ -1,4 +1,4 @@
|
||||
package auth
|
||||
package template
|
||||
|
||||
templ ResetPasswordComp() {
|
||||
<form
|
||||
@@ -1,13 +1,13 @@
|
||||
package auth
|
||||
package template
|
||||
|
||||
templ SignInOrUpComp(isSignIn bool) {
|
||||
{{
|
||||
var postUrl string
|
||||
if isSignIn {
|
||||
postUrl = "/api/auth/signin"
|
||||
} else {
|
||||
postUrl = "/api/auth/signup"
|
||||
}
|
||||
var postUrl string
|
||||
if isSignIn {
|
||||
postUrl = "/api/auth/signin"
|
||||
} else {
|
||||
postUrl = "/api/auth/signup"
|
||||
}
|
||||
}}
|
||||
<form
|
||||
class="max-w-xl px-2 mx-auto flex flex-col gap-4 h-full justify-center"
|
||||
@@ -1,4 +1,4 @@
|
||||
package auth
|
||||
package template
|
||||
|
||||
templ VerifyComp() {
|
||||
<main class="h-full">
|
||||
@@ -1,4 +1,4 @@
|
||||
package auth
|
||||
package template
|
||||
|
||||
templ VerifyResponseComp(isVerified bool) {
|
||||
<main>
|
||||
51
internal/core/auth.go
Normal file
51
internal/core/auth.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"spend-sparrow/internal/auth_types"
|
||||
)
|
||||
|
||||
type ContextKey string
|
||||
|
||||
var SessionKey ContextKey = "session"
|
||||
var UserKey ContextKey = "user"
|
||||
|
||||
func GetUser(r *http.Request) *auth_types.User {
|
||||
obj := r.Context().Value(UserKey)
|
||||
if obj == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
user, ok := obj.(*auth_types.User)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
func GetSession(r *http.Request) *auth_types.Session {
|
||||
obj := r.Context().Value(SessionKey)
|
||||
if obj == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
session, ok := obj.(*auth_types.Session)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
return session
|
||||
}
|
||||
|
||||
func CreateSessionCookie(sessionId string) http.Cookie {
|
||||
return http.Cookie{
|
||||
Name: "id",
|
||||
Value: sessionId,
|
||||
MaxAge: 60 * 60 * 8, // 8 hours
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Path: "/",
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package service
|
||||
package core
|
||||
|
||||
import "time"
|
||||
|
||||
71
internal/core/error.go
Normal file
71
internal/core/error.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"spend-sparrow/internal/utils"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("the value does not exist")
|
||||
ErrAlreadyExists = errors.New("row already exists")
|
||||
|
||||
ErrInternal = errors.New("internal server error")
|
||||
ErrUnauthorized = errors.New("you are not authorized to perform this action")
|
||||
|
||||
ErrBadRequest = errors.New("bad request")
|
||||
)
|
||||
|
||||
func TransformAndLogDbError(ctx context.Context, module string, r sql.Result, err error) error {
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
slog.ErrorContext(ctx, "database sql", "module", module, "err", err)
|
||||
return ErrInternal
|
||||
}
|
||||
|
||||
if r != nil {
|
||||
rows, err := r.RowsAffected()
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "database rows affected", "module", module, "err", err)
|
||||
return ErrInternal
|
||||
}
|
||||
|
||||
if rows == 0 {
|
||||
slog.InfoContext(ctx, "row not found", "module", module)
|
||||
return ErrNotFound
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func HandleError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
switch {
|
||||
case errors.Is(err, ErrUnauthorized):
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", "You are not autorized to perform this operation.", http.StatusUnauthorized)
|
||||
return
|
||||
case errors.Is(err, ErrBadRequest):
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", extractErrorMessage(err), http.StatusBadRequest)
|
||||
return
|
||||
case errors.Is(err, ErrNotFound):
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", extractErrorMessage(err), http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
func extractErrorMessage(err error) string {
|
||||
errMsg := err.Error()
|
||||
if errMsg == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
return strings.SplitN(errMsg, ":", 2)[0]
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package template
|
||||
package core
|
||||
|
||||
import "spend-sparrow/internal/template/svg"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package service
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -1,10 +1,9 @@
|
||||
package db
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"spend-sparrow/internal/types"
|
||||
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
"github.com/golang-migrate/migrate/v4/database/sqlite3"
|
||||
@@ -25,7 +24,7 @@ func RunMigrations(ctx context.Context, db *sqlx.DB, pathPrefix string) error {
|
||||
driver, err := sqlite3.WithInstance(db.DB, &sqlite3.Config{})
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not create Migration instance", "err", err)
|
||||
return types.ErrInternal
|
||||
return ErrInternal
|
||||
}
|
||||
|
||||
m, err := migrate.NewWithDatabaseInstance(
|
||||
@@ -34,14 +33,14 @@ func RunMigrations(ctx context.Context, db *sqlx.DB, pathPrefix string) error {
|
||||
driver)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Could not create migrations instance", "err", err)
|
||||
return types.ErrInternal
|
||||
return ErrInternal
|
||||
}
|
||||
|
||||
m.Log = migrationLogger{}
|
||||
|
||||
if err = m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
||||
slog.ErrorContext(ctx, "Could not run migrations", "err", err)
|
||||
return types.ErrInternal
|
||||
return ErrInternal
|
||||
}
|
||||
|
||||
return nil
|
||||
16
internal/core/observabillity.go
Normal file
16
internal/core/observabillity.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
func UpdateSpan(r *http.Request) {
|
||||
currentSpan := trace.SpanFromContext(r.Context())
|
||||
if currentSpan != nil {
|
||||
currentSpan.SetAttributes(attribute.String("http.pattern", r.Pattern))
|
||||
currentSpan.SetAttributes(attribute.String("http.pattern.id", r.PathValue("id")))
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
package service
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"log/slog"
|
||||
"spend-sparrow/internal/types"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
@@ -28,7 +27,7 @@ func (r *RandomImpl) Bytes(ctx context.Context, tsize int) ([]byte, error) {
|
||||
_, err := rand.Read(b)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Error generating random bytes", "err", err)
|
||||
return []byte{}, types.ErrInternal
|
||||
return []byte{}, ErrInternal
|
||||
}
|
||||
|
||||
return b, nil
|
||||
@@ -38,7 +37,7 @@ func (r *RandomImpl) String(ctx context.Context, size int) (string, error) {
|
||||
bytes, err := r.Bytes(ctx, size)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Error generating random string", "err", err)
|
||||
return "", types.ErrInternal
|
||||
return "", ErrInternal
|
||||
}
|
||||
|
||||
return base64.StdEncoding.EncodeToString(bytes), nil
|
||||
@@ -48,7 +47,7 @@ func (r *RandomImpl) UUID(ctx context.Context) (uuid.UUID, error) {
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "Error generating random UUID", "err", err)
|
||||
return uuid.Nil, types.ErrInternal
|
||||
return uuid.Nil, ErrInternal
|
||||
}
|
||||
|
||||
return id, nil
|
||||
@@ -1,11 +1,9 @@
|
||||
package handler
|
||||
package core
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"spend-sparrow/internal/template"
|
||||
"spend-sparrow/internal/template/auth"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/auth_types"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
)
|
||||
@@ -31,21 +29,21 @@ func (render *Render) Render(r *http.Request, w http.ResponseWriter, comp templ.
|
||||
render.RenderWithStatus(r, w, comp, http.StatusOK)
|
||||
}
|
||||
|
||||
func (render *Render) RenderLayout(r *http.Request, w http.ResponseWriter, slot templ.Component, user *types.User) {
|
||||
func (render *Render) RenderLayout(r *http.Request, w http.ResponseWriter, slot templ.Component, user *auth_types.User) {
|
||||
render.RenderLayoutWithStatus(r, w, slot, user, http.StatusOK)
|
||||
}
|
||||
|
||||
func (render *Render) RenderLayoutWithStatus(r *http.Request, w http.ResponseWriter, slot templ.Component, user *types.User, status int) {
|
||||
func (render *Render) RenderLayoutWithStatus(r *http.Request, w http.ResponseWriter, slot templ.Component, user *auth_types.User, status int) {
|
||||
userComp := render.getUserComp(user)
|
||||
layout := template.Layout(slot, userComp, user != nil, r.URL.Path)
|
||||
layout := Layout(slot, userComp, user != nil, r.URL.Path)
|
||||
|
||||
render.RenderWithStatus(r, w, layout, status)
|
||||
}
|
||||
|
||||
func (render *Render) getUserComp(user *types.User) templ.Component {
|
||||
func (render *Render) getUserComp(user *auth_types.User) templ.Component {
|
||||
if user != nil {
|
||||
return auth.UserComp(user.Email)
|
||||
return UserComp(user.Email)
|
||||
} else {
|
||||
return auth.UserComp("")
|
||||
return UserComp("")
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package auth
|
||||
package core
|
||||
|
||||
templ UserComp(user string) {
|
||||
<div id="user-info" class="flex items-center gap-2 text-nowrap">
|
||||
@@ -1,19 +1,15 @@
|
||||
package service
|
||||
package core
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
const (
|
||||
DECIMALS_MULTIPLIER = 100
|
||||
)
|
||||
|
||||
var (
|
||||
safeInputRegex = regexp.MustCompile(`^[a-zA-Z0-9ÄÖÜäöüß,&'". \-\?]+$`)
|
||||
)
|
||||
|
||||
func validateString(value string, fieldName string) error {
|
||||
func ValidateString(value string, fieldName string) error {
|
||||
switch {
|
||||
case value == "":
|
||||
return fmt.Errorf("field \"%s\" needs to be set: %w", fieldName, ErrBadRequest)
|
||||
@@ -1,12 +1,12 @@
|
||||
package handler
|
||||
package dashboard
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"spend-sparrow/internal/handler/middleware"
|
||||
"spend-sparrow/internal/service"
|
||||
"spend-sparrow/internal/template/dashboard"
|
||||
"spend-sparrow/internal/core"
|
||||
"spend-sparrow/internal/dashboard/template"
|
||||
"spend-sparrow/internal/treasure_chest"
|
||||
"spend-sparrow/internal/utils"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -14,36 +14,36 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Dashboard interface {
|
||||
type Handler interface {
|
||||
Handle(router *http.ServeMux)
|
||||
}
|
||||
|
||||
type DashboardImpl struct {
|
||||
r *Render
|
||||
d *service.Dashboard
|
||||
treasureChest service.TreasureChest
|
||||
type HandlerImpl struct {
|
||||
r *core.Render
|
||||
s *Service
|
||||
treasureChest treasure_chest.Service
|
||||
}
|
||||
|
||||
func NewDashboard(r *Render, d *service.Dashboard, treasureChest service.TreasureChest) Dashboard {
|
||||
return DashboardImpl{
|
||||
func NewHandler(r *core.Render, s *Service, treasureChest treasure_chest.Service) Handler {
|
||||
return HandlerImpl{
|
||||
r: r,
|
||||
d: d,
|
||||
s: s,
|
||||
treasureChest: treasureChest,
|
||||
}
|
||||
}
|
||||
|
||||
func (handler DashboardImpl) Handle(router *http.ServeMux) {
|
||||
func (handler HandlerImpl) Handle(router *http.ServeMux) {
|
||||
router.Handle("GET /dashboard", handler.handleDashboard())
|
||||
router.Handle("GET /dashboard/main-chart", handler.handleDashboardMainChart())
|
||||
router.Handle("GET /dashboard/treasure-chests", handler.handleDashboardTreasureChests())
|
||||
router.Handle("GET /dashboard/treasure-chest", handler.handleDashboardTreasureChest())
|
||||
router.Handle("GET /dashboard/main-chart", handler.handleMainChart())
|
||||
router.Handle("GET /dashboard/treasure-chests", handler.handleTreasureChests())
|
||||
router.Handle("GET /dashboard/treasure-chest", handler.handleTreasureChest())
|
||||
}
|
||||
|
||||
func (handler DashboardImpl) handleDashboard() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleDashboard() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -51,24 +51,24 @@ func (handler DashboardImpl) handleDashboard() http.HandlerFunc {
|
||||
|
||||
treasureChests, err := handler.treasureChest.GetAll(r.Context(), user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
comp := dashboard.Dashboard(treasureChests)
|
||||
comp := template.Dashboard(treasureChests)
|
||||
handler.r.RenderLayoutWithStatus(r, w, comp, user, http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler DashboardImpl) handleDashboardMainChart() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleMainChart() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
|
||||
series, err := handler.d.MainChart(r.Context(), user)
|
||||
series, err := handler.s.MainChart(r.Context(), user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -79,8 +79,8 @@ func (handler DashboardImpl) handleDashboardMainChart() http.HandlerFunc {
|
||||
savingsBuilder := strings.Builder{}
|
||||
|
||||
for _, entry := range series {
|
||||
accountBuilder.WriteString(fmt.Sprintf(`["%s",%.2f],`, entry.Day.Format(time.RFC3339), float64(entry.Value)/100))
|
||||
savingsBuilder.WriteString(fmt.Sprintf(`["%s",%.2f],`, entry.Day.Format(time.RFC3339), float64(entry.Savings)/100))
|
||||
fmt.Fprintf(&accountBuilder, `["%s",%.2f],`, entry.Day.Format(time.RFC3339), float64(entry.Value)/100)
|
||||
fmt.Fprintf(&savingsBuilder, `["%s",%.2f],`, entry.Day.Format(time.RFC3339), float64(entry.Savings)/100)
|
||||
}
|
||||
|
||||
account := accountBuilder.String()
|
||||
@@ -126,15 +126,15 @@ func (handler DashboardImpl) handleDashboardMainChart() http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func (handler DashboardImpl) handleDashboardTreasureChests() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleTreasureChests() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
|
||||
treeList, err := handler.d.TreasureChests(r.Context(), user)
|
||||
treeList, err := handler.s.TreasureChests(r.Context(), user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -148,15 +148,15 @@ func (handler DashboardImpl) handleDashboardTreasureChests() http.HandlerFunc {
|
||||
|
||||
for _, child := range item.Children {
|
||||
if child.Value < 0 {
|
||||
childrenBuilder.WriteString(fmt.Sprintf(`{"name":"%s\n%.2f €","value":%d},`, child.Name, float64(child.Value)/100, -child.Value))
|
||||
fmt.Fprintf(&childrenBuilder, `{"name":"%s\n%.2f €","value":%d},`, child.Name, float64(child.Value)/100, -child.Value)
|
||||
} else {
|
||||
childrenBuilder.WriteString(fmt.Sprintf(`{"name":"%s\n%.2f €","value":%d},`, child.Name, float64(child.Value)/100, child.Value))
|
||||
fmt.Fprintf(&childrenBuilder, `{"name":"%s\n%.2f €","value":%d},`, child.Name, float64(child.Value)/100, child.Value)
|
||||
}
|
||||
}
|
||||
|
||||
children := childrenBuilder.String()
|
||||
children = children[:len(children)-1]
|
||||
dataBuilder.WriteString(fmt.Sprintf(`{"name":"%s","children":[%s]},`, item.Name, children))
|
||||
fmt.Fprintf(&dataBuilder, `{"name":"%s","children":[%s]},`, item.Name, children)
|
||||
}
|
||||
data := dataBuilder.String()
|
||||
data = data[:len(data)-1]
|
||||
@@ -181,11 +181,11 @@ func (handler DashboardImpl) handleDashboardTreasureChests() http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func (handler DashboardImpl) handleDashboardTreasureChest() http.HandlerFunc {
|
||||
func (handler HandlerImpl) handleTreasureChest() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
|
||||
var treasureChestId *uuid.UUID
|
||||
|
||||
@@ -193,16 +193,16 @@ func (handler DashboardImpl) handleDashboardTreasureChest() http.HandlerFunc {
|
||||
if treasureChestStr != "" {
|
||||
id, err := uuid.Parse(treasureChestStr)
|
||||
if err != nil {
|
||||
handleError(w, r, fmt.Errorf("could not parse treasure chest: %w", service.ErrBadRequest))
|
||||
core.HandleError(w, r, fmt.Errorf("could not parse treasure chest: %w", core.ErrBadRequest))
|
||||
return
|
||||
}
|
||||
|
||||
treasureChestId = &id
|
||||
}
|
||||
|
||||
series, err := handler.d.TreasureChest(r.Context(), user, treasureChestId)
|
||||
series, err := handler.s.TreasureChest(r.Context(), user, treasureChestId)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -212,7 +212,7 @@ func (handler DashboardImpl) handleDashboardTreasureChest() http.HandlerFunc {
|
||||
valueBuilder := strings.Builder{}
|
||||
|
||||
for _, entry := range series {
|
||||
valueBuilder.WriteString(fmt.Sprintf(`["%s",%.2f],`, entry.Day.Format(time.RFC3339), float64(entry.Value)/100))
|
||||
fmt.Fprintf(&valueBuilder, `["%s",%.2f],`, entry.Day.Format(time.RFC3339), float64(entry.Value)/100)
|
||||
}
|
||||
|
||||
value := valueBuilder.String()
|
||||
@@ -1,8 +1,11 @@
|
||||
package service
|
||||
package dashboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"spend-sparrow/internal/db"
|
||||
"spend-sparrow/internal/auth_types"
|
||||
"spend-sparrow/internal/core"
|
||||
"spend-sparrow/internal/treasure_chest"
|
||||
"spend-sparrow/internal/treasure_chest_types"
|
||||
"spend-sparrow/internal/types"
|
||||
"time"
|
||||
|
||||
@@ -10,22 +13,22 @@ import (
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
type Dashboard struct {
|
||||
type Service struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewDashboard(db *sqlx.DB) *Dashboard {
|
||||
return &Dashboard{
|
||||
func NewService(db *sqlx.DB) *Service {
|
||||
return &Service{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Dashboard) MainChart(
|
||||
func (s Service) MainChart(
|
||||
ctx context.Context,
|
||||
user *types.User,
|
||||
) ([]types.DashboardMainChartEntry, error) {
|
||||
user *auth_types.User,
|
||||
) ([]DashboardMainChartEntry, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
|
||||
transactions := make([]types.Transaction, 0)
|
||||
@@ -34,14 +37,14 @@ func (s Dashboard) MainChart(
|
||||
FROM "transaction"
|
||||
WHERE user_id = ?
|
||||
ORDER BY timestamp`, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "dashboard Chart", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "dashboard Chart", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
timeEntries := make([]types.DashboardMainChartEntry, 0)
|
||||
timeEntries := make([]DashboardMainChartEntry, 0)
|
||||
|
||||
var lastEntry *types.DashboardMainChartEntry
|
||||
var lastEntry *DashboardMainChartEntry
|
||||
|
||||
for _, t := range transactions {
|
||||
if t.Error != nil {
|
||||
@@ -50,14 +53,14 @@ func (s Dashboard) MainChart(
|
||||
|
||||
newDay := t.Timestamp.Truncate(24 * time.Hour)
|
||||
if lastEntry == nil {
|
||||
lastEntry = &types.DashboardMainChartEntry{
|
||||
lastEntry = &DashboardMainChartEntry{
|
||||
Day: newDay,
|
||||
Value: 0,
|
||||
Savings: 0,
|
||||
}
|
||||
} else if lastEntry.Day != newDay {
|
||||
timeEntries = append(timeEntries, *lastEntry)
|
||||
lastEntry = &types.DashboardMainChartEntry{
|
||||
lastEntry = &DashboardMainChartEntry{
|
||||
Day: newDay,
|
||||
Value: lastEntry.Value,
|
||||
Savings: lastEntry.Savings,
|
||||
@@ -80,37 +83,37 @@ func (s Dashboard) MainChart(
|
||||
return timeEntries, nil
|
||||
}
|
||||
|
||||
func (s Dashboard) TreasureChests(
|
||||
func (s Service) TreasureChests(
|
||||
ctx context.Context,
|
||||
user *types.User,
|
||||
) ([]*types.DashboardTreasureChest, error) {
|
||||
user *auth_types.User,
|
||||
) ([]*DashboardTreasureChest, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
|
||||
treasureChests := make([]*types.TreasureChest, 0)
|
||||
treasureChests := make([]*treasure_chest_types.TreasureChest, 0)
|
||||
err := s.db.SelectContext(ctx, &treasureChests, `SELECT * FROM treasure_chest WHERE user_id = ?`, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "dashboard TreasureChests", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "dashboard TreasureChests", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
treasureChests = sortTreasureChests(treasureChests)
|
||||
treasureChests = treasure_chest.SortTreasureChests(treasureChests)
|
||||
|
||||
result := make([]*types.DashboardTreasureChest, 0)
|
||||
result := make([]*DashboardTreasureChest, 0)
|
||||
|
||||
for _, t := range treasureChests {
|
||||
if t.ParentId == nil {
|
||||
result = append(result, &types.DashboardTreasureChest{
|
||||
result = append(result, &DashboardTreasureChest{
|
||||
Name: t.Name,
|
||||
Value: t.CurrentBalance,
|
||||
Children: make([]types.DashboardTreasureChest, 0),
|
||||
Children: make([]DashboardTreasureChest, 0),
|
||||
})
|
||||
} else {
|
||||
result[len(result)-1].Children = append(result[len(result)-1].Children, types.DashboardTreasureChest{
|
||||
result[len(result)-1].Children = append(result[len(result)-1].Children, DashboardTreasureChest{
|
||||
Name: t.Name,
|
||||
Value: t.CurrentBalance,
|
||||
Children: make([]types.DashboardTreasureChest, 0),
|
||||
Children: make([]DashboardTreasureChest, 0),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -118,13 +121,13 @@ func (s Dashboard) TreasureChests(
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s Dashboard) TreasureChest(
|
||||
func (s Service) TreasureChest(
|
||||
ctx context.Context,
|
||||
user *types.User,
|
||||
user *auth_types.User,
|
||||
treausureChestId *uuid.UUID,
|
||||
) ([]types.DashboardMainChartEntry, error) {
|
||||
) ([]DashboardMainChartEntry, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
|
||||
transactions := make([]types.Transaction, 0)
|
||||
@@ -134,14 +137,14 @@ func (s Dashboard) TreasureChest(
|
||||
WHERE user_id = ?
|
||||
AND treasure_chest_id = ?
|
||||
ORDER BY timestamp`, user.Id, treausureChestId)
|
||||
err = db.TransformAndLogDbError(ctx, "dashboard Chart", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "dashboard Chart", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
timeEntries := make([]types.DashboardMainChartEntry, 0)
|
||||
timeEntries := make([]DashboardMainChartEntry, 0)
|
||||
|
||||
var lastEntry *types.DashboardMainChartEntry
|
||||
var lastEntry *DashboardMainChartEntry
|
||||
|
||||
for _, t := range transactions {
|
||||
if t.Error != nil {
|
||||
@@ -150,13 +153,13 @@ func (s Dashboard) TreasureChest(
|
||||
|
||||
newDay := t.Timestamp.Truncate(24 * time.Hour)
|
||||
if lastEntry == nil {
|
||||
lastEntry = &types.DashboardMainChartEntry{
|
||||
lastEntry = &DashboardMainChartEntry{
|
||||
Day: newDay,
|
||||
Value: 0,
|
||||
}
|
||||
} else if lastEntry.Day != newDay {
|
||||
timeEntries = append(timeEntries, *lastEntry)
|
||||
lastEntry = &types.DashboardMainChartEntry{
|
||||
lastEntry = &DashboardMainChartEntry{
|
||||
Day: newDay,
|
||||
Value: lastEntry.Value,
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
package dashboard
|
||||
package template
|
||||
|
||||
import "spend-sparrow/internal/types"
|
||||
import "spend-sparrow/internal/treasure_chest_types"
|
||||
|
||||
templ Dashboard(treasureChests []*types.TreasureChest) {
|
||||
templ Dashboard(treasureChests []*treasure_chest_types.TreasureChest) {
|
||||
<div class="mt-10 h-full">
|
||||
<div id="main-chart" class="h-96 mt-10"></div>
|
||||
<div id="treasure-chests" class="h-96 mt-10"></div>
|
||||
1
internal/dashboard/template/default.go
Normal file
1
internal/dashboard/template/default.go
Normal file
@@ -0,0 +1 @@
|
||||
package template
|
||||
@@ -1,4 +1,4 @@
|
||||
package types
|
||||
package dashboard
|
||||
|
||||
import "time"
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"spend-sparrow/internal/types"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("the value does not exist")
|
||||
ErrAlreadyExists = errors.New("row already exists")
|
||||
)
|
||||
|
||||
func TransformAndLogDbError(ctx context.Context, module string, r sql.Result, err error) error {
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
slog.ErrorContext(ctx, "database sql", "module", module, "err", err)
|
||||
return types.ErrInternal
|
||||
}
|
||||
|
||||
if r != nil {
|
||||
rows, err := r.RowsAffected()
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "database rows affected", "module", module, "err", err)
|
||||
return types.ErrInternal
|
||||
}
|
||||
|
||||
if rows == 0 {
|
||||
slog.InfoContext(ctx, "row not found", "module", module)
|
||||
return ErrNotFound
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,19 +1,23 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"spend-sparrow/internal/db"
|
||||
"net/http"
|
||||
"os/signal"
|
||||
"spend-sparrow/internal/account"
|
||||
"spend-sparrow/internal/authentication"
|
||||
"spend-sparrow/internal/core"
|
||||
"spend-sparrow/internal/dashboard"
|
||||
"spend-sparrow/internal/handler"
|
||||
"spend-sparrow/internal/handler/middleware"
|
||||
"spend-sparrow/internal/log"
|
||||
"spend-sparrow/internal/service"
|
||||
"spend-sparrow/internal/transaction_recurring"
|
||||
"spend-sparrow/internal/treasure_chest"
|
||||
"spend-sparrow/internal/types"
|
||||
|
||||
"context"
|
||||
"net/http"
|
||||
"os/signal"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
@@ -56,7 +60,7 @@ func Run(ctx context.Context, database *sqlx.DB, migrationsPrefix string, env fu
|
||||
}
|
||||
|
||||
// init db
|
||||
err = db.RunMigrations(ctx, database, migrationsPrefix)
|
||||
err = core.RunMigrations(ctx, database, migrationsPrefix)
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not run migrations: %w", err)
|
||||
}
|
||||
@@ -106,27 +110,27 @@ func shutdownServer(ctx context.Context, s *http.Server, wg *sync.WaitGroup) {
|
||||
func createHandlerWithServices(ctx context.Context, d *sqlx.DB, serverSettings *types.Settings) http.Handler {
|
||||
var router = http.NewServeMux()
|
||||
|
||||
authDb := db.NewAuthSqlite(d)
|
||||
authDb := authentication.NewDbSqlite(d)
|
||||
|
||||
randomService := service.NewRandom()
|
||||
clockService := service.NewClock()
|
||||
mailService := service.NewMail(serverSettings)
|
||||
randomService := core.NewRandom()
|
||||
clockService := core.NewClock()
|
||||
mailService := core.NewMail(serverSettings)
|
||||
|
||||
authService := service.NewAuth(authDb, randomService, clockService, mailService, serverSettings)
|
||||
accountService := service.NewAccount(d, randomService, clockService)
|
||||
treasureChestService := service.NewTreasureChest(d, randomService, clockService)
|
||||
authService := authentication.NewService(authDb, randomService, clockService, mailService, serverSettings)
|
||||
accountService := account.NewServiceImpl(d, randomService, clockService)
|
||||
treasureChestService := treasure_chest.NewService(d, randomService, clockService)
|
||||
transactionService := service.NewTransaction(d, randomService, clockService)
|
||||
transactionRecurringService := service.NewTransactionRecurring(d, randomService, clockService, transactionService)
|
||||
dashboardService := service.NewDashboard(d)
|
||||
transactionRecurringService := transaction_recurring.NewService(d, randomService, clockService, transactionService)
|
||||
dashboardService := dashboard.NewService(d)
|
||||
|
||||
render := handler.NewRender()
|
||||
render := core.NewRender()
|
||||
indexHandler := handler.NewIndex(render, clockService)
|
||||
dashboardHandler := handler.NewDashboard(render, dashboardService, treasureChestService)
|
||||
authHandler := handler.NewAuth(authService, render)
|
||||
accountHandler := handler.NewAccount(accountService, render)
|
||||
treasureChestHandler := handler.NewTreasureChest(treasureChestService, transactionRecurringService, render)
|
||||
dashboardHandler := dashboard.NewHandler(render, dashboardService, treasureChestService)
|
||||
authHandler := authentication.NewHandler(authService, render)
|
||||
accountHandler := account.NewHandler(accountService, render)
|
||||
treasureChestHandler := treasure_chest.NewHandler(treasureChestService, transactionRecurringService, render)
|
||||
transactionHandler := handler.NewTransaction(transactionService, accountService, treasureChestService, render)
|
||||
transactionRecurringHandler := handler.NewTransactionRecurring(transactionRecurringService, render)
|
||||
transactionRecurringHandler := transaction_recurring.NewHandler(transactionRecurringService, render)
|
||||
|
||||
go dailyTaskTimer(ctx, transactionRecurringService, authService)
|
||||
|
||||
@@ -156,7 +160,7 @@ func createHandlerWithServices(ctx context.Context, d *sqlx.DB, serverSettings *
|
||||
return wrapper
|
||||
}
|
||||
|
||||
func dailyTaskTimer(ctx context.Context, transactionRecurring service.TransactionRecurring, auth service.Auth) {
|
||||
func dailyTaskTimer(ctx context.Context, transactionRecurring transaction_recurring.Service, auth authentication.Service) {
|
||||
runDailyTasks(ctx, transactionRecurring, auth)
|
||||
ticker := time.NewTicker(24 * time.Hour)
|
||||
defer ticker.Stop()
|
||||
@@ -171,7 +175,7 @@ func dailyTaskTimer(ctx context.Context, transactionRecurring service.Transactio
|
||||
}
|
||||
}
|
||||
|
||||
func runDailyTasks(ctx context.Context, transactionRecurring service.TransactionRecurring, auth service.Auth) {
|
||||
func runDailyTasks(ctx context.Context, transactionRecurring transaction_recurring.Service, auth authentication.Service) {
|
||||
slog.InfoContext(ctx, "Running daily tasks")
|
||||
_ = transactionRecurring.GenerateTransactions(ctx)
|
||||
_ = auth.CleanupSessionsAndTokens(ctx)
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"spend-sparrow/internal/db"
|
||||
"spend-sparrow/internal/service"
|
||||
"spend-sparrow/internal/utils"
|
||||
"strings"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
func handleError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrUnauthorized):
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", "You are not autorized to perform this operation.", http.StatusUnauthorized)
|
||||
return
|
||||
case errors.Is(err, service.ErrBadRequest):
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", extractErrorMessage(err), http.StatusBadRequest)
|
||||
return
|
||||
case errors.Is(err, db.ErrNotFound):
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", extractErrorMessage(err), http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
func extractErrorMessage(err error) string {
|
||||
errMsg := err.Error()
|
||||
if errMsg == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
return strings.SplitN(errMsg, ":", 2)[0]
|
||||
}
|
||||
|
||||
func updateSpan(r *http.Request) {
|
||||
currentSpan := trace.SpanFromContext(r.Context())
|
||||
if currentSpan != nil {
|
||||
currentSpan.SetAttributes(attribute.String("http.pattern", r.Pattern))
|
||||
currentSpan.SetAttributes(attribute.String("http.pattern.id", r.PathValue("id")))
|
||||
}
|
||||
}
|
||||
@@ -3,18 +3,12 @@ package middleware
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"spend-sparrow/internal/authentication"
|
||||
"spend-sparrow/internal/core"
|
||||
"strings"
|
||||
|
||||
"spend-sparrow/internal/service"
|
||||
"spend-sparrow/internal/types"
|
||||
)
|
||||
|
||||
type ContextKey string
|
||||
|
||||
var SessionKey ContextKey = "session"
|
||||
var UserKey ContextKey = "user"
|
||||
|
||||
func Authenticate(service service.Auth) func(http.Handler) http.Handler {
|
||||
func Authenticate(service authentication.Service) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
@@ -37,46 +31,18 @@ func Authenticate(service service.Auth) func(http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
|
||||
cookie := CreateSessionCookie(session.Id)
|
||||
cookie := core.CreateSessionCookie(session.Id)
|
||||
http.SetCookie(w, &cookie)
|
||||
}
|
||||
|
||||
ctx = context.WithValue(ctx, UserKey, user)
|
||||
ctx = context.WithValue(ctx, SessionKey, session)
|
||||
ctx = context.WithValue(ctx, core.UserKey, user)
|
||||
ctx = context.WithValue(ctx, core.SessionKey, session)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func GetUser(r *http.Request) *types.User {
|
||||
obj := r.Context().Value(UserKey)
|
||||
if obj == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
user, ok := obj.(*types.User)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
func GetSession(r *http.Request) *types.Session {
|
||||
obj := r.Context().Value(SessionKey)
|
||||
if obj == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
session, ok := obj.(*types.Session)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
return session
|
||||
}
|
||||
|
||||
func getSessionID(r *http.Request) string {
|
||||
cookie, err := r.Cookie("id")
|
||||
if err != nil {
|
||||
|
||||
@@ -3,7 +3,8 @@ package middleware
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"spend-sparrow/internal/service"
|
||||
"spend-sparrow/internal/authentication"
|
||||
"spend-sparrow/internal/core"
|
||||
"spend-sparrow/internal/utils"
|
||||
"strings"
|
||||
)
|
||||
@@ -30,7 +31,7 @@ func (rr *csrfResponseWriter) Write(data []byte) (int, error) {
|
||||
return rr.ResponseWriter.Write([]byte(dataStr))
|
||||
}
|
||||
|
||||
func CrossSiteRequestForgery(auth service.Auth) func(http.Handler) http.Handler {
|
||||
func CrossSiteRequestForgery(auth authentication.Service) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
@@ -40,7 +41,7 @@ func CrossSiteRequestForgery(auth service.Auth) func(http.Handler) http.Handler
|
||||
return
|
||||
}
|
||||
|
||||
session := GetSession(r)
|
||||
session := core.GetSession(r)
|
||||
|
||||
if r.Method == http.MethodPost ||
|
||||
r.Method == http.MethodPut ||
|
||||
|
||||
@@ -1,15 +1 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
func CreateSessionCookie(sessionId string) http.Cookie {
|
||||
return http.Cookie{
|
||||
Name: "id",
|
||||
Value: sessionId,
|
||||
MaxAge: 60 * 60 * 8, // 8 hours
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Path: "/",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,7 @@ package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"spend-sparrow/internal/handler/middleware"
|
||||
"spend-sparrow/internal/service"
|
||||
"spend-sparrow/internal/core"
|
||||
"spend-sparrow/internal/template"
|
||||
"spend-sparrow/internal/utils"
|
||||
|
||||
@@ -15,11 +14,11 @@ type Index interface {
|
||||
}
|
||||
|
||||
type IndexImpl struct {
|
||||
r *Render
|
||||
c service.Clock
|
||||
r *core.Render
|
||||
c core.Clock
|
||||
}
|
||||
|
||||
func NewIndex(r *Render, c service.Clock) Index {
|
||||
func NewIndex(r *core.Render, c core.Clock) Index {
|
||||
return IndexImpl{
|
||||
r: r,
|
||||
c: c,
|
||||
@@ -33,9 +32,9 @@ func (handler IndexImpl) Handle(router *http.ServeMux) {
|
||||
|
||||
func (handler IndexImpl) handleRootAnd404() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
|
||||
htmx := utils.IsHtmx(r)
|
||||
|
||||
@@ -65,7 +64,7 @@ func (handler IndexImpl) handleRootAnd404() http.HandlerFunc {
|
||||
|
||||
func (handler IndexImpl) handleEmpty() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
// Return nothing
|
||||
}
|
||||
|
||||
@@ -4,9 +4,12 @@ import (
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"spend-sparrow/internal/handler/middleware"
|
||||
"spend-sparrow/internal/account"
|
||||
"spend-sparrow/internal/core"
|
||||
"spend-sparrow/internal/service"
|
||||
t "spend-sparrow/internal/template/transaction"
|
||||
"spend-sparrow/internal/treasure_chest"
|
||||
"spend-sparrow/internal/treasure_chest_types"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/utils"
|
||||
"strconv"
|
||||
@@ -16,18 +19,22 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
DECIMALS_MULTIPLIER = 100
|
||||
)
|
||||
|
||||
type Transaction interface {
|
||||
Handle(router *http.ServeMux)
|
||||
}
|
||||
|
||||
type TransactionImpl struct {
|
||||
s service.Transaction
|
||||
account service.Account
|
||||
treasureChest service.TreasureChest
|
||||
r *Render
|
||||
account account.Service
|
||||
treasureChest treasure_chest.Service
|
||||
r *core.Render
|
||||
}
|
||||
|
||||
func NewTransaction(s service.Transaction, account service.Account, treasureChest service.TreasureChest, r *Render) Transaction {
|
||||
func NewTransaction(s service.Transaction, account account.Service, treasureChest treasure_chest.Service, r *core.Render) Transaction {
|
||||
return TransactionImpl{
|
||||
s: s,
|
||||
account: account,
|
||||
@@ -46,9 +53,9 @@ func (h TransactionImpl) Handle(r *http.ServeMux) {
|
||||
|
||||
func (h TransactionImpl) handleTransactionPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -63,19 +70,19 @@ func (h TransactionImpl) handleTransactionPage() http.HandlerFunc {
|
||||
|
||||
transactions, err := h.s.GetAll(r.Context(), user, filter)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
accounts, err := h.account.GetAll(r.Context(), user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
treasureChests, err := h.treasureChest.GetAll(r.Context(), user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -93,9 +100,9 @@ func (h TransactionImpl) handleTransactionPage() http.HandlerFunc {
|
||||
|
||||
func (h TransactionImpl) handleTransactionItemComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -103,13 +110,13 @@ func (h TransactionImpl) handleTransactionItemComp() http.HandlerFunc {
|
||||
|
||||
accounts, err := h.account.GetAll(r.Context(), user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
treasureChests, err := h.treasureChest.GetAll(r.Context(), user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -122,7 +129,7 @@ func (h TransactionImpl) handleTransactionItemComp() http.HandlerFunc {
|
||||
|
||||
transaction, err := h.s.Get(r.Context(), user, id)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -139,9 +146,9 @@ func (h TransactionImpl) handleTransactionItemComp() http.HandlerFunc {
|
||||
|
||||
func (h TransactionImpl) handleUpdateTransaction() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -156,7 +163,7 @@ func (h TransactionImpl) handleUpdateTransaction() http.HandlerFunc {
|
||||
if idStr != "new" {
|
||||
id, err = uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
handleError(w, r, fmt.Errorf("could not parse Id: %w", service.ErrBadRequest))
|
||||
core.HandleError(w, r, fmt.Errorf("could not parse Id: %w", core.ErrBadRequest))
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -166,7 +173,7 @@ func (h TransactionImpl) handleUpdateTransaction() http.HandlerFunc {
|
||||
if accountIdStr != "" {
|
||||
i, err := uuid.Parse(accountIdStr)
|
||||
if err != nil {
|
||||
handleError(w, r, fmt.Errorf("could not parse account id: %w", service.ErrBadRequest))
|
||||
core.HandleError(w, r, fmt.Errorf("could not parse account id: %w", core.ErrBadRequest))
|
||||
return
|
||||
}
|
||||
accountId = &i
|
||||
@@ -177,7 +184,7 @@ func (h TransactionImpl) handleUpdateTransaction() http.HandlerFunc {
|
||||
if treasureChestIdStr != "" {
|
||||
i, err := uuid.Parse(treasureChestIdStr)
|
||||
if err != nil {
|
||||
handleError(w, r, fmt.Errorf("could not parse treasure chest id: %w", service.ErrBadRequest))
|
||||
core.HandleError(w, r, fmt.Errorf("could not parse treasure chest id: %w", core.ErrBadRequest))
|
||||
return
|
||||
}
|
||||
treasureChestId = &i
|
||||
@@ -185,14 +192,14 @@ func (h TransactionImpl) handleUpdateTransaction() http.HandlerFunc {
|
||||
|
||||
valueF, err := strconv.ParseFloat(r.FormValue("value"), 64)
|
||||
if err != nil {
|
||||
handleError(w, r, fmt.Errorf("could not parse value: %w", service.ErrBadRequest))
|
||||
core.HandleError(w, r, fmt.Errorf("could not parse value: %w", core.ErrBadRequest))
|
||||
return
|
||||
}
|
||||
value := int64(math.Round(valueF * service.DECIMALS_MULTIPLIER))
|
||||
value := int64(math.Round(valueF * DECIMALS_MULTIPLIER))
|
||||
|
||||
timestamp, err := time.Parse("2006-01-02", r.FormValue("timestamp"))
|
||||
if err != nil {
|
||||
handleError(w, r, fmt.Errorf("could not parse timestamp: %w", service.ErrBadRequest))
|
||||
core.HandleError(w, r, fmt.Errorf("could not parse timestamp: %w", core.ErrBadRequest))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -210,26 +217,26 @@ func (h TransactionImpl) handleUpdateTransaction() http.HandlerFunc {
|
||||
if idStr == "new" {
|
||||
transaction, err = h.s.Add(r.Context(), nil, user, input)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
transaction, err = h.s.Update(r.Context(), user, input)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
accounts, err := h.account.GetAll(r.Context(), user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
treasureChests, err := h.treasureChest.GetAll(r.Context(), user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -241,9 +248,9 @@ func (h TransactionImpl) handleUpdateTransaction() http.HandlerFunc {
|
||||
|
||||
func (h TransactionImpl) handleRecalculate() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -251,7 +258,7 @@ func (h TransactionImpl) handleRecalculate() http.HandlerFunc {
|
||||
|
||||
err := h.s.RecalculateBalances(r.Context(), user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -261,9 +268,9 @@ func (h TransactionImpl) handleRecalculate() http.HandlerFunc {
|
||||
|
||||
func (h TransactionImpl) handleDeleteTransaction() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -273,13 +280,13 @@ func (h TransactionImpl) handleDeleteTransaction() http.HandlerFunc {
|
||||
|
||||
err := h.s.Delete(r.Context(), user, id)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h TransactionImpl) getTransactionData(accounts []*types.Account, treasureChests []*types.TreasureChest) (map[uuid.UUID]string, map[uuid.UUID]string) {
|
||||
func (h TransactionImpl) getTransactionData(accounts []*account.Account, treasureChests []*treasure_chest_types.TreasureChest) (map[uuid.UUID]string, map[uuid.UUID]string) {
|
||||
accountMap := make(map[uuid.UUID]string, 0)
|
||||
for _, account := range accounts {
|
||||
accountMap[account.Id] = account.Name
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
package service
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrBadRequest = errors.New("bad request")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
)
|
||||
@@ -5,7 +5,9 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"spend-sparrow/internal/db"
|
||||
"spend-sparrow/internal/auth_types"
|
||||
"spend-sparrow/internal/core"
|
||||
"spend-sparrow/internal/treasure_chest_types"
|
||||
"spend-sparrow/internal/types"
|
||||
"strconv"
|
||||
"time"
|
||||
@@ -17,22 +19,22 @@ import (
|
||||
const page_size = 25
|
||||
|
||||
type Transaction interface {
|
||||
Add(ctx context.Context, tx *sqlx.Tx, user *types.User, transaction types.Transaction) (*types.Transaction, error)
|
||||
Update(ctx context.Context, user *types.User, transaction types.Transaction) (*types.Transaction, error)
|
||||
Get(ctx context.Context, user *types.User, id string) (*types.Transaction, error)
|
||||
GetAll(ctx context.Context, user *types.User, filter types.TransactionItemsFilter) ([]*types.Transaction, error)
|
||||
Delete(ctx context.Context, user *types.User, id string) error
|
||||
Add(ctx context.Context, tx *sqlx.Tx, user *auth_types.User, transaction types.Transaction) (*types.Transaction, error)
|
||||
Update(ctx context.Context, user *auth_types.User, transaction types.Transaction) (*types.Transaction, error)
|
||||
Get(ctx context.Context, user *auth_types.User, id string) (*types.Transaction, error)
|
||||
GetAll(ctx context.Context, user *auth_types.User, filter types.TransactionItemsFilter) ([]*types.Transaction, error)
|
||||
Delete(ctx context.Context, user *auth_types.User, id string) error
|
||||
|
||||
RecalculateBalances(ctx context.Context, user *types.User) error
|
||||
RecalculateBalances(ctx context.Context, user *auth_types.User) error
|
||||
}
|
||||
|
||||
type TransactionImpl struct {
|
||||
db *sqlx.DB
|
||||
clock Clock
|
||||
random Random
|
||||
clock core.Clock
|
||||
random core.Random
|
||||
}
|
||||
|
||||
func NewTransaction(db *sqlx.DB, random Random, clock Clock) Transaction {
|
||||
func NewTransaction(db *sqlx.DB, random core.Random, clock core.Clock) Transaction {
|
||||
return TransactionImpl{
|
||||
db: db,
|
||||
clock: clock,
|
||||
@@ -40,9 +42,9 @@ func NewTransaction(db *sqlx.DB, random Random, clock Clock) Transaction {
|
||||
}
|
||||
}
|
||||
|
||||
func (s TransactionImpl) Add(ctx context.Context, tx *sqlx.Tx, user *types.User, transactionInput types.Transaction) (*types.Transaction, error) {
|
||||
func (s TransactionImpl) Add(ctx context.Context, tx *sqlx.Tx, user *auth_types.User, transactionInput types.Transaction) (*types.Transaction, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
|
||||
var err error
|
||||
@@ -50,7 +52,7 @@ func (s TransactionImpl) Add(ctx context.Context, tx *sqlx.Tx, user *types.User,
|
||||
if tx == nil {
|
||||
ownsTransaction = true
|
||||
tx, err = s.db.BeginTxx(ctx, nil)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Add", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Add", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -69,7 +71,7 @@ func (s TransactionImpl) Add(ctx context.Context, tx *sqlx.Tx, user *types.User,
|
||||
party, description, error, created_at, created_by)
|
||||
VALUES (:id, :user_id, :account_id, :treasure_chest_id, :value, :timestamp,
|
||||
:party, :description, :error, :created_at, :created_by)`, transaction)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Insert", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Insert", r, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -79,7 +81,7 @@ func (s TransactionImpl) Add(ctx context.Context, tx *sqlx.Tx, user *types.User,
|
||||
UPDATE account
|
||||
SET current_balance = current_balance + ?
|
||||
WHERE id = ? AND user_id = ?`, transaction.Value, transaction.AccountId, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Add", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Add", r, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -90,7 +92,7 @@ func (s TransactionImpl) Add(ctx context.Context, tx *sqlx.Tx, user *types.User,
|
||||
UPDATE treasure_chest
|
||||
SET current_balance = current_balance + ?
|
||||
WHERE id = ? AND user_id = ?`, transaction.Value, transaction.TreasureChestId, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Add", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Add", r, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -98,7 +100,7 @@ func (s TransactionImpl) Add(ctx context.Context, tx *sqlx.Tx, user *types.User,
|
||||
|
||||
if ownsTransaction {
|
||||
err = tx.Commit()
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Add", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Add", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -107,13 +109,13 @@ func (s TransactionImpl) Add(ctx context.Context, tx *sqlx.Tx, user *types.User,
|
||||
return transaction, nil
|
||||
}
|
||||
|
||||
func (s TransactionImpl) Update(ctx context.Context, user *types.User, input types.Transaction) (*types.Transaction, error) {
|
||||
func (s TransactionImpl) Update(ctx context.Context, user *auth_types.User, input types.Transaction) (*types.Transaction, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Update", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Update", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -123,12 +125,12 @@ func (s TransactionImpl) Update(ctx context.Context, user *types.User, input typ
|
||||
|
||||
transaction := &types.Transaction{}
|
||||
err = tx.GetContext(ctx, transaction, `SELECT * FROM "transaction" WHERE user_id = ? AND id = ?`, user.Id, input.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Update", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Update", nil, err)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return nil, fmt.Errorf("transaction %v not found: %w", input.Id, ErrBadRequest)
|
||||
if errors.Is(err, core.ErrNotFound) {
|
||||
return nil, fmt.Errorf("transaction %v not found: %w", input.Id, core.ErrBadRequest)
|
||||
}
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
if transaction.Error == nil && transaction.AccountId != nil {
|
||||
@@ -136,7 +138,7 @@ func (s TransactionImpl) Update(ctx context.Context, user *types.User, input typ
|
||||
UPDATE account
|
||||
SET current_balance = current_balance - ?
|
||||
WHERE id = ? AND user_id = ?`, transaction.Value, transaction.AccountId, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Update", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Update", r, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -146,7 +148,7 @@ func (s TransactionImpl) Update(ctx context.Context, user *types.User, input typ
|
||||
UPDATE treasure_chest
|
||||
SET current_balance = current_balance - ?
|
||||
WHERE id = ? AND user_id = ?`, transaction.Value, transaction.TreasureChestId, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Update", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Update", r, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -162,7 +164,7 @@ func (s TransactionImpl) Update(ctx context.Context, user *types.User, input typ
|
||||
UPDATE account
|
||||
SET current_balance = current_balance + ?
|
||||
WHERE id = ? AND user_id = ?`, transaction.Value, transaction.AccountId, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Update", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Update", r, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -172,7 +174,7 @@ func (s TransactionImpl) Update(ctx context.Context, user *types.User, input typ
|
||||
UPDATE treasure_chest
|
||||
SET current_balance = current_balance + ?
|
||||
WHERE id = ? AND user_id = ?`, transaction.Value, transaction.TreasureChestId, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Update", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Update", r, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -192,13 +194,13 @@ func (s TransactionImpl) Update(ctx context.Context, user *types.User, input typ
|
||||
updated_by = :updated_by
|
||||
WHERE id = :id
|
||||
AND user_id = :user_id`, transaction)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Update", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Update", r, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Update", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Update", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -206,32 +208,32 @@ func (s TransactionImpl) Update(ctx context.Context, user *types.User, input typ
|
||||
return transaction, nil
|
||||
}
|
||||
|
||||
func (s TransactionImpl) Get(ctx context.Context, user *types.User, id string) (*types.Transaction, error) {
|
||||
func (s TransactionImpl) Get(ctx context.Context, user *auth_types.User, id string) (*types.Transaction, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
uuid, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "transaction get", "err", err)
|
||||
return nil, fmt.Errorf("could not parse Id: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("could not parse Id: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
var transaction types.Transaction
|
||||
err = s.db.GetContext(ctx, &transaction, `SELECT * FROM "transaction" WHERE user_id = ? AND id = ?`, user.Id, uuid)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Get", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Get", nil, err)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return nil, fmt.Errorf("transaction %v not found: %w", id, ErrBadRequest)
|
||||
if errors.Is(err, core.ErrNotFound) {
|
||||
return nil, fmt.Errorf("transaction %v not found: %w", id, core.ErrBadRequest)
|
||||
}
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
return &transaction, nil
|
||||
}
|
||||
|
||||
func (s TransactionImpl) GetAll(ctx context.Context, user *types.User, filter types.TransactionItemsFilter) ([]*types.Transaction, error) {
|
||||
func (s TransactionImpl) GetAll(ctx context.Context, user *auth_types.User, filter types.TransactionItemsFilter) ([]*types.Transaction, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -269,7 +271,7 @@ func (s TransactionImpl) GetAll(ctx context.Context, user *types.User, filter ty
|
||||
filter.Error,
|
||||
page_size,
|
||||
offset)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction GetAll", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction GetAll", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -277,18 +279,18 @@ func (s TransactionImpl) GetAll(ctx context.Context, user *types.User, filter ty
|
||||
return transactions, nil
|
||||
}
|
||||
|
||||
func (s TransactionImpl) Delete(ctx context.Context, user *types.User, id string) error {
|
||||
func (s TransactionImpl) Delete(ctx context.Context, user *auth_types.User, id string) error {
|
||||
if user == nil {
|
||||
return ErrUnauthorized
|
||||
return core.ErrUnauthorized
|
||||
}
|
||||
uuid, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "transaction delete", "err", err)
|
||||
return fmt.Errorf("could not parse Id: %w", ErrBadRequest)
|
||||
return fmt.Errorf("could not parse Id: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Delete", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Delete", nil, err)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -298,7 +300,7 @@ func (s TransactionImpl) Delete(ctx context.Context, user *types.User, id string
|
||||
|
||||
var transaction types.Transaction
|
||||
err = tx.GetContext(ctx, &transaction, `SELECT * FROM "transaction" WHERE user_id = ? AND id = ?`, user.Id, uuid)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Delete", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Delete", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -309,8 +311,8 @@ func (s TransactionImpl) Delete(ctx context.Context, user *types.User, id string
|
||||
SET current_balance = current_balance - ?
|
||||
WHERE id = ?
|
||||
AND user_id = ?`, transaction.Value, transaction.AccountId, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Delete", r, err)
|
||||
if err != nil && !errors.Is(err, db.ErrNotFound) {
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Delete", r, err)
|
||||
if err != nil && !errors.Is(err, core.ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -321,20 +323,20 @@ func (s TransactionImpl) Delete(ctx context.Context, user *types.User, id string
|
||||
SET current_balance = current_balance - ?
|
||||
WHERE id = ?
|
||||
AND user_id = ?`, transaction.Value, transaction.TreasureChestId, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Delete", r, err)
|
||||
if err != nil && !errors.Is(err, db.ErrNotFound) {
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Delete", r, err)
|
||||
if err != nil && !errors.Is(err, core.ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
r, err := tx.ExecContext(ctx, "DELETE FROM \"transaction\" WHERE id = ? AND user_id = ?", uuid, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Delete", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Delete", r, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
err = db.TransformAndLogDbError(ctx, "transaction Delete", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction Delete", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -342,13 +344,13 @@ func (s TransactionImpl) Delete(ctx context.Context, user *types.User, id string
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s TransactionImpl) RecalculateBalances(ctx context.Context, user *types.User) error {
|
||||
func (s TransactionImpl) RecalculateBalances(ctx context.Context, user *auth_types.User) error {
|
||||
if user == nil {
|
||||
return ErrUnauthorized
|
||||
return core.ErrUnauthorized
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction RecalculateBalances", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction RecalculateBalances", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -360,8 +362,8 @@ func (s TransactionImpl) RecalculateBalances(ctx context.Context, user *types.Us
|
||||
UPDATE account
|
||||
SET current_balance = 0
|
||||
WHERE user_id = ?`, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction RecalculateBalances", r, err)
|
||||
if err != nil && !errors.Is(err, db.ErrNotFound) {
|
||||
err = core.TransformAndLogDbError(ctx, "transaction RecalculateBalances", r, err)
|
||||
if err != nil && !errors.Is(err, core.ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -369,8 +371,8 @@ func (s TransactionImpl) RecalculateBalances(ctx context.Context, user *types.Us
|
||||
UPDATE treasure_chest
|
||||
SET current_balance = 0
|
||||
WHERE user_id = ?`, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction RecalculateBalances", r, err)
|
||||
if err != nil && !errors.Is(err, db.ErrNotFound) {
|
||||
err = core.TransformAndLogDbError(ctx, "transaction RecalculateBalances", r, err)
|
||||
if err != nil && !errors.Is(err, core.ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -378,8 +380,8 @@ func (s TransactionImpl) RecalculateBalances(ctx context.Context, user *types.Us
|
||||
SELECT *
|
||||
FROM "transaction"
|
||||
WHERE user_id = ?`, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction RecalculateBalances", nil, err)
|
||||
if err != nil && !errors.Is(err, db.ErrNotFound) {
|
||||
err = core.TransformAndLogDbError(ctx, "transaction RecalculateBalances", nil, err)
|
||||
if err != nil && !errors.Is(err, core.ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
@@ -392,7 +394,7 @@ func (s TransactionImpl) RecalculateBalances(ctx context.Context, user *types.Us
|
||||
var transaction types.Transaction
|
||||
for rows.Next() {
|
||||
err = rows.StructScan(&transaction)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction RecalculateBalances", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction RecalculateBalances", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -403,7 +405,7 @@ func (s TransactionImpl) RecalculateBalances(ctx context.Context, user *types.Us
|
||||
SET error = ?
|
||||
WHERE user_id = ?
|
||||
AND id = ?`, transaction.Error, user.Id, transaction.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction RecalculateBalances", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction RecalculateBalances", r, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -417,7 +419,7 @@ func (s TransactionImpl) RecalculateBalances(ctx context.Context, user *types.Us
|
||||
UPDATE account
|
||||
SET current_balance = current_balance + ?
|
||||
WHERE id = ? AND user_id = ?`, transaction.Value, transaction.AccountId, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction RecalculateBalances", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction RecalculateBalances", r, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -427,7 +429,7 @@ func (s TransactionImpl) RecalculateBalances(ctx context.Context, user *types.Us
|
||||
UPDATE treasure_chest
|
||||
SET current_balance = current_balance + ?
|
||||
WHERE id = ? AND user_id = ?`, transaction.Value, transaction.TreasureChestId, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction RecalculateBalances", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction RecalculateBalances", r, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -435,7 +437,7 @@ func (s TransactionImpl) RecalculateBalances(ctx context.Context, user *types.Us
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
err = db.TransformAndLogDbError(ctx, "transaction RecalculateBalances", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction RecalculateBalances", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -458,7 +460,7 @@ func (s TransactionImpl) validateAndEnrichTransaction(ctx context.Context, tx *s
|
||||
if oldTransaction == nil {
|
||||
id, err = s.random.UUID(ctx)
|
||||
if err != nil {
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
createdAt = s.clock.Now()
|
||||
createdBy = userId
|
||||
@@ -473,39 +475,39 @@ func (s TransactionImpl) validateAndEnrichTransaction(ctx context.Context, tx *s
|
||||
|
||||
if input.AccountId != nil {
|
||||
err = tx.GetContext(ctx, &rowCount, `SELECT COUNT(*) FROM account WHERE id = ? AND user_id = ?`, input.AccountId, userId)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction validate", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction validate", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rowCount == 0 {
|
||||
slog.ErrorContext(ctx, "transaction validate", "err", err)
|
||||
return nil, fmt.Errorf("account not found: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("account not found: %w", core.ErrBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
if input.TreasureChestId != nil {
|
||||
var treasureChest types.TreasureChest
|
||||
var treasureChest treasure_chest_types.TreasureChest
|
||||
err = tx.GetContext(ctx, &treasureChest, `SELECT * FROM treasure_chest WHERE id = ? AND user_id = ?`, input.TreasureChestId, userId)
|
||||
err = db.TransformAndLogDbError(ctx, "transaction validate", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transaction validate", nil, err)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return nil, fmt.Errorf("treasure chest not found: %w", ErrBadRequest)
|
||||
if errors.Is(err, core.ErrNotFound) {
|
||||
return nil, fmt.Errorf("treasure chest not found: %w", core.ErrBadRequest)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if treasureChest.ParentId == nil {
|
||||
return nil, fmt.Errorf("treasure chest is a group: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("treasure chest is a group: %w", core.ErrBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
if input.Party != "" {
|
||||
err = validateString(input.Party, "party")
|
||||
err = core.ValidateString(input.Party, "party")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if input.Description != "" {
|
||||
err = validateString(input.Description, "description")
|
||||
err = core.ValidateString(input.Description, "description")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
package account
|
||||
@@ -1 +0,0 @@
|
||||
package auth
|
||||
@@ -1,2 +0,0 @@
|
||||
package dashboard
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
package transaction
|
||||
|
||||
import "fmt"
|
||||
import "time"
|
||||
import "spend-sparrow/internal/template/svg"
|
||||
import "spend-sparrow/internal/types"
|
||||
import "github.com/google/uuid"
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"spend-sparrow/internal/account"
|
||||
"spend-sparrow/internal/template/svg"
|
||||
"spend-sparrow/internal/treasure_chest_types"
|
||||
"spend-sparrow/internal/types"
|
||||
"time"
|
||||
)
|
||||
|
||||
templ Transaction(items templ.Component, filter types.TransactionItemsFilter, accounts []*types.Account, treasureChests []*types.TreasureChest) {
|
||||
templ Transaction(items templ.Component, filter types.TransactionItemsFilter, accounts []*account.Account, treasureChests []*treasure_chest_types.TreasureChest) {
|
||||
<div class="max-w-6xl mt-10 mx-auto">
|
||||
<div class="flex items-center gap-4">
|
||||
<form
|
||||
@@ -95,7 +99,7 @@ templ TransactionItems(transactions []*types.Transaction, accounts, treasureChes
|
||||
</div>
|
||||
}
|
||||
|
||||
templ EditTransaction(transaction *types.Transaction, accounts []*types.Account, treasureChests []*types.TreasureChest) {
|
||||
templ EditTransaction(transaction *types.Transaction, accounts []*account.Account, treasureChests []*treasure_chest_types.TreasureChest) {
|
||||
{{
|
||||
var (
|
||||
timestamp time.Time
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
package transaction_recurring
|
||||
@@ -1 +0,0 @@
|
||||
package treasurechest
|
||||
@@ -1,41 +1,39 @@
|
||||
package handler
|
||||
package transaction_recurring
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"spend-sparrow/internal/handler/middleware"
|
||||
"spend-sparrow/internal/service"
|
||||
t "spend-sparrow/internal/template/transaction_recurring"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/auth_types"
|
||||
"spend-sparrow/internal/core"
|
||||
"spend-sparrow/internal/utils"
|
||||
)
|
||||
|
||||
type TransactionRecurring interface {
|
||||
type Handler interface {
|
||||
Handle(router *http.ServeMux)
|
||||
}
|
||||
|
||||
type TransactionRecurringImpl struct {
|
||||
s service.TransactionRecurring
|
||||
r *Render
|
||||
type HandlerImpl struct {
|
||||
s Service
|
||||
r *core.Render
|
||||
}
|
||||
|
||||
func NewTransactionRecurring(s service.TransactionRecurring, r *Render) TransactionRecurring {
|
||||
return TransactionRecurringImpl{
|
||||
func NewHandler(s Service, r *core.Render) Handler {
|
||||
return HandlerImpl{
|
||||
s: s,
|
||||
r: r,
|
||||
}
|
||||
}
|
||||
|
||||
func (h TransactionRecurringImpl) Handle(r *http.ServeMux) {
|
||||
func (h HandlerImpl) Handle(r *http.ServeMux) {
|
||||
r.Handle("GET /transaction-recurring", h.handleTransactionRecurringItemComp())
|
||||
r.Handle("POST /transaction-recurring/{id}", h.handleUpdateTransactionRecurring())
|
||||
r.Handle("DELETE /transaction-recurring/{id}", h.handleDeleteTransactionRecurring())
|
||||
}
|
||||
|
||||
func (h TransactionRecurringImpl) handleTransactionRecurringItemComp() http.HandlerFunc {
|
||||
func (h HandlerImpl) handleTransactionRecurringItemComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -48,17 +46,17 @@ func (h TransactionRecurringImpl) handleTransactionRecurringItemComp() http.Hand
|
||||
}
|
||||
}
|
||||
|
||||
func (h TransactionRecurringImpl) handleUpdateTransactionRecurring() http.HandlerFunc {
|
||||
func (h HandlerImpl) handleUpdateTransactionRecurring() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
input := types.TransactionRecurringInput{
|
||||
input := TransactionRecurringInput{
|
||||
Id: r.PathValue("id"),
|
||||
IntervalMonths: r.FormValue("interval-months"),
|
||||
NextExecution: r.FormValue("next-execution"),
|
||||
@@ -72,13 +70,13 @@ func (h TransactionRecurringImpl) handleUpdateTransactionRecurring() http.Handle
|
||||
if input.Id == "new" {
|
||||
_, err := h.s.Add(r.Context(), user, input)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
_, err := h.s.Update(r.Context(), user, input)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -87,11 +85,11 @@ func (h TransactionRecurringImpl) handleUpdateTransactionRecurring() http.Handle
|
||||
}
|
||||
}
|
||||
|
||||
func (h TransactionRecurringImpl) handleDeleteTransactionRecurring() http.HandlerFunc {
|
||||
func (h HandlerImpl) handleDeleteTransactionRecurring() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -103,7 +101,7 @@ func (h TransactionRecurringImpl) handleDeleteTransactionRecurring() http.Handle
|
||||
|
||||
err := h.s.Delete(r.Context(), user, id)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -111,8 +109,8 @@ func (h TransactionRecurringImpl) handleDeleteTransactionRecurring() http.Handle
|
||||
}
|
||||
}
|
||||
|
||||
func (h TransactionRecurringImpl) renderItems(w http.ResponseWriter, r *http.Request, user *types.User, id, accountId, treasureChestId string) {
|
||||
var transactionsRecurring []*types.TransactionRecurring
|
||||
func (h HandlerImpl) renderItems(w http.ResponseWriter, r *http.Request, user *auth_types.User, id, accountId, treasureChestId string) {
|
||||
var transactionsRecurring []*TransactionRecurring
|
||||
var err error
|
||||
if accountId == "" && treasureChestId == "" {
|
||||
utils.TriggerToastWithStatus(r.Context(), w, r, "error", "Please select an account or treasure chest", http.StatusBadRequest)
|
||||
@@ -120,17 +118,17 @@ func (h TransactionRecurringImpl) renderItems(w http.ResponseWriter, r *http.Req
|
||||
if accountId != "" {
|
||||
transactionsRecurring, err = h.s.GetAllByAccount(r.Context(), user, accountId)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
transactionsRecurring, err = h.s.GetAllByTreasureChest(r.Context(), user, treasureChestId)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
comp := t.TransactionRecurringItems(transactionsRecurring, id, accountId, treasureChestId)
|
||||
comp := TransactionRecurringItems(transactionsRecurring, id, accountId, treasureChestId)
|
||||
h.r.Render(r, w, comp)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package service
|
||||
package transaction_recurring
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -6,7 +6,10 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math"
|
||||
"spend-sparrow/internal/db"
|
||||
"spend-sparrow/internal/auth_types"
|
||||
"spend-sparrow/internal/core"
|
||||
"spend-sparrow/internal/service"
|
||||
"spend-sparrow/internal/treasure_chest_types"
|
||||
"spend-sparrow/internal/types"
|
||||
"strconv"
|
||||
"time"
|
||||
@@ -15,26 +18,30 @@ import (
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
type TransactionRecurring interface {
|
||||
Add(ctx context.Context, user *types.User, transactionRecurring types.TransactionRecurringInput) (*types.TransactionRecurring, error)
|
||||
Update(ctx context.Context, user *types.User, transactionRecurring types.TransactionRecurringInput) (*types.TransactionRecurring, error)
|
||||
GetAll(ctx context.Context, user *types.User) ([]*types.TransactionRecurring, error)
|
||||
GetAllByAccount(ctx context.Context, user *types.User, accountId string) ([]*types.TransactionRecurring, error)
|
||||
GetAllByTreasureChest(ctx context.Context, user *types.User, treasureChestId string) ([]*types.TransactionRecurring, error)
|
||||
Delete(ctx context.Context, user *types.User, id string) error
|
||||
const (
|
||||
DECIMALS_MULTIPLIER = 100
|
||||
)
|
||||
|
||||
type Service interface {
|
||||
Add(ctx context.Context, user *auth_types.User, transactionRecurring TransactionRecurringInput) (*TransactionRecurring, error)
|
||||
Update(ctx context.Context, user *auth_types.User, transactionRecurring TransactionRecurringInput) (*TransactionRecurring, error)
|
||||
GetAll(ctx context.Context, user *auth_types.User) ([]*TransactionRecurring, error)
|
||||
GetAllByAccount(ctx context.Context, user *auth_types.User, accountId string) ([]*TransactionRecurring, error)
|
||||
GetAllByTreasureChest(ctx context.Context, user *auth_types.User, treasureChestId string) ([]*TransactionRecurring, error)
|
||||
Delete(ctx context.Context, user *auth_types.User, id string) error
|
||||
|
||||
GenerateTransactions(ctx context.Context) error
|
||||
}
|
||||
|
||||
type TransactionRecurringImpl struct {
|
||||
type ServiceImpl struct {
|
||||
db *sqlx.DB
|
||||
clock Clock
|
||||
random Random
|
||||
transaction Transaction
|
||||
clock core.Clock
|
||||
random core.Random
|
||||
transaction service.Transaction
|
||||
}
|
||||
|
||||
func NewTransactionRecurring(db *sqlx.DB, random Random, clock Clock, transaction Transaction) TransactionRecurring {
|
||||
return TransactionRecurringImpl{
|
||||
func NewService(db *sqlx.DB, random core.Random, clock core.Clock, transaction service.Transaction) Service {
|
||||
return ServiceImpl{
|
||||
db: db,
|
||||
clock: clock,
|
||||
random: random,
|
||||
@@ -42,16 +49,16 @@ func NewTransactionRecurring(db *sqlx.DB, random Random, clock Clock, transactio
|
||||
}
|
||||
}
|
||||
|
||||
func (s TransactionRecurringImpl) Add(ctx context.Context,
|
||||
user *types.User,
|
||||
transactionRecurringInput types.TransactionRecurringInput,
|
||||
) (*types.TransactionRecurring, error) {
|
||||
func (s ServiceImpl) Add(ctx context.Context,
|
||||
user *auth_types.User,
|
||||
transactionRecurringInput TransactionRecurringInput,
|
||||
) (*TransactionRecurring, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring Add", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring Add", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -70,13 +77,13 @@ func (s TransactionRecurringImpl) Add(ctx context.Context,
|
||||
VALUES (:id, :user_id, :interval_months,
|
||||
:next_execution, :party, :description, :account_id, :treasure_chest_id, :value, :created_at, :created_by)`,
|
||||
transactionRecurring)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring Insert", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring Insert", r, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring Add", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring Add", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -84,21 +91,21 @@ func (s TransactionRecurringImpl) Add(ctx context.Context,
|
||||
return transactionRecurring, nil
|
||||
}
|
||||
|
||||
func (s TransactionRecurringImpl) Update(ctx context.Context,
|
||||
user *types.User,
|
||||
input types.TransactionRecurringInput,
|
||||
) (*types.TransactionRecurring, error) {
|
||||
func (s ServiceImpl) Update(ctx context.Context,
|
||||
user *auth_types.User,
|
||||
input TransactionRecurringInput,
|
||||
) (*TransactionRecurring, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
uuid, err := uuid.Parse(input.Id)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "transactionRecurring update", "err", err)
|
||||
return nil, fmt.Errorf("could not parse Id: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("could not parse Id: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring Update", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring Update", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -106,14 +113,14 @@ func (s TransactionRecurringImpl) Update(ctx context.Context,
|
||||
_ = tx.Rollback()
|
||||
}()
|
||||
|
||||
transactionRecurring := &types.TransactionRecurring{}
|
||||
transactionRecurring := &TransactionRecurring{}
|
||||
err = tx.GetContext(ctx, transactionRecurring, `SELECT * FROM transaction_recurring WHERE user_id = ? AND id = ?`, user.Id, uuid)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring Update", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring Update", nil, err)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return nil, fmt.Errorf("transactionRecurring %v not found: %w", input.Id, ErrBadRequest)
|
||||
if errors.Is(err, core.ErrNotFound) {
|
||||
return nil, fmt.Errorf("transactionRecurring %v not found: %w", input.Id, core.ErrBadRequest)
|
||||
}
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
transactionRecurring, err = s.validateAndEnrichTransactionRecurring(ctx, tx, transactionRecurring, user.Id, input)
|
||||
@@ -135,13 +142,13 @@ func (s TransactionRecurringImpl) Update(ctx context.Context,
|
||||
updated_by = :updated_by
|
||||
WHERE id = :id
|
||||
AND user_id = :user_id`, transactionRecurring)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring Update", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring Update", r, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring Update", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring Update", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -149,19 +156,19 @@ func (s TransactionRecurringImpl) Update(ctx context.Context,
|
||||
return transactionRecurring, nil
|
||||
}
|
||||
|
||||
func (s TransactionRecurringImpl) GetAll(ctx context.Context, user *types.User) ([]*types.TransactionRecurring, error) {
|
||||
func (s ServiceImpl) GetAll(ctx context.Context, user *auth_types.User) ([]*TransactionRecurring, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
|
||||
transactionRecurrings := make([]*types.TransactionRecurring, 0)
|
||||
transactionRecurrings := make([]*TransactionRecurring, 0)
|
||||
err := s.db.SelectContext(ctx, &transactionRecurrings, `
|
||||
SELECT *
|
||||
FROM transaction_recurring
|
||||
WHERE user_id = ?
|
||||
ORDER BY created_at DESC`,
|
||||
user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring GetAll", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring GetAll", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -169,19 +176,19 @@ func (s TransactionRecurringImpl) GetAll(ctx context.Context, user *types.User)
|
||||
return transactionRecurrings, nil
|
||||
}
|
||||
|
||||
func (s TransactionRecurringImpl) GetAllByAccount(ctx context.Context, user *types.User, accountId string) ([]*types.TransactionRecurring, error) {
|
||||
func (s ServiceImpl) GetAllByAccount(ctx context.Context, user *auth_types.User, accountId string) ([]*TransactionRecurring, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
|
||||
accountUuid, err := uuid.Parse(accountId)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "transactionRecurring GetAllByAccount", "err", err)
|
||||
return nil, fmt.Errorf("could not parse accountId: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("could not parse accountId: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring GetAllByAccount", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring GetAllByAccount", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -191,15 +198,15 @@ func (s TransactionRecurringImpl) GetAllByAccount(ctx context.Context, user *typ
|
||||
|
||||
var rowCount int
|
||||
err = tx.GetContext(ctx, &rowCount, `SELECT COUNT(*) FROM account WHERE id = ? AND user_id = ?`, accountUuid, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring GetAllByAccount", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring GetAllByAccount", nil, err)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return nil, fmt.Errorf("account %v not found: %w", accountId, ErrBadRequest)
|
||||
if errors.Is(err, core.ErrNotFound) {
|
||||
return nil, fmt.Errorf("account %v not found: %w", accountId, core.ErrBadRequest)
|
||||
}
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
transactionRecurrings := make([]*types.TransactionRecurring, 0)
|
||||
transactionRecurrings := make([]*TransactionRecurring, 0)
|
||||
err = tx.SelectContext(ctx, &transactionRecurrings, `
|
||||
SELECT *
|
||||
FROM transaction_recurring
|
||||
@@ -207,13 +214,13 @@ func (s TransactionRecurringImpl) GetAllByAccount(ctx context.Context, user *typ
|
||||
AND account_id = ?
|
||||
ORDER BY created_at DESC`,
|
||||
user.Id, accountUuid)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring GetAll", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring GetAll", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring GetAllByAccount", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring GetAllByAccount", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -221,22 +228,22 @@ func (s TransactionRecurringImpl) GetAllByAccount(ctx context.Context, user *typ
|
||||
return transactionRecurrings, nil
|
||||
}
|
||||
|
||||
func (s TransactionRecurringImpl) GetAllByTreasureChest(ctx context.Context,
|
||||
user *types.User,
|
||||
func (s ServiceImpl) GetAllByTreasureChest(ctx context.Context,
|
||||
user *auth_types.User,
|
||||
treasureChestId string,
|
||||
) ([]*types.TransactionRecurring, error) {
|
||||
) ([]*TransactionRecurring, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
|
||||
treasureChestUuid, err := uuid.Parse(treasureChestId)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "transactionRecurring GetAllByTreasureChest", "err", err)
|
||||
return nil, fmt.Errorf("could not parse treasureChestId: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("could not parse treasureChestId: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring GetAllByTreasureChest", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring GetAllByTreasureChest", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -246,15 +253,15 @@ func (s TransactionRecurringImpl) GetAllByTreasureChest(ctx context.Context,
|
||||
|
||||
var rowCount int
|
||||
err = tx.GetContext(ctx, &rowCount, `SELECT COUNT(*) FROM treasure_chest WHERE id = ? AND user_id = ?`, treasureChestId, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring GetAllByTreasureChest", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring GetAllByTreasureChest", nil, err)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return nil, fmt.Errorf("treasurechest %v not found: %w", treasureChestId, ErrBadRequest)
|
||||
if errors.Is(err, core.ErrNotFound) {
|
||||
return nil, fmt.Errorf("treasurechest %v not found: %w", treasureChestId, core.ErrBadRequest)
|
||||
}
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
transactionRecurrings := make([]*types.TransactionRecurring, 0)
|
||||
transactionRecurrings := make([]*TransactionRecurring, 0)
|
||||
err = tx.SelectContext(ctx, &transactionRecurrings, `
|
||||
SELECT *
|
||||
FROM transaction_recurring
|
||||
@@ -262,13 +269,13 @@ func (s TransactionRecurringImpl) GetAllByTreasureChest(ctx context.Context,
|
||||
AND treasure_chest_id = ?
|
||||
ORDER BY created_at DESC`,
|
||||
user.Id, treasureChestUuid)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring GetAll", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring GetAll", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring GetAllByTreasureChest", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring GetAllByTreasureChest", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -276,18 +283,18 @@ func (s TransactionRecurringImpl) GetAllByTreasureChest(ctx context.Context,
|
||||
return transactionRecurrings, nil
|
||||
}
|
||||
|
||||
func (s TransactionRecurringImpl) Delete(ctx context.Context, user *types.User, id string) error {
|
||||
func (s ServiceImpl) Delete(ctx context.Context, user *auth_types.User, id string) error {
|
||||
if user == nil {
|
||||
return ErrUnauthorized
|
||||
return core.ErrUnauthorized
|
||||
}
|
||||
uuid, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "transactionRecurring delete", "err", err)
|
||||
return fmt.Errorf("could not parse Id: %w", ErrBadRequest)
|
||||
return fmt.Errorf("could not parse Id: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring Delete", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring Delete", nil, err)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -295,21 +302,21 @@ func (s TransactionRecurringImpl) Delete(ctx context.Context, user *types.User,
|
||||
_ = tx.Rollback()
|
||||
}()
|
||||
|
||||
var transactionRecurring types.TransactionRecurring
|
||||
var transactionRecurring TransactionRecurring
|
||||
err = tx.GetContext(ctx, &transactionRecurring, `SELECT * FROM transaction_recurring WHERE user_id = ? AND id = ?`, user.Id, uuid)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring Delete", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring Delete", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r, err := tx.ExecContext(ctx, "DELETE FROM transaction_recurring WHERE id = ? AND user_id = ?", uuid, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring Delete", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring Delete", r, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring Delete", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring Delete", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -317,11 +324,11 @@ func (s TransactionRecurringImpl) Delete(ctx context.Context, user *types.User,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s TransactionRecurringImpl) GenerateTransactions(ctx context.Context) error {
|
||||
func (s ServiceImpl) GenerateTransactions(ctx context.Context) error {
|
||||
now := s.clock.Now()
|
||||
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring GenerateTransactions", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring GenerateTransactions", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -329,17 +336,17 @@ func (s TransactionRecurringImpl) GenerateTransactions(ctx context.Context) erro
|
||||
_ = tx.Rollback()
|
||||
}()
|
||||
|
||||
recurringTransactions := make([]*types.TransactionRecurring, 0)
|
||||
recurringTransactions := make([]*TransactionRecurring, 0)
|
||||
err = tx.SelectContext(ctx, &recurringTransactions, `
|
||||
SELECT * FROM transaction_recurring WHERE next_execution <= ?`,
|
||||
now)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring GenerateTransactions", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring GenerateTransactions", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, transactionRecurring := range recurringTransactions {
|
||||
user := &types.User{
|
||||
user := &auth_types.User{
|
||||
Id: transactionRecurring.UserId,
|
||||
}
|
||||
transaction := types.Transaction{
|
||||
@@ -359,27 +366,27 @@ func (s TransactionRecurringImpl) GenerateTransactions(ctx context.Context) erro
|
||||
nextExecution := transactionRecurring.NextExecution.AddDate(0, int(transactionRecurring.IntervalMonths), 0)
|
||||
r, err := tx.ExecContext(ctx, `UPDATE transaction_recurring SET next_execution = ? WHERE id = ? AND user_id = ?`,
|
||||
nextExecution, transactionRecurring.Id, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring GenerateTransactions", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring GenerateTransactions", r, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring GenerateTransactions", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring GenerateTransactions", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s TransactionRecurringImpl) validateAndEnrichTransactionRecurring(
|
||||
func (s ServiceImpl) validateAndEnrichTransactionRecurring(
|
||||
ctx context.Context,
|
||||
tx *sqlx.Tx,
|
||||
oldTransactionRecurring *types.TransactionRecurring,
|
||||
oldTransactionRecurring *TransactionRecurring,
|
||||
userId uuid.UUID,
|
||||
input types.TransactionRecurringInput,
|
||||
) (*types.TransactionRecurring, error) {
|
||||
input TransactionRecurringInput,
|
||||
) (*TransactionRecurring, error) {
|
||||
var (
|
||||
id uuid.UUID
|
||||
accountUuid *uuid.UUID
|
||||
@@ -397,7 +404,7 @@ func (s TransactionRecurringImpl) validateAndEnrichTransactionRecurring(
|
||||
if oldTransactionRecurring == nil {
|
||||
id, err = s.random.UUID(ctx)
|
||||
if err != nil {
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
createdAt = s.clock.Now()
|
||||
createdBy = userId
|
||||
@@ -416,17 +423,17 @@ func (s TransactionRecurringImpl) validateAndEnrichTransactionRecurring(
|
||||
temp, err := uuid.Parse(input.AccountId)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "transactionRecurring validate", "err", err)
|
||||
return nil, fmt.Errorf("could not parse accountId: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("could not parse accountId: %w", core.ErrBadRequest)
|
||||
}
|
||||
accountUuid = &temp
|
||||
err = tx.GetContext(ctx, &rowCount, `SELECT COUNT(*) FROM account WHERE id = ? AND user_id = ?`, accountUuid, userId)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring validate", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring validate", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rowCount == 0 {
|
||||
slog.ErrorContext(ctx, "transactionRecurring validate", "err", err)
|
||||
return nil, fmt.Errorf("account not found: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("account not found: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
hasAccount = true
|
||||
@@ -436,48 +443,48 @@ func (s TransactionRecurringImpl) validateAndEnrichTransactionRecurring(
|
||||
temp, err := uuid.Parse(input.TreasureChestId)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "transactionRecurring validate", "err", err)
|
||||
return nil, fmt.Errorf("could not parse treasureChestId: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("could not parse treasureChestId: %w", core.ErrBadRequest)
|
||||
}
|
||||
treasureChestUuid = &temp
|
||||
var treasureChest types.TreasureChest
|
||||
var treasureChest treasure_chest_types.TreasureChest
|
||||
err = tx.GetContext(ctx, &treasureChest, `SELECT * FROM treasure_chest WHERE id = ? AND user_id = ?`, treasureChestUuid, userId)
|
||||
err = db.TransformAndLogDbError(ctx, "transactionRecurring validate", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "transactionRecurring validate", nil, err)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return nil, fmt.Errorf("treasure chest not found: %w", ErrBadRequest)
|
||||
if errors.Is(err, core.ErrNotFound) {
|
||||
return nil, fmt.Errorf("treasure chest not found: %w", core.ErrBadRequest)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if treasureChest.ParentId == nil {
|
||||
return nil, fmt.Errorf("treasure chest is a group: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("treasure chest is a group: %w", core.ErrBadRequest)
|
||||
}
|
||||
hasTreasureChest = true
|
||||
}
|
||||
|
||||
if !hasAccount && !hasTreasureChest {
|
||||
slog.ErrorContext(ctx, "transactionRecurring validate", "err", err)
|
||||
return nil, fmt.Errorf("either account or treasure chest is required: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("either account or treasure chest is required: %w", core.ErrBadRequest)
|
||||
}
|
||||
if hasAccount && hasTreasureChest {
|
||||
slog.ErrorContext(ctx, "transactionRecurring validate", "err", err)
|
||||
return nil, fmt.Errorf("either account or treasure chest is required, not both: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("either account or treasure chest is required, not both: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
valueFloat, err := strconv.ParseFloat(input.Value, 64)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "transactionRecurring validate", "err", err)
|
||||
return nil, fmt.Errorf("could not parse value: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("could not parse value: %w", core.ErrBadRequest)
|
||||
}
|
||||
value := int64(math.Round(valueFloat * DECIMALS_MULTIPLIER))
|
||||
|
||||
if input.Party != "" {
|
||||
err = validateString(input.Party, "party")
|
||||
err = core.ValidateString(input.Party, "party")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if input.Description != "" {
|
||||
err = validateString(input.Description, "description")
|
||||
err = core.ValidateString(input.Description, "description")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -485,25 +492,25 @@ func (s TransactionRecurringImpl) validateAndEnrichTransactionRecurring(
|
||||
intervalMonths, err = strconv.ParseInt(input.IntervalMonths, 10, 0)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "transactionRecurring validate", "err", err)
|
||||
return nil, fmt.Errorf("could not parse intervalMonths: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("could not parse intervalMonths: %w", core.ErrBadRequest)
|
||||
}
|
||||
if intervalMonths < 1 {
|
||||
slog.ErrorContext(ctx, "transactionRecurring validate", "err", err)
|
||||
return nil, fmt.Errorf("intervalMonths needs to be greater than 0: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("intervalMonths needs to be greater than 0: %w", core.ErrBadRequest)
|
||||
}
|
||||
var nextExecution *time.Time = nil
|
||||
if input.NextExecution != "" {
|
||||
t, err := time.Parse("2006-01-02", input.NextExecution)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "transaction validate", "err", err)
|
||||
return nil, fmt.Errorf("could not parse timestamp: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("could not parse timestamp: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
t = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
|
||||
nextExecution = &t
|
||||
}
|
||||
|
||||
transactionRecurring := types.TransactionRecurring{
|
||||
transactionRecurring := TransactionRecurring{
|
||||
Id: id,
|
||||
UserId: userId,
|
||||
|
||||
@@ -5,7 +5,7 @@ import "time"
|
||||
import "spend-sparrow/internal/template/svg"
|
||||
import "spend-sparrow/internal/types"
|
||||
|
||||
templ TransactionRecurringItems(transactionsRecurring []*types.TransactionRecurring, editId, accountId, treasureChestId string) {
|
||||
templ TransactionRecurringItems(transactionsRecurring []*TransactionRecurring, editId, accountId, treasureChestId string) {
|
||||
<!-- Don't use table, because embedded forms are only valid for cells -->
|
||||
<div id="transaction-recurring" class="max-w-full grid gap-4 mt-10 grid-cols-[max-content_auto_auto_auto_auto_max-content] items-center text-xl">
|
||||
<span class="text-sm text-gray-500">Next Execution</span>
|
||||
@@ -27,7 +27,7 @@ templ TransactionRecurringItems(transactionsRecurring []*types.TransactionRecurr
|
||||
</div>
|
||||
}
|
||||
|
||||
templ TransactionRecurringItem(transactionRecurring *types.TransactionRecurring, accountId, treasureChestId string) {
|
||||
templ TransactionRecurringItem(transactionRecurring *TransactionRecurring, accountId, treasureChestId string) {
|
||||
<p class="text-gray-600">
|
||||
if transactionRecurring.NextExecution != nil {
|
||||
{ transactionRecurring.NextExecution.Format("2006/01") }
|
||||
@@ -84,7 +84,7 @@ templ TransactionRecurringItem(transactionRecurring *types.TransactionRecurring,
|
||||
</div>
|
||||
}
|
||||
|
||||
templ EditTransactionRecurring(transactionRecurring *types.TransactionRecurring, accountId, treasureChestId string) {
|
||||
templ EditTransactionRecurring(transactionRecurring *TransactionRecurring, accountId, treasureChestId string) {
|
||||
{{
|
||||
var (
|
||||
id string
|
||||
@@ -1,4 +1,4 @@
|
||||
package types
|
||||
package transaction_recurring
|
||||
|
||||
import (
|
||||
"time"
|
||||
@@ -1,48 +1,46 @@
|
||||
package handler
|
||||
package treasure_chest
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"spend-sparrow/internal/handler/middleware"
|
||||
"spend-sparrow/internal/service"
|
||||
tr "spend-sparrow/internal/template/transaction_recurring"
|
||||
t "spend-sparrow/internal/template/treasurechest"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/core"
|
||||
"spend-sparrow/internal/transaction_recurring"
|
||||
"spend-sparrow/internal/treasure_chest_types"
|
||||
"spend-sparrow/internal/utils"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type TreasureChest interface {
|
||||
type Handler interface {
|
||||
Handle(router *http.ServeMux)
|
||||
}
|
||||
|
||||
type TreasureChestImpl struct {
|
||||
s service.TreasureChest
|
||||
transactionRecurring service.TransactionRecurring
|
||||
r *Render
|
||||
type HandlerImpl struct {
|
||||
s Service
|
||||
transactionRecurring transaction_recurring.Service
|
||||
r *core.Render
|
||||
}
|
||||
|
||||
func NewTreasureChest(s service.TreasureChest, transactionRecurring service.TransactionRecurring, r *Render) TreasureChest {
|
||||
return TreasureChestImpl{
|
||||
func NewHandler(s Service, transactionRecurring transaction_recurring.Service, r *core.Render) Handler {
|
||||
return HandlerImpl{
|
||||
s: s,
|
||||
transactionRecurring: transactionRecurring,
|
||||
r: r,
|
||||
}
|
||||
}
|
||||
|
||||
func (h TreasureChestImpl) Handle(r *http.ServeMux) {
|
||||
r.Handle("GET /treasurechest", h.handleTreasureChestPage())
|
||||
r.Handle("GET /treasurechest/{id}", h.handleTreasureChestItemComp())
|
||||
r.Handle("POST /treasurechest/{id}", h.handleUpdateTreasureChest())
|
||||
r.Handle("DELETE /treasurechest/{id}", h.handleDeleteTreasureChest())
|
||||
func (h HandlerImpl) Handle(r *http.ServeMux) {
|
||||
r.Handle("GET /treasurechest", h.handleHandlerPage())
|
||||
r.Handle("GET /treasurechest/{id}", h.handleHandlerItemComp())
|
||||
r.Handle("POST /treasurechest/{id}", h.handleUpdateHandler())
|
||||
r.Handle("DELETE /treasurechest/{id}", h.handleDeleteHandler())
|
||||
}
|
||||
|
||||
func (h TreasureChestImpl) handleTreasureChestPage() http.HandlerFunc {
|
||||
func (h HandlerImpl) handleHandlerPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -50,28 +48,28 @@ func (h TreasureChestImpl) handleTreasureChestPage() http.HandlerFunc {
|
||||
|
||||
treasureChests, err := h.s.GetAll(r.Context(), user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
transactionsRecurring, err := h.transactionRecurring.GetAll(r.Context(), user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
monthlySums := h.calculateMonthlySums(treasureChests, transactionsRecurring)
|
||||
|
||||
comp := t.TreasureChest(treasureChests, monthlySums)
|
||||
comp := TreasureChestComp(treasureChests, monthlySums)
|
||||
h.r.RenderLayout(r, w, comp, user)
|
||||
}
|
||||
}
|
||||
|
||||
func (h TreasureChestImpl) handleTreasureChestItemComp() http.HandlerFunc {
|
||||
func (h HandlerImpl) handleHandlerItemComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -79,53 +77,53 @@ func (h TreasureChestImpl) handleTreasureChestItemComp() http.HandlerFunc {
|
||||
|
||||
treasureChests, err := h.s.GetAll(r.Context(), user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
id := r.PathValue("id")
|
||||
if id == "new" {
|
||||
comp := t.EditTreasureChest(nil, treasureChests, nil)
|
||||
comp := EditTreasureChest(nil, treasureChests, nil)
|
||||
h.r.Render(r, w, comp)
|
||||
return
|
||||
}
|
||||
|
||||
treasureChest, err := h.s.Get(r.Context(), user, id)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
transactionsRecurring, err := h.transactionRecurring.GetAllByTreasureChest(r.Context(), user, treasureChest.Id.String())
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
transactionsRec := tr.TransactionRecurringItems(transactionsRecurring, "", "", treasureChest.Id.String())
|
||||
transactionsRec := transaction_recurring.TransactionRecurringItems(transactionsRecurring, "", "", treasureChest.Id.String())
|
||||
|
||||
var comp templ.Component
|
||||
if r.URL.Query().Get("edit") == "true" {
|
||||
comp = t.EditTreasureChest(treasureChest, treasureChests, transactionsRec)
|
||||
comp = EditTreasureChest(treasureChest, treasureChests, transactionsRec)
|
||||
} else {
|
||||
monthlySums := h.calculateMonthlySums(treasureChests, transactionsRecurring)
|
||||
comp = t.TreasureChestItem(treasureChest, monthlySums)
|
||||
comp = TreasureChestItem(treasureChest, monthlySums)
|
||||
}
|
||||
h.r.Render(r, w, comp)
|
||||
}
|
||||
}
|
||||
|
||||
func (h TreasureChestImpl) handleUpdateTreasureChest() http.HandlerFunc {
|
||||
func (h HandlerImpl) handleUpdateHandler() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
treasureChest *types.TreasureChest
|
||||
treasureChest *treasure_chest_types.TreasureChest
|
||||
err error
|
||||
)
|
||||
id := r.PathValue("id")
|
||||
@@ -134,36 +132,36 @@ func (h TreasureChestImpl) handleUpdateTreasureChest() http.HandlerFunc {
|
||||
if id == "new" {
|
||||
treasureChest, err = h.s.Add(r.Context(), user, parentId, name)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
treasureChest, err = h.s.Update(r.Context(), user, id, parentId, name)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
transactionsRecurring, err := h.transactionRecurring.GetAllByTreasureChest(r.Context(), user, treasureChest.Id.String())
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
treasureChests := make([]*types.TreasureChest, 1)
|
||||
treasureChests := make([]*treasure_chest_types.TreasureChest, 1)
|
||||
treasureChests[0] = treasureChest
|
||||
monthlySums := h.calculateMonthlySums(treasureChests, transactionsRecurring)
|
||||
comp := t.TreasureChestItem(treasureChest, monthlySums)
|
||||
comp := TreasureChestItem(treasureChest, monthlySums)
|
||||
h.r.Render(r, w, comp)
|
||||
}
|
||||
}
|
||||
|
||||
func (h TreasureChestImpl) handleDeleteTreasureChest() http.HandlerFunc {
|
||||
func (h HandlerImpl) handleDeleteHandler() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateSpan(r)
|
||||
core.UpdateSpan(r)
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
user := core.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
@@ -173,15 +171,15 @@ func (h TreasureChestImpl) handleDeleteTreasureChest() http.HandlerFunc {
|
||||
|
||||
err := h.s.Delete(r.Context(), user, id)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
core.HandleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h TreasureChestImpl) calculateMonthlySums(
|
||||
treasureChests []*types.TreasureChest,
|
||||
transactionsRecurring []*types.TransactionRecurring,
|
||||
func (h HandlerImpl) calculateMonthlySums(
|
||||
treasureChests []*treasure_chest_types.TreasureChest,
|
||||
transactionsRecurring []*transaction_recurring.TransactionRecurring,
|
||||
) map[uuid.UUID]int64 {
|
||||
monthlySums := make(map[uuid.UUID]int64)
|
||||
for _, tc := range treasureChests {
|
||||
@@ -1,4 +1,4 @@
|
||||
package service
|
||||
package treasure_chest
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -6,46 +6,47 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"spend-sparrow/internal/db"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/auth_types"
|
||||
"spend-sparrow/internal/core"
|
||||
"spend-sparrow/internal/treasure_chest_types"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
type TreasureChest interface {
|
||||
Add(ctx context.Context, user *types.User, parentId, name string) (*types.TreasureChest, error)
|
||||
Update(ctx context.Context, user *types.User, id, parentId, name string) (*types.TreasureChest, error)
|
||||
Get(ctx context.Context, user *types.User, id string) (*types.TreasureChest, error)
|
||||
GetAll(ctx context.Context, user *types.User) ([]*types.TreasureChest, error)
|
||||
Delete(ctx context.Context, user *types.User, id string) error
|
||||
type Service interface {
|
||||
Add(ctx context.Context, user *auth_types.User, parentId, name string) (*treasure_chest_types.TreasureChest, error)
|
||||
Update(ctx context.Context, user *auth_types.User, id, parentId, name string) (*treasure_chest_types.TreasureChest, error)
|
||||
Get(ctx context.Context, user *auth_types.User, id string) (*treasure_chest_types.TreasureChest, error)
|
||||
GetAll(ctx context.Context, user *auth_types.User) ([]*treasure_chest_types.TreasureChest, error)
|
||||
Delete(ctx context.Context, user *auth_types.User, id string) error
|
||||
}
|
||||
|
||||
type TreasureChestImpl struct {
|
||||
type ServiceImpl struct {
|
||||
db *sqlx.DB
|
||||
clock Clock
|
||||
random Random
|
||||
clock core.Clock
|
||||
random core.Random
|
||||
}
|
||||
|
||||
func NewTreasureChest(db *sqlx.DB, random Random, clock Clock) TreasureChest {
|
||||
return TreasureChestImpl{
|
||||
func NewService(db *sqlx.DB, random core.Random, clock core.Clock) Service {
|
||||
return ServiceImpl{
|
||||
db: db,
|
||||
clock: clock,
|
||||
random: random,
|
||||
}
|
||||
}
|
||||
|
||||
func (s TreasureChestImpl) Add(ctx context.Context, user *types.User, parentId, name string) (*types.TreasureChest, error) {
|
||||
func (s ServiceImpl) Add(ctx context.Context, user *auth_types.User, parentId, name string) (*treasure_chest_types.TreasureChest, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
|
||||
newId, err := s.random.UUID(ctx)
|
||||
if err != nil {
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
err = validateString(name, "name")
|
||||
err = core.ValidateString(name, "name")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -57,12 +58,12 @@ func (s TreasureChestImpl) Add(ctx context.Context, user *types.User, parentId,
|
||||
return nil, err
|
||||
}
|
||||
if parent.ParentId != nil {
|
||||
return nil, fmt.Errorf("only a depth of 1 allowed: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("only a depth of 1 allowed: %w", core.ErrBadRequest)
|
||||
}
|
||||
parentUuid = &parent.Id
|
||||
}
|
||||
|
||||
treasureChest := &types.TreasureChest{
|
||||
treasureChest := &treasure_chest_types.TreasureChest{
|
||||
Id: newId,
|
||||
ParentId: parentUuid,
|
||||
UserId: user.Id,
|
||||
@@ -80,7 +81,7 @@ func (s TreasureChestImpl) Add(ctx context.Context, user *types.User, parentId,
|
||||
r, err := s.db.NamedExecContext(ctx, `
|
||||
INSERT INTO treasure_chest (id, parent_id, user_id, name, current_balance, created_at, created_by)
|
||||
VALUES (:id, :parent_id, :user_id, :name, :current_balance, :created_at, :created_by)`, treasureChest)
|
||||
err = db.TransformAndLogDbError(ctx, "treasureChest Insert", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "treasureChest Insert", r, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -88,22 +89,22 @@ func (s TreasureChestImpl) Add(ctx context.Context, user *types.User, parentId,
|
||||
return treasureChest, nil
|
||||
}
|
||||
|
||||
func (s TreasureChestImpl) Update(ctx context.Context, user *types.User, idStr, parentId, name string) (*types.TreasureChest, error) {
|
||||
func (s ServiceImpl) Update(ctx context.Context, user *auth_types.User, idStr, parentId, name string) (*treasure_chest_types.TreasureChest, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
err := validateString(name, "name")
|
||||
err := core.ValidateString(name, "name")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, err := uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "treasureChest update", "err", err)
|
||||
return nil, fmt.Errorf("could not parse Id: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("could not parse Id: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
err = db.TransformAndLogDbError(ctx, "treasureChest Update", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "treasureChest Update", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -111,14 +112,14 @@ func (s TreasureChestImpl) Update(ctx context.Context, user *types.User, idStr,
|
||||
_ = tx.Rollback()
|
||||
}()
|
||||
|
||||
treasureChest := &types.TreasureChest{}
|
||||
treasureChest := &treasure_chest_types.TreasureChest{}
|
||||
err = tx.GetContext(ctx, treasureChest, `SELECT * FROM treasure_chest WHERE user_id = ? AND id = ?`, user.Id, id)
|
||||
err = db.TransformAndLogDbError(ctx, "treasureChest Update", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "treasureChest Update", nil, err)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
if errors.Is(err, core.ErrNotFound) {
|
||||
return nil, fmt.Errorf("treasureChest %v not found: %w", idStr, err)
|
||||
}
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
var parentUuid *uuid.UUID
|
||||
@@ -129,12 +130,12 @@ func (s TreasureChestImpl) Update(ctx context.Context, user *types.User, idStr,
|
||||
}
|
||||
var childCount int
|
||||
err = tx.GetContext(ctx, &childCount, `SELECT COUNT(*) FROM treasure_chest WHERE user_id = ? AND parent_id = ?`, user.Id, id)
|
||||
err = db.TransformAndLogDbError(ctx, "treasureChest Update", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "treasureChest Update", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if parent.ParentId != nil || childCount > 0 {
|
||||
return nil, fmt.Errorf("only one level allowed: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("only one level allowed: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
parentUuid = &parent.Id
|
||||
@@ -156,13 +157,13 @@ func (s TreasureChestImpl) Update(ctx context.Context, user *types.User, idStr,
|
||||
updated_by = :updated_by
|
||||
WHERE id = :id
|
||||
AND user_id = :user_id`, treasureChest)
|
||||
err = db.TransformAndLogDbError(ctx, "treasureChest Update", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "treasureChest Update", r, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
err = db.TransformAndLogDbError(ctx, "treasureChest Update", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "treasureChest Update", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -170,56 +171,56 @@ func (s TreasureChestImpl) Update(ctx context.Context, user *types.User, idStr,
|
||||
return treasureChest, nil
|
||||
}
|
||||
|
||||
func (s TreasureChestImpl) Get(ctx context.Context, user *types.User, id string) (*types.TreasureChest, error) {
|
||||
func (s ServiceImpl) Get(ctx context.Context, user *auth_types.User, id string) (*treasure_chest_types.TreasureChest, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
uuid, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "treasureChest get", "err", err)
|
||||
return nil, fmt.Errorf("could not parse Id: %w", ErrBadRequest)
|
||||
return nil, fmt.Errorf("could not parse Id: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
var treasureChest types.TreasureChest
|
||||
var treasureChest treasure_chest_types.TreasureChest
|
||||
err = s.db.GetContext(ctx, &treasureChest, `SELECT * FROM treasure_chest WHERE user_id = ? AND id = ?`, user.Id, uuid)
|
||||
err = db.TransformAndLogDbError(ctx, "treasureChest Get", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "treasureChest Get", nil, err)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
if errors.Is(err, core.ErrNotFound) {
|
||||
return nil, fmt.Errorf("treasureChest %v not found: %w", id, err)
|
||||
}
|
||||
return nil, types.ErrInternal
|
||||
return nil, core.ErrInternal
|
||||
}
|
||||
|
||||
return &treasureChest, nil
|
||||
}
|
||||
|
||||
func (s TreasureChestImpl) GetAll(ctx context.Context, user *types.User) ([]*types.TreasureChest, error) {
|
||||
func (s ServiceImpl) GetAll(ctx context.Context, user *auth_types.User) ([]*treasure_chest_types.TreasureChest, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
return nil, core.ErrUnauthorized
|
||||
}
|
||||
|
||||
treasureChests := make([]*types.TreasureChest, 0)
|
||||
treasureChests := make([]*treasure_chest_types.TreasureChest, 0)
|
||||
err := s.db.SelectContext(ctx, &treasureChests, `SELECT * FROM treasure_chest WHERE user_id = ?`, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "treasureChest GetAll", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "treasureChest GetAll", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return sortTreasureChests(treasureChests), nil
|
||||
return SortTreasureChests(treasureChests), nil
|
||||
}
|
||||
|
||||
func (s TreasureChestImpl) Delete(ctx context.Context, user *types.User, idStr string) error {
|
||||
func (s ServiceImpl) Delete(ctx context.Context, user *auth_types.User, idStr string) error {
|
||||
if user == nil {
|
||||
return ErrUnauthorized
|
||||
return core.ErrUnauthorized
|
||||
}
|
||||
id, err := uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx, "treasureChest delete", "err", err)
|
||||
return fmt.Errorf("could not parse Id: %w", ErrBadRequest)
|
||||
return fmt.Errorf("could not parse Id: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
err = db.TransformAndLogDbError(ctx, "treasureChest Delete", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "treasureChest Delete", nil, err)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -229,47 +230,47 @@ func (s TreasureChestImpl) Delete(ctx context.Context, user *types.User, idStr s
|
||||
|
||||
childCount := 0
|
||||
err = tx.GetContext(ctx, &childCount, `SELECT COUNT(*) FROM treasure_chest WHERE user_id = ? AND parent_id = ?`, user.Id, id)
|
||||
err = db.TransformAndLogDbError(ctx, "treasureChest Delete", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "treasureChest Delete", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if childCount > 0 {
|
||||
return fmt.Errorf("treasure chest has children: %w", ErrBadRequest)
|
||||
return fmt.Errorf("treasure chest has children: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
transactionsCount := 0
|
||||
err = tx.GetContext(ctx, &transactionsCount,
|
||||
`SELECT COUNT(*) FROM "transaction" WHERE user_id = ? AND treasure_chest_id = ?`,
|
||||
user.Id, id)
|
||||
err = db.TransformAndLogDbError(ctx, "treasureChest Delete", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "treasureChest Delete", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if transactionsCount > 0 {
|
||||
return fmt.Errorf("treasure chest has transactions: %w", ErrBadRequest)
|
||||
return fmt.Errorf("treasure chest has transactions: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
recurringCount := 0
|
||||
err = tx.GetContext(ctx, &recurringCount, `
|
||||
SELECT COUNT(*) FROM transaction_recurring WHERE user_id = ? AND treasure_chest_id = ?`,
|
||||
user.Id, id)
|
||||
err = db.TransformAndLogDbError(ctx, "treasureChest Delete", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "treasureChest Delete", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if recurringCount > 0 {
|
||||
return fmt.Errorf("cannot delete treasure chest with existing recurring transactions: %w", ErrBadRequest)
|
||||
return fmt.Errorf("cannot delete treasure chest with existing recurring transactions: %w", core.ErrBadRequest)
|
||||
}
|
||||
|
||||
r, err := tx.ExecContext(ctx, `DELETE FROM treasure_chest WHERE id = ? AND user_id = ?`, id, user.Id)
|
||||
err = db.TransformAndLogDbError(ctx, "treasureChest Delete", r, err)
|
||||
err = core.TransformAndLogDbError(ctx, "treasureChest Delete", r, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
err = db.TransformAndLogDbError(ctx, "treasureChest Delete", nil, err)
|
||||
err = core.TransformAndLogDbError(ctx, "treasureChest Delete", nil, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -277,12 +278,12 @@ func (s TreasureChestImpl) Delete(ctx context.Context, user *types.User, idStr s
|
||||
return nil
|
||||
}
|
||||
|
||||
func sortTreasureChests(nodes []*types.TreasureChest) []*types.TreasureChest {
|
||||
func SortTreasureChests(nodes []*treasure_chest_types.TreasureChest) []*treasure_chest_types.TreasureChest {
|
||||
var (
|
||||
roots []*types.TreasureChest
|
||||
roots []*treasure_chest_types.TreasureChest
|
||||
)
|
||||
children := make(map[uuid.UUID][]*types.TreasureChest)
|
||||
result := make([]*types.TreasureChest, 0)
|
||||
children := make(map[uuid.UUID][]*treasure_chest_types.TreasureChest)
|
||||
result := make([]*treasure_chest_types.TreasureChest, 0)
|
||||
|
||||
for _, node := range nodes {
|
||||
if node.ParentId == nil {
|
||||
@@ -292,7 +293,7 @@ func sortTreasureChests(nodes []*types.TreasureChest) []*types.TreasureChest {
|
||||
}
|
||||
}
|
||||
|
||||
slices.SortFunc(roots, func(a, b *types.TreasureChest) int {
|
||||
slices.SortFunc(roots, func(a, b *treasure_chest_types.TreasureChest) int {
|
||||
return compareStrings(a.Name, b.Name)
|
||||
})
|
||||
|
||||
@@ -301,7 +302,7 @@ func sortTreasureChests(nodes []*types.TreasureChest) []*types.TreasureChest {
|
||||
|
||||
childList := children[root.Id]
|
||||
|
||||
slices.SortFunc(childList, func(a, b *types.TreasureChest) int {
|
||||
slices.SortFunc(childList, func(a, b *treasure_chest_types.TreasureChest) int {
|
||||
return compareStrings(a.Name, b.Name)
|
||||
})
|
||||
result = append(result, childList...)
|
||||
@@ -1,10 +1,13 @@
|
||||
package treasurechest
|
||||
package treasure_chest
|
||||
|
||||
import "spend-sparrow/internal/template/svg"
|
||||
import "spend-sparrow/internal/types"
|
||||
import "github.com/google/uuid"
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"spend-sparrow/internal/template/svg"
|
||||
"spend-sparrow/internal/treasure_chest_types"
|
||||
"spend-sparrow/internal/types"
|
||||
)
|
||||
|
||||
templ TreasureChest(treasureChests []*types.TreasureChest, monthlySums map[uuid.UUID]int64) {
|
||||
templ TreasureChestComp(treasureChests []*treasure_chest_types.TreasureChest, monthlySums map[uuid.UUID]int64) {
|
||||
<div class="max-w-6xl mt-10 mx-auto">
|
||||
<button
|
||||
hx-get="/treasurechest/new"
|
||||
@@ -23,30 +26,30 @@ templ TreasureChest(treasureChests []*types.TreasureChest, monthlySums map[uuid.
|
||||
</div>
|
||||
}
|
||||
|
||||
templ EditTreasureChest(treasureChest *types.TreasureChest, parents []*types.TreasureChest, transactionsRecurring templ.Component) {
|
||||
templ EditTreasureChest(treasureChest *treasure_chest_types.TreasureChest, parents []*treasure_chest_types.TreasureChest, transactionsRecurring templ.Component) {
|
||||
{{
|
||||
var (
|
||||
id string
|
||||
name string
|
||||
parentId uuid.UUID
|
||||
cancelUrl string
|
||||
)
|
||||
var (
|
||||
id string
|
||||
name string
|
||||
parentId uuid.UUID
|
||||
cancelUrl string
|
||||
)
|
||||
|
||||
indentation := " mt-10"
|
||||
if treasureChest == nil {
|
||||
id = "new"
|
||||
name = ""
|
||||
parentId = uuid.Nil
|
||||
cancelUrl = "/empty"
|
||||
} else {
|
||||
id = treasureChest.Id.String()
|
||||
name = treasureChest.Name
|
||||
if treasureChest.ParentId != nil {
|
||||
parentId = *treasureChest.ParentId
|
||||
indentation = " mt-2 ml-14"
|
||||
indentation := " mt-10"
|
||||
if treasureChest == nil {
|
||||
id = "new"
|
||||
name = ""
|
||||
parentId = uuid.Nil
|
||||
cancelUrl = "/empty"
|
||||
} else {
|
||||
id = treasureChest.Id.String()
|
||||
name = treasureChest.Name
|
||||
if treasureChest.ParentId != nil {
|
||||
parentId = *treasureChest.ParentId
|
||||
indentation = " mt-2 ml-14"
|
||||
}
|
||||
cancelUrl = "/treasurechest/" + id
|
||||
}
|
||||
cancelUrl = "/treasurechest/" + id
|
||||
}
|
||||
}}
|
||||
<div id={ "treasurechest-" + id } class={ "border-1 border-gray-300 p-4 bg-gray-50 rounded-lg" + indentation }>
|
||||
<form
|
||||
@@ -115,16 +118,16 @@ templ EditTreasureChest(treasureChest *types.TreasureChest, parents []*types.Tre
|
||||
</div>
|
||||
}
|
||||
|
||||
templ TreasureChestItem(treasureChest *types.TreasureChest, monthlySums map[uuid.UUID]int64) {
|
||||
templ TreasureChestItem(treasureChest *treasure_chest_types.TreasureChest, monthlySums map[uuid.UUID]int64) {
|
||||
{{
|
||||
var indentation string
|
||||
viewTransactions := ""
|
||||
if treasureChest.ParentId != nil {
|
||||
indentation = " mt-2 ml-14"
|
||||
} else {
|
||||
indentation = " mt-10"
|
||||
viewTransactions = "hidden"
|
||||
}
|
||||
var indentation string
|
||||
viewTransactions := ""
|
||||
if treasureChest.ParentId != nil {
|
||||
indentation = " mt-2 ml-14"
|
||||
} else {
|
||||
indentation = " mt-10"
|
||||
viewTransactions = "hidden"
|
||||
}
|
||||
}}
|
||||
<div id={ "treasurechest-" + treasureChest.Id.String() } class={ "border-1 border-gray-300 p-4 bg-gray-50 rounded-lg" + indentation }>
|
||||
<div class="text-xl flex justify-end items-center gap-4">
|
||||
@@ -177,8 +180,8 @@ templ TreasureChestItem(treasureChest *types.TreasureChest, monthlySums map[uuid
|
||||
</div>
|
||||
}
|
||||
|
||||
func filterNoChildNoSelf(nodes []*types.TreasureChest, selfId string) []*types.TreasureChest {
|
||||
var result []*types.TreasureChest
|
||||
func filterNoChildNoSelf(nodes []*treasure_chest_types.TreasureChest, selfId string) []*treasure_chest_types.TreasureChest {
|
||||
var result []*treasure_chest_types.TreasureChest
|
||||
|
||||
for _, node := range nodes {
|
||||
if node.ParentId == nil && node.Id.String() != selfId {
|
||||
@@ -1,4 +1,4 @@
|
||||
package types
|
||||
package treasure_chest_types
|
||||
|
||||
import (
|
||||
"time"
|
||||
@@ -1,10 +0,0 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInternal = errors.New("internal server error")
|
||||
ErrUnauthorized = errors.New("you are not authorized to perform this action")
|
||||
)
|
||||
@@ -1 +0,0 @@
|
||||
package mocks
|
||||
156
package-lock.json
generated
156
package-lock.json
generated
@@ -9,10 +9,10 @@
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"@tailwindcss/cli": "4.1.16",
|
||||
"@tailwindcss/cli": "4.1.18",
|
||||
"echarts": "6.0.0",
|
||||
"htmx.org": "2.0.8",
|
||||
"tailwindcss": "4.1.16"
|
||||
"tailwindcss": "4.1.18"
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/gen-mapping": {
|
||||
@@ -375,28 +375,28 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/cli": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/cli/-/cli-4.1.16.tgz",
|
||||
"integrity": "sha512-dsnANPrh2ZooHyZ/8uJhc9ecpcYtufToc21NY09NS9vF16rxPCjJ8dP7TUAtPqlUJTHSmRkN2hCdoYQIlgh4fw==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/cli/-/cli-4.1.18.tgz",
|
||||
"integrity": "sha512-sMZ+lZbDyxwjD2E0L7oRUjJ01Ffjtme5OtjvvnC+cV4CEDcbqzbp25TCpxHj6kWLU9+DlqJOiNgSOgctC2aZmg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@parcel/watcher": "^2.5.1",
|
||||
"@tailwindcss/node": "4.1.16",
|
||||
"@tailwindcss/oxide": "4.1.16",
|
||||
"@tailwindcss/node": "4.1.18",
|
||||
"@tailwindcss/oxide": "4.1.18",
|
||||
"enhanced-resolve": "^5.18.3",
|
||||
"mri": "^1.2.0",
|
||||
"picocolors": "^1.1.1",
|
||||
"tailwindcss": "4.1.16"
|
||||
"tailwindcss": "4.1.18"
|
||||
},
|
||||
"bin": {
|
||||
"tailwindcss": "dist/index.mjs"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/node": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.16.tgz",
|
||||
"integrity": "sha512-BX5iaSsloNuvKNHRN3k2RcCuTEgASTo77mofW0vmeHkfrDWaoFAFvNHpEgtu0eqyypcyiBkDWzSMxJhp3AUVcw==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.18.tgz",
|
||||
"integrity": "sha512-DoR7U1P7iYhw16qJ49fgXUlry1t4CpXeErJHnQ44JgTSKMaZUdf17cfn5mHchfJ4KRBZRFA/Coo+MUF5+gOaCQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -404,39 +404,39 @@
|
||||
"enhanced-resolve": "^5.18.3",
|
||||
"jiti": "^2.6.1",
|
||||
"lightningcss": "1.30.2",
|
||||
"magic-string": "^0.30.19",
|
||||
"magic-string": "^0.30.21",
|
||||
"source-map-js": "^1.2.1",
|
||||
"tailwindcss": "4.1.16"
|
||||
"tailwindcss": "4.1.18"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.1.16.tgz",
|
||||
"integrity": "sha512-2OSv52FRuhdlgyOQqgtQHuCgXnS8nFSYRp2tJ+4WZXKgTxqPy7SMSls8c3mPT5pkZ17SBToGM5LHEJBO7miEdg==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.1.18.tgz",
|
||||
"integrity": "sha512-EgCR5tTS5bUSKQgzeMClT6iCY3ToqE1y+ZB0AKldj809QXk1Y+3jB0upOYZrn9aGIzPtUsP7sX4QQ4XtjBB95A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@tailwindcss/oxide-android-arm64": "4.1.16",
|
||||
"@tailwindcss/oxide-darwin-arm64": "4.1.16",
|
||||
"@tailwindcss/oxide-darwin-x64": "4.1.16",
|
||||
"@tailwindcss/oxide-freebsd-x64": "4.1.16",
|
||||
"@tailwindcss/oxide-linux-arm-gnueabihf": "4.1.16",
|
||||
"@tailwindcss/oxide-linux-arm64-gnu": "4.1.16",
|
||||
"@tailwindcss/oxide-linux-arm64-musl": "4.1.16",
|
||||
"@tailwindcss/oxide-linux-x64-gnu": "4.1.16",
|
||||
"@tailwindcss/oxide-linux-x64-musl": "4.1.16",
|
||||
"@tailwindcss/oxide-wasm32-wasi": "4.1.16",
|
||||
"@tailwindcss/oxide-win32-arm64-msvc": "4.1.16",
|
||||
"@tailwindcss/oxide-win32-x64-msvc": "4.1.16"
|
||||
"@tailwindcss/oxide-android-arm64": "4.1.18",
|
||||
"@tailwindcss/oxide-darwin-arm64": "4.1.18",
|
||||
"@tailwindcss/oxide-darwin-x64": "4.1.18",
|
||||
"@tailwindcss/oxide-freebsd-x64": "4.1.18",
|
||||
"@tailwindcss/oxide-linux-arm-gnueabihf": "4.1.18",
|
||||
"@tailwindcss/oxide-linux-arm64-gnu": "4.1.18",
|
||||
"@tailwindcss/oxide-linux-arm64-musl": "4.1.18",
|
||||
"@tailwindcss/oxide-linux-x64-gnu": "4.1.18",
|
||||
"@tailwindcss/oxide-linux-x64-musl": "4.1.18",
|
||||
"@tailwindcss/oxide-wasm32-wasi": "4.1.18",
|
||||
"@tailwindcss/oxide-win32-arm64-msvc": "4.1.18",
|
||||
"@tailwindcss/oxide-win32-x64-msvc": "4.1.18"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-android-arm64": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.1.16.tgz",
|
||||
"integrity": "sha512-8+ctzkjHgwDJ5caq9IqRSgsP70xhdhJvm+oueS/yhD5ixLhqTw9fSL1OurzMUhBwE5zK26FXLCz2f/RtkISqHA==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.1.18.tgz",
|
||||
"integrity": "sha512-dJHz7+Ugr9U/diKJA0W6N/6/cjI+ZTAoxPf9Iz9BFRF2GzEX8IvXxFIi/dZBloVJX/MZGvRuFA9rqwdiIEZQ0Q==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -451,9 +451,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-darwin-arm64": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.1.16.tgz",
|
||||
"integrity": "sha512-C3oZy5042v2FOALBZtY0JTDnGNdS6w7DxL/odvSny17ORUnaRKhyTse8xYi3yKGyfnTUOdavRCdmc8QqJYwFKA==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.1.18.tgz",
|
||||
"integrity": "sha512-Gc2q4Qhs660bhjyBSKgq6BYvwDz4G+BuyJ5H1xfhmDR3D8HnHCmT/BSkvSL0vQLy/nkMLY20PQ2OoYMO15Jd0A==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -468,9 +468,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-darwin-x64": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.1.16.tgz",
|
||||
"integrity": "sha512-vjrl/1Ub9+JwU6BP0emgipGjowzYZMjbWCDqwA2Z4vCa+HBSpP4v6U2ddejcHsolsYxwL5r4bPNoamlV0xDdLg==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.1.18.tgz",
|
||||
"integrity": "sha512-FL5oxr2xQsFrc3X9o1fjHKBYBMD1QZNyc1Xzw/h5Qu4XnEBi3dZn96HcHm41c/euGV+GRiXFfh2hUCyKi/e+yw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -485,9 +485,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-freebsd-x64": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.1.16.tgz",
|
||||
"integrity": "sha512-TSMpPYpQLm+aR1wW5rKuUuEruc/oOX3C7H0BTnPDn7W/eMw8W+MRMpiypKMkXZfwH8wqPIRKppuZoedTtNj2tg==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.1.18.tgz",
|
||||
"integrity": "sha512-Fj+RHgu5bDodmV1dM9yAxlfJwkkWvLiRjbhuO2LEtwtlYlBgiAT4x/j5wQr1tC3SANAgD+0YcmWVrj8R9trVMA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -502,9 +502,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.1.16.tgz",
|
||||
"integrity": "sha512-p0GGfRg/w0sdsFKBjMYvvKIiKy/LNWLWgV/plR4lUgrsxFAoQBFrXkZ4C0w8IOXfslB9vHK/JGASWD2IefIpvw==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.1.18.tgz",
|
||||
"integrity": "sha512-Fp+Wzk/Ws4dZn+LV2Nqx3IilnhH51YZoRaYHQsVq3RQvEl+71VGKFpkfHrLM/Li+kt5c0DJe/bHXK1eHgDmdiA==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
@@ -519,9 +519,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-linux-arm64-gnu": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.1.16.tgz",
|
||||
"integrity": "sha512-DoixyMmTNO19rwRPdqviTrG1rYzpxgyYJl8RgQvdAQUzxC1ToLRqtNJpU/ATURSKgIg6uerPw2feW0aS8SNr/w==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.1.18.tgz",
|
||||
"integrity": "sha512-S0n3jboLysNbh55Vrt7pk9wgpyTTPD0fdQeh7wQfMqLPM/Hrxi+dVsLsPrycQjGKEQk85Kgbx+6+QnYNiHalnw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -536,9 +536,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-linux-arm64-musl": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.1.16.tgz",
|
||||
"integrity": "sha512-H81UXMa9hJhWhaAUca6bU2wm5RRFpuHImrwXBUvPbYb+3jo32I9VIwpOX6hms0fPmA6f2pGVlybO6qU8pF4fzQ==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.1.18.tgz",
|
||||
"integrity": "sha512-1px92582HkPQlaaCkdRcio71p8bc8i/ap5807tPRDK/uw953cauQBT8c5tVGkOwrHMfc2Yh6UuxaH4vtTjGvHg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -553,9 +553,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-linux-x64-gnu": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.1.16.tgz",
|
||||
"integrity": "sha512-ZGHQxDtFC2/ruo7t99Qo2TTIvOERULPl5l0K1g0oK6b5PGqjYMga+FcY1wIUnrUxY56h28FxybtDEla+ICOyew==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.1.18.tgz",
|
||||
"integrity": "sha512-v3gyT0ivkfBLoZGF9LyHmts0Isc8jHZyVcbzio6Wpzifg/+5ZJpDiRiUhDLkcr7f/r38SWNe7ucxmGW3j3Kb/g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -570,9 +570,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-linux-x64-musl": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.1.16.tgz",
|
||||
"integrity": "sha512-Oi1tAaa0rcKf1Og9MzKeINZzMLPbhxvm7rno5/zuP1WYmpiG0bEHq4AcRUiG2165/WUzvxkW4XDYCscZWbTLZw==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.1.18.tgz",
|
||||
"integrity": "sha512-bhJ2y2OQNlcRwwgOAGMY0xTFStt4/wyU6pvI6LSuZpRgKQwxTec0/3Scu91O8ir7qCR3AuepQKLU/kX99FouqQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -587,9 +587,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-wasm32-wasi": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.1.16.tgz",
|
||||
"integrity": "sha512-B01u/b8LteGRwucIBmCQ07FVXLzImWESAIMcUU6nvFt/tYsQ6IHz8DmZ5KtvmwxD+iTYBtM1xwoGXswnlu9v0Q==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.1.18.tgz",
|
||||
"integrity": "sha512-LffYTvPjODiP6PT16oNeUQJzNVyJl1cjIebq/rWWBF+3eDst5JGEFSc5cWxyRCJ0Mxl+KyIkqRxk1XPEs9x8TA==",
|
||||
"bundleDependencies": [
|
||||
"@napi-rs/wasm-runtime",
|
||||
"@emnapi/core",
|
||||
@@ -605,10 +605,10 @@
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@emnapi/core": "^1.5.0",
|
||||
"@emnapi/runtime": "^1.5.0",
|
||||
"@emnapi/core": "^1.7.1",
|
||||
"@emnapi/runtime": "^1.7.1",
|
||||
"@emnapi/wasi-threads": "^1.1.0",
|
||||
"@napi-rs/wasm-runtime": "^1.0.7",
|
||||
"@napi-rs/wasm-runtime": "^1.1.0",
|
||||
"@tybys/wasm-util": "^0.10.1",
|
||||
"tslib": "^2.4.0"
|
||||
},
|
||||
@@ -617,7 +617,7 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {
|
||||
"version": "1.5.0",
|
||||
"version": "1.7.1",
|
||||
"dev": true,
|
||||
"inBundle": true,
|
||||
"license": "MIT",
|
||||
@@ -628,7 +628,7 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {
|
||||
"version": "1.5.0",
|
||||
"version": "1.7.1",
|
||||
"dev": true,
|
||||
"inBundle": true,
|
||||
"license": "MIT",
|
||||
@@ -648,14 +648,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {
|
||||
"version": "1.0.7",
|
||||
"version": "1.1.0",
|
||||
"dev": true,
|
||||
"inBundle": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@emnapi/core": "^1.5.0",
|
||||
"@emnapi/runtime": "^1.5.0",
|
||||
"@emnapi/core": "^1.7.1",
|
||||
"@emnapi/runtime": "^1.7.1",
|
||||
"@tybys/wasm-util": "^0.10.1"
|
||||
}
|
||||
},
|
||||
@@ -677,9 +677,9 @@
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.1.16.tgz",
|
||||
"integrity": "sha512-zX+Q8sSkGj6HKRTMJXuPvOcP8XfYON24zJBRPlszcH1Np7xuHXhWn8qfFjIujVzvH3BHU+16jBXwgpl20i+v9A==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.1.18.tgz",
|
||||
"integrity": "sha512-HjSA7mr9HmC8fu6bdsZvZ+dhjyGCLdotjVOgLA2vEqxEBZaQo9YTX4kwgEvPCpRh8o4uWc4J/wEoFzhEmjvPbA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -694,9 +694,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-win32-x64-msvc": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.1.16.tgz",
|
||||
"integrity": "sha512-m5dDFJUEejbFqP+UXVstd4W/wnxA4F61q8SoL+mqTypId2T2ZpuxosNSgowiCnLp2+Z+rivdU0AqpfgiD7yCBg==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.1.18.tgz",
|
||||
"integrity": "sha512-bJWbyYpUlqamC8dpR7pfjA0I7vdF6t5VpUGMWRkXVE3AXgIZjYUYAK7II1GNaxR8J1SSrSrppRar8G++JekE3Q==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1103,9 +1103,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/magic-string": {
|
||||
"version": "0.30.19",
|
||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.19.tgz",
|
||||
"integrity": "sha512-2N21sPY9Ws53PZvsEpVtNuSW+ScYbQdp4b9qUaL+9QkHUrGFKo56Lg9Emg5s9V/qrtNBmiR01sYhUOwu3H+VOw==",
|
||||
"version": "0.30.21",
|
||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
|
||||
"integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -1174,9 +1174,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/tailwindcss": {
|
||||
"version": "4.1.16",
|
||||
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.16.tgz",
|
||||
"integrity": "sha512-pONL5awpaQX4LN5eiv7moSiSPd/DLDzKVRJz8Q9PgzmAdd1R4307GQS2ZpfiN7ZmekdQrfhZZiSE5jkLR4WNaA==",
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.18.tgz",
|
||||
"integrity": "sha512-4+Z+0yiYyEtUVCScyfHCxOYP06L5Ne+JiHhY2IjR2KWMIWhJOYZKLSGZaP5HkZ8+bY0cxfzwDE5uOmzFXyIwxw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
|
||||
@@ -11,9 +11,9 @@
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"@tailwindcss/cli": "4.1.16",
|
||||
"@tailwindcss/cli": "4.1.18",
|
||||
"htmx.org": "2.0.8",
|
||||
"tailwindcss": "4.1.16",
|
||||
"tailwindcss": "4.1.18",
|
||||
"echarts": "6.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,9 @@ package test_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"spend-sparrow/internal/db"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/auth_types"
|
||||
"spend-sparrow/internal/authentication"
|
||||
"spend-sparrow/internal/core"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -27,7 +28,7 @@ func setupDb(t *testing.T) *sqlx.DB {
|
||||
}
|
||||
})
|
||||
|
||||
err = db.RunMigrations(context.Background(), d, "../")
|
||||
err = core.RunMigrations(context.Background(), d, "../")
|
||||
if err != nil {
|
||||
t.Fatalf("Error running migrations: %v", err)
|
||||
}
|
||||
@@ -42,11 +43,11 @@ func TestUser(t *testing.T) {
|
||||
t.Parallel()
|
||||
d := setupDb(t)
|
||||
|
||||
underTest := db.NewAuthSqlite(d)
|
||||
underTest := authentication.NewDbSqlite(d)
|
||||
|
||||
verifiedAt := time.Date(2020, 1, 5, 13, 0, 0, 0, time.UTC)
|
||||
createAt := time.Date(2020, 1, 5, 12, 0, 0, 0, time.UTC)
|
||||
expected := types.NewUser(uuid.New(), "some@email.de", true, &verifiedAt, false, []byte("somePass"), []byte("someSalt"), createAt)
|
||||
expected := auth_types.NewUser(uuid.New(), "some@email.de", true, &verifiedAt, false, []byte("somePass"), []byte("someSalt"), createAt)
|
||||
|
||||
err := underTest.InsertUser(context.Background(), expected)
|
||||
require.NoError(t, err)
|
||||
@@ -63,38 +64,38 @@ func TestUser(t *testing.T) {
|
||||
t.Parallel()
|
||||
d := setupDb(t)
|
||||
|
||||
underTest := db.NewAuthSqlite(d)
|
||||
underTest := authentication.NewDbSqlite(d)
|
||||
|
||||
_, err := underTest.GetUserByEmail(context.Background(), "nonExistentEmail")
|
||||
assert.Equal(t, db.ErrNotFound, err)
|
||||
assert.Equal(t, core.ErrNotFound, err)
|
||||
})
|
||||
t.Run("should return ErrUserExist", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
d := setupDb(t)
|
||||
|
||||
underTest := db.NewAuthSqlite(d)
|
||||
underTest := authentication.NewDbSqlite(d)
|
||||
|
||||
verifiedAt := time.Date(2020, 1, 5, 13, 0, 0, 0, time.UTC)
|
||||
createAt := time.Date(2020, 1, 5, 12, 0, 0, 0, time.UTC)
|
||||
user := types.NewUser(uuid.New(), "some@email.de", true, &verifiedAt, false, []byte("somePass"), []byte("someSalt"), createAt)
|
||||
user := auth_types.NewUser(uuid.New(), "some@email.de", true, &verifiedAt, false, []byte("somePass"), []byte("someSalt"), createAt)
|
||||
|
||||
err := underTest.InsertUser(context.Background(), user)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = underTest.InsertUser(context.Background(), user)
|
||||
assert.Equal(t, db.ErrAlreadyExists, err)
|
||||
assert.Equal(t, core.ErrAlreadyExists, err)
|
||||
})
|
||||
t.Run("should return ErrInternal on missing NOT NULL fields", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
d := setupDb(t)
|
||||
|
||||
underTest := db.NewAuthSqlite(d)
|
||||
underTest := authentication.NewDbSqlite(d)
|
||||
|
||||
createAt := time.Date(2020, 1, 5, 12, 0, 0, 0, time.UTC)
|
||||
user := types.NewUser(uuid.New(), "some@email.de", false, nil, false, []byte("somePass"), nil, createAt)
|
||||
user := auth_types.NewUser(uuid.New(), "some@email.de", false, nil, false, []byte("somePass"), nil, createAt)
|
||||
|
||||
err := underTest.InsertUser(context.Background(), user)
|
||||
assert.Equal(t, types.ErrInternal, err)
|
||||
assert.Equal(t, core.ErrInternal, err)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -105,11 +106,11 @@ func TestToken(t *testing.T) {
|
||||
t.Parallel()
|
||||
d := setupDb(t)
|
||||
|
||||
underTest := db.NewAuthSqlite(d)
|
||||
underTest := authentication.NewDbSqlite(d)
|
||||
|
||||
createAt := time.Date(2020, 1, 5, 12, 0, 0, 0, time.UTC)
|
||||
expiresAt := createAt.Add(24 * time.Hour)
|
||||
expected := types.NewToken(uuid.New(), "sessionId", "token", types.TokenTypeCsrf, createAt, expiresAt)
|
||||
expected := auth_types.NewToken(uuid.New(), "sessionId", "token", auth_types.TokenTypeCsrf, createAt, expiresAt)
|
||||
|
||||
err := underTest.InsertToken(context.Background(), expected)
|
||||
require.NoError(t, err)
|
||||
@@ -121,25 +122,25 @@ func TestToken(t *testing.T) {
|
||||
expected.SessionId = ""
|
||||
actuals, err := underTest.GetTokensByUserIdAndType(context.Background(), expected.UserId, expected.Type)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []*types.Token{expected}, actuals)
|
||||
assert.Equal(t, []*auth_types.Token{expected}, actuals)
|
||||
|
||||
expected.SessionId = "sessionId"
|
||||
expected.UserId = uuid.Nil
|
||||
actuals, err = underTest.GetTokensBySessionIdAndType(context.Background(), expected.SessionId, expected.Type)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []*types.Token{expected}, actuals)
|
||||
assert.Equal(t, []*auth_types.Token{expected}, actuals)
|
||||
})
|
||||
t.Run("should insert and return multiple tokens", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
d := setupDb(t)
|
||||
|
||||
underTest := db.NewAuthSqlite(d)
|
||||
underTest := authentication.NewDbSqlite(d)
|
||||
|
||||
createAt := time.Date(2020, 1, 5, 12, 0, 0, 0, time.UTC)
|
||||
expiresAt := createAt.Add(24 * time.Hour)
|
||||
userId := uuid.New()
|
||||
expected1 := types.NewToken(userId, "sessionId", "token1", types.TokenTypeCsrf, createAt, expiresAt)
|
||||
expected2 := types.NewToken(userId, "sessionId", "token2", types.TokenTypeCsrf, createAt, expiresAt)
|
||||
expected1 := auth_types.NewToken(userId, "sessionId", "token1", auth_types.TokenTypeCsrf, createAt, expiresAt)
|
||||
expected2 := auth_types.NewToken(userId, "sessionId", "token2", auth_types.TokenTypeCsrf, createAt, expiresAt)
|
||||
|
||||
err := underTest.InsertToken(context.Background(), expected1)
|
||||
require.NoError(t, err)
|
||||
@@ -150,7 +151,7 @@ func TestToken(t *testing.T) {
|
||||
expected2.UserId = uuid.Nil
|
||||
actuals, err := underTest.GetTokensBySessionIdAndType(context.Background(), expected1.SessionId, expected1.Type)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []*types.Token{expected1, expected2}, actuals)
|
||||
assert.Equal(t, []*auth_types.Token{expected1, expected2}, actuals)
|
||||
|
||||
expected1.SessionId = ""
|
||||
expected2.SessionId = ""
|
||||
@@ -158,49 +159,49 @@ func TestToken(t *testing.T) {
|
||||
expected2.UserId = userId
|
||||
actuals, err = underTest.GetTokensByUserIdAndType(context.Background(), userId, expected1.Type)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []*types.Token{expected1, expected2}, actuals)
|
||||
assert.Equal(t, []*auth_types.Token{expected1, expected2}, actuals)
|
||||
})
|
||||
t.Run("should return ErrNotFound", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
d := setupDb(t)
|
||||
|
||||
underTest := db.NewAuthSqlite(d)
|
||||
underTest := authentication.NewDbSqlite(d)
|
||||
|
||||
_, err := underTest.GetToken(context.Background(), "nonExistent")
|
||||
assert.Equal(t, db.ErrNotFound, err)
|
||||
assert.Equal(t, core.ErrNotFound, err)
|
||||
|
||||
_, err = underTest.GetTokensByUserIdAndType(context.Background(), uuid.New(), types.TokenTypeEmailVerify)
|
||||
assert.Equal(t, db.ErrNotFound, err)
|
||||
_, err = underTest.GetTokensByUserIdAndType(context.Background(), uuid.New(), auth_types.TokenTypeEmailVerify)
|
||||
assert.Equal(t, core.ErrNotFound, err)
|
||||
|
||||
_, err = underTest.GetTokensBySessionIdAndType(context.Background(), "sessionId", types.TokenTypeEmailVerify)
|
||||
assert.Equal(t, db.ErrNotFound, err)
|
||||
_, err = underTest.GetTokensBySessionIdAndType(context.Background(), "sessionId", auth_types.TokenTypeEmailVerify)
|
||||
assert.Equal(t, core.ErrNotFound, err)
|
||||
})
|
||||
t.Run("should return ErrAlreadyExists", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
d := setupDb(t)
|
||||
|
||||
underTest := db.NewAuthSqlite(d)
|
||||
underTest := authentication.NewDbSqlite(d)
|
||||
|
||||
verifiedAt := time.Date(2020, 1, 5, 13, 0, 0, 0, time.UTC)
|
||||
createAt := time.Date(2020, 1, 5, 12, 0, 0, 0, time.UTC)
|
||||
user := types.NewUser(uuid.New(), "some@email.de", true, &verifiedAt, false, []byte("somePass"), []byte("someSalt"), createAt)
|
||||
user := auth_types.NewUser(uuid.New(), "some@email.de", true, &verifiedAt, false, []byte("somePass"), []byte("someSalt"), createAt)
|
||||
|
||||
err := underTest.InsertUser(context.Background(), user)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = underTest.InsertUser(context.Background(), user)
|
||||
assert.Equal(t, db.ErrAlreadyExists, err)
|
||||
assert.Equal(t, core.ErrAlreadyExists, err)
|
||||
})
|
||||
t.Run("should return ErrInternal on missing NOT NULL fields", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
d := setupDb(t)
|
||||
|
||||
underTest := db.NewAuthSqlite(d)
|
||||
underTest := authentication.NewDbSqlite(d)
|
||||
|
||||
createAt := time.Date(2020, 1, 5, 12, 0, 0, 0, time.UTC)
|
||||
user := types.NewUser(uuid.New(), "some@email.de", false, nil, false, []byte("somePass"), nil, createAt)
|
||||
user := auth_types.NewUser(uuid.New(), "some@email.de", false, nil, false, []byte("somePass"), nil, createAt)
|
||||
|
||||
err := underTest.InsertUser(context.Background(), user)
|
||||
assert.Equal(t, types.ErrInternal, err)
|
||||
assert.Equal(t, core.ErrInternal, err)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2,8 +2,9 @@ package test_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"spend-sparrow/internal/db"
|
||||
"spend-sparrow/internal/service"
|
||||
"spend-sparrow/internal/auth_types"
|
||||
"spend-sparrow/internal/authentication"
|
||||
"spend-sparrow/internal/core"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/mocks"
|
||||
"strings"
|
||||
@@ -30,26 +31,26 @@ func TestSignUp(t *testing.T) {
|
||||
t.Run("should check for correct email address", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mockAuthDb := mocks.NewMockAuth(t)
|
||||
mockAuthDb := mocks.NewMockDb(t)
|
||||
mockRandom := mocks.NewMockRandom(t)
|
||||
mockClock := mocks.NewMockClock(t)
|
||||
mockMail := mocks.NewMockMail(t)
|
||||
|
||||
underTest := service.NewAuth(mockAuthDb, mockRandom, mockClock, mockMail, &settings)
|
||||
underTest := authentication.NewService(mockAuthDb, mockRandom, mockClock, mockMail, &settings)
|
||||
|
||||
_, err := underTest.SignUp(context.Background(), "invalid email address", "SomeStrongPassword123!")
|
||||
|
||||
assert.Equal(t, service.ErrInvalidEmail, err)
|
||||
assert.Equal(t, authentication.ErrInvalidEmail, err)
|
||||
})
|
||||
t.Run("should check for password complexity", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mockAuthDb := mocks.NewMockAuth(t)
|
||||
mockAuthDb := mocks.NewMockDb(t)
|
||||
mockRandom := mocks.NewMockRandom(t)
|
||||
mockClock := mocks.NewMockClock(t)
|
||||
mockMail := mocks.NewMockMail(t)
|
||||
|
||||
underTest := service.NewAuth(mockAuthDb, mockRandom, mockClock, mockMail, &settings)
|
||||
underTest := authentication.NewService(mockAuthDb, mockRandom, mockClock, mockMail, &settings)
|
||||
|
||||
weakPasswords := []string{
|
||||
"123!ab", // too short
|
||||
@@ -60,13 +61,13 @@ func TestSignUp(t *testing.T) {
|
||||
|
||||
for _, password := range weakPasswords {
|
||||
_, err := underTest.SignUp(context.Background(), "some@valid.email", password)
|
||||
assert.Equal(t, service.ErrInvalidPassword, err)
|
||||
assert.Equal(t, authentication.ErrInvalidPassword, err)
|
||||
}
|
||||
})
|
||||
t.Run("should signup correctly", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mockAuthDb := mocks.NewMockAuth(t)
|
||||
mockAuthDb := mocks.NewMockDb(t)
|
||||
mockRandom := mocks.NewMockRandom(t)
|
||||
mockClock := mocks.NewMockClock(t)
|
||||
mockMail := mocks.NewMockMail(t)
|
||||
@@ -77,7 +78,7 @@ func TestSignUp(t *testing.T) {
|
||||
salt := []byte("salt")
|
||||
createTime := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
expected := types.NewUser(userId, email, false, nil, false, service.GetHashPassword(password, salt), salt, createTime)
|
||||
expected := auth_types.NewUser(userId, email, false, nil, false, authentication.GetHashPassword(password, salt), salt, createTime)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
@@ -86,7 +87,7 @@ func TestSignUp(t *testing.T) {
|
||||
mockClock.EXPECT().Now().Return(createTime)
|
||||
mockAuthDb.EXPECT().InsertUser(context.Background(), expected).Return(nil)
|
||||
|
||||
underTest := service.NewAuth(mockAuthDb, mockRandom, mockClock, mockMail, &settings)
|
||||
underTest := authentication.NewService(mockAuthDb, mockRandom, mockClock, mockMail, &settings)
|
||||
actual, err := underTest.SignUp(context.Background(), email, password)
|
||||
|
||||
require.NoError(t, err)
|
||||
@@ -96,7 +97,7 @@ func TestSignUp(t *testing.T) {
|
||||
t.Run("should return ErrAccountExists", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mockAuthDb := mocks.NewMockAuth(t)
|
||||
mockAuthDb := mocks.NewMockDb(t)
|
||||
mockRandom := mocks.NewMockRandom(t)
|
||||
mockClock := mocks.NewMockClock(t)
|
||||
mockMail := mocks.NewMockMail(t)
|
||||
@@ -106,19 +107,19 @@ func TestSignUp(t *testing.T) {
|
||||
createTime := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
password := "SomeStrongPassword123!"
|
||||
salt := []byte("salt")
|
||||
user := types.NewUser(userId, email, false, nil, false, service.GetHashPassword(password, salt), salt, createTime)
|
||||
user := auth_types.NewUser(userId, email, false, nil, false, authentication.GetHashPassword(password, salt), salt, createTime)
|
||||
|
||||
ctx := context.Background()
|
||||
mockRandom.EXPECT().UUID(ctx).Return(user.Id, nil)
|
||||
mockRandom.EXPECT().Bytes(ctx, 16).Return(salt, nil)
|
||||
mockClock.EXPECT().Now().Return(createTime)
|
||||
|
||||
mockAuthDb.EXPECT().InsertUser(context.Background(), user).Return(db.ErrAlreadyExists)
|
||||
mockAuthDb.EXPECT().InsertUser(context.Background(), user).Return(core.ErrAlreadyExists)
|
||||
|
||||
underTest := service.NewAuth(mockAuthDb, mockRandom, mockClock, mockMail, &settings)
|
||||
underTest := authentication.NewService(mockAuthDb, mockRandom, mockClock, mockMail, &settings)
|
||||
|
||||
_, err := underTest.SignUp(context.Background(), user.Email, password)
|
||||
assert.Equal(t, service.ErrAccountExists, err)
|
||||
assert.Equal(t, authentication.ErrAccountExists, err)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -127,30 +128,30 @@ func TestSendVerificationMail(t *testing.T) {
|
||||
t.Run("should use stored token and send mail", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
token := types.NewToken(
|
||||
token := auth_types.NewToken(
|
||||
uuid.New(),
|
||||
"sessionId",
|
||||
"someRandomTokenToUse",
|
||||
types.TokenTypeEmailVerify,
|
||||
auth_types.TokenTypeEmailVerify,
|
||||
time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC))
|
||||
tokens := []*types.Token{token}
|
||||
tokens := []*auth_types.Token{token}
|
||||
|
||||
email := "some@email.de"
|
||||
userId := uuid.New()
|
||||
|
||||
mockAuthDb := mocks.NewMockAuth(t)
|
||||
mockAuthDb := mocks.NewMockDb(t)
|
||||
mockRandom := mocks.NewMockRandom(t)
|
||||
mockClock := mocks.NewMockClock(t)
|
||||
mockMail := mocks.NewMockMail(t)
|
||||
|
||||
ctx := context.Background()
|
||||
mockAuthDb.EXPECT().GetTokensByUserIdAndType(context.Background(), userId, types.TokenTypeEmailVerify).Return(tokens, nil)
|
||||
mockAuthDb.EXPECT().GetTokensByUserIdAndType(context.Background(), userId, auth_types.TokenTypeEmailVerify).Return(tokens, nil)
|
||||
mockMail.EXPECT().SendMail(ctx, email, "Welcome to spend-sparrow", mock.MatchedBy(func(message string) bool {
|
||||
return strings.Contains(message, token.Token)
|
||||
})).Return()
|
||||
|
||||
underTest := service.NewAuth(mockAuthDb, mockRandom, mockClock, mockMail, &settings)
|
||||
underTest := authentication.NewService(mockAuthDb, mockRandom, mockClock, mockMail, &settings)
|
||||
|
||||
underTest.SendVerificationMail(context.Background(), userId, email)
|
||||
})
|
||||
|
||||
@@ -7,8 +7,9 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"spend-sparrow/internal"
|
||||
"spend-sparrow/internal/service"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/auth_types"
|
||||
"spend-sparrow/internal/authentication"
|
||||
"spend-sparrow/internal/core"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
@@ -117,7 +118,7 @@ func waitForReady(
|
||||
default:
|
||||
if time.Since(startTime) >= timeout {
|
||||
t.Fatal("timeout reached while waiting for endpoint")
|
||||
return types.ErrInternal
|
||||
return core.ErrInternal
|
||||
}
|
||||
// wait a little while between checks
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
@@ -178,7 +179,7 @@ func createValidUserSession(t *testing.T, db *sqlx.DB, add string) (uuid.UUID, s
|
||||
t.Helper()
|
||||
userId := uuid.New()
|
||||
sessionId := "session-id" + add
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
csrfToken := "my-verifying-token" + add
|
||||
email := add + "mail@mail.de"
|
||||
|
||||
@@ -193,7 +194,7 @@ func createValidUserSession(t *testing.T, db *sqlx.DB, add string) (uuid.UUID, s
|
||||
|
||||
_, err = db.ExecContext(context.Background(), `
|
||||
INSERT INTO token (token, user_id, session_id, type, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, datetime(), datetime("now", "+1 day"))`, csrfToken, userId, sessionId, types.TokenTypeCsrf)
|
||||
VALUES (?, ?, ?, ?, datetime(), datetime("now", "+1 day"))`, csrfToken, userId, sessionId, auth_types.TokenTypeCsrf)
|
||||
require.NoError(t, err)
|
||||
|
||||
return userId, csrfToken, sessionId
|
||||
|
||||
@@ -3,8 +3,8 @@ package test_test
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"spend-sparrow/internal/service"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/auth_types"
|
||||
"spend-sparrow/internal/authentication"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -110,7 +110,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
|
||||
userId := uuid.New()
|
||||
sessionId := "session-id"
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
@@ -136,7 +136,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
db, basePath, ctx := setupIntegrationTest(t)
|
||||
|
||||
userId := uuid.New()
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
@@ -163,7 +163,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
db, basePath, ctx := setupIntegrationTest(t)
|
||||
|
||||
userId := uuid.New()
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
@@ -206,7 +206,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
db, basePath, ctx := setupIntegrationTest(t)
|
||||
|
||||
userId := uuid.New()
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
@@ -247,7 +247,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
|
||||
db, basePath, ctx := setupIntegrationTest(t)
|
||||
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", FALSE, FALSE, ?, ?, datetime())`, uuid.New(), pass, []byte("salt"))
|
||||
@@ -295,7 +295,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
|
||||
db, basePath, ctx := setupIntegrationTest(t)
|
||||
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", FALSE, FALSE, ?, ?, datetime())`, uuid.New(), pass, []byte("salt"))
|
||||
@@ -414,7 +414,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
|
||||
db, basePath, ctx := setupIntegrationTest(t)
|
||||
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", FALSE, FALSE, ?, ?, datetime())`, uuid.New(), pass, []byte("salt"))
|
||||
@@ -467,7 +467,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
|
||||
userId := uuid.New()
|
||||
sessionId := "session-id"
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
@@ -550,7 +550,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", TRUE, FALSE, ?, ?, datetime())`, uuid.New(), service.GetHashPassword("password", []byte("salt")), []byte("salt"))
|
||||
VALUES (?, "mail@mail.de", TRUE, FALSE, ?, ?, datetime())`, uuid.New(), authentication.GetHashPassword("password", []byte("salt")), []byte("salt"))
|
||||
require.NoError(t, err)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, basePath+"/auth/signup", nil)
|
||||
@@ -631,7 +631,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, rows)
|
||||
var token string
|
||||
err = db.QueryRowContext(ctx, "SELECT t.token FROM token t INNER JOIN user u ON u.user_id = t.user_id WHERE u.email = ? AND t.type = ?", "mail@mail.de", types.TokenTypeEmailVerify).Scan(&token)
|
||||
err = db.QueryRowContext(ctx, "SELECT t.token FROM token t INNER JOIN user u ON u.user_id = t.user_id WHERE u.email = ? AND t.type = ?", "mail@mail.de", auth_types.TokenTypeEmailVerify).Scan(&token)
|
||||
require.NoError(t, err)
|
||||
assert.NotEmpty(t, token)
|
||||
})
|
||||
@@ -676,7 +676,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
_, err = db.ExecContext(ctx, `
|
||||
INSERT INTO token (token, user_id, type, created_at, expires_at)
|
||||
VALUES (?, ?, ?, datetime("now", "-16 minute"), datetime("now", "-1 minute"))`, token, userId, types.TokenTypeEmailVerify)
|
||||
VALUES (?, ?, ?, datetime("now", "-16 minute"), datetime("now", "-1 minute"))`, token, userId, auth_types.TokenTypeEmailVerify)
|
||||
require.NoError(t, err)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, basePath+"/auth/verify-email?token="+token, nil)
|
||||
@@ -706,7 +706,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
_, err = db.ExecContext(ctx, `
|
||||
INSERT INTO token (token, user_id, session_id, type, created_at, expires_at)
|
||||
VALUES (?, ?, "", ?, datetime("now"), datetime("now", "+15 minute"))`, token, userId, types.TokenTypeEmailVerify)
|
||||
VALUES (?, ?, "", ?, datetime("now"), datetime("now", "+15 minute"))`, token, userId, auth_types.TokenTypeEmailVerify)
|
||||
require.NoError(t, err)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, basePath+"/auth/verify-email?token="+token, nil)
|
||||
@@ -746,7 +746,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
userId := uuid.New()
|
||||
sessionId := "session-id"
|
||||
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", FALSE, FALSE, ?, ?, datetime())`, userId, pass, []byte("salt"))
|
||||
@@ -765,7 +765,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var csrfToken string
|
||||
err = db.QueryRowContext(ctx, "SELECT token FROM token WHERE user_id = ? AND type = ?", userId, types.TokenTypeCsrf).Scan(&csrfToken)
|
||||
err = db.QueryRowContext(ctx, "SELECT token FROM token WHERE user_id = ? AND type = ?", userId, auth_types.TokenTypeCsrf).Scan(&csrfToken)
|
||||
require.NoError(t, err)
|
||||
|
||||
req, err = http.NewRequestWithContext(ctx, http.MethodPost, basePath+"/api/auth/signout", nil)
|
||||
@@ -824,7 +824,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
db, basePath, ctx := setupIntegrationTest(t)
|
||||
userId := uuid.New()
|
||||
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", FALSE, FALSE, ?, ?, datetime())`, userId, pass, []byte("salt"))
|
||||
@@ -870,7 +870,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
db, basePath, ctx := setupIntegrationTest(t)
|
||||
userId := uuid.New()
|
||||
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", FALSE, FALSE, ?, ?, datetime())`, userId, pass, []byte("salt"))
|
||||
@@ -1039,7 +1039,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
db, basePath, ctx := setupIntegrationTest(t)
|
||||
userId := uuid.New()
|
||||
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", FALSE, FALSE, ?, ?, datetime())`, userId, pass, []byte("salt"))
|
||||
@@ -1078,7 +1078,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
|
||||
db, basePath, ctx := setupIntegrationTest(t)
|
||||
userId := uuid.New()
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
@@ -1128,7 +1128,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
|
||||
db, basePath, ctx := setupIntegrationTest(t)
|
||||
userId := uuid.New()
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
@@ -1180,7 +1180,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
userId := uuid.New()
|
||||
userIdOther := uuid.New()
|
||||
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", FALSE, FALSE, ?, ?, datetime())`, userId, pass, []byte("salt"))
|
||||
@@ -1230,7 +1230,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
pass = service.GetHashPassword("MyNewSecurePassword1!", []byte("salt"))
|
||||
pass = authentication.GetHashPassword("MyNewSecurePassword1!", []byte("salt"))
|
||||
var rows int
|
||||
err = db.QueryRowContext(ctx, "SELECT COUNT(*) FROM user WHERE user_id = ? AND password = ?", userId, pass).Scan(&rows)
|
||||
require.NoError(t, err)
|
||||
@@ -1259,7 +1259,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
d, basePath, ctx := setupIntegrationTest(t)
|
||||
userId := uuid.New()
|
||||
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
_, err := d.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", FALSE, FALSE, ?, ?, datetime())`, userId, pass, []byte("salt"))
|
||||
@@ -1287,7 +1287,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
d, basePath, ctx := setupIntegrationTest(t)
|
||||
userId := uuid.New()
|
||||
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
_, err := d.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", FALSE, FALSE, ?, ?, datetime())`, userId, pass, []byte("salt"))
|
||||
@@ -1317,7 +1317,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
|
||||
|
||||
var rows int
|
||||
err = d.QueryRowContext(ctx, "SELECT COUNT(*) FROM token WHERE user_id = ? AND type = ?", userId, types.TokenTypePasswordReset).Scan(&rows)
|
||||
err = d.QueryRowContext(ctx, "SELECT COUNT(*) FROM token WHERE user_id = ? AND type = ?", userId, auth_types.TokenTypePasswordReset).Scan(&rows)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, rows)
|
||||
})
|
||||
@@ -1362,7 +1362,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
db, basePath, ctx := setupIntegrationTest(t)
|
||||
|
||||
userId := uuid.New()
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", TRUE, FALSE, ?, ?, datetime())`, userId, pass, []byte("salt"))
|
||||
@@ -1399,7 +1399,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
assert.Contains(t, resp.Header.Get("Hx-Trigger"), msg)
|
||||
|
||||
var rows int
|
||||
err = db.QueryRowContext(ctx, "SELECT COUNT(*) FROM token WHERE user_id = ? AND type = ?", userId, types.TokenTypePasswordReset).Scan(&rows)
|
||||
err = db.QueryRowContext(ctx, "SELECT COUNT(*) FROM token WHERE user_id = ? AND type = ?", userId, auth_types.TokenTypePasswordReset).Scan(&rows)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, rows)
|
||||
})
|
||||
@@ -1412,7 +1412,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
d, basePath, ctx := setupIntegrationTest(t)
|
||||
userId := uuid.New()
|
||||
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
_, err := d.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", FALSE, FALSE, ?, ?, datetime())`, userId, pass, []byte("salt"))
|
||||
@@ -1455,7 +1455,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
d, basePath, ctx := setupIntegrationTest(t)
|
||||
userId := uuid.New()
|
||||
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
_, err := d.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", FALSE, FALSE, ?, ?, datetime())`, userId, pass, []byte("salt"))
|
||||
@@ -1475,7 +1475,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
token := "password-reset-token"
|
||||
_, err = d.ExecContext(ctx, `
|
||||
INSERT INTO token (token, user_id, session_id, type, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, datetime("now", "-16 minute"), datetime("now", "-1 minute"))`, token, userId, "", types.TokenTypePasswordReset)
|
||||
VALUES (?, ?, ?, ?, datetime("now", "-16 minute"), datetime("now", "-1 minute"))`, token, userId, "", auth_types.TokenTypePasswordReset)
|
||||
require.NoError(t, err)
|
||||
|
||||
formData := url.Values{
|
||||
@@ -1504,7 +1504,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
d, basePath, ctx := setupIntegrationTest(t)
|
||||
userId := uuid.New()
|
||||
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
_, err := d.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", FALSE, FALSE, ?, ?, datetime())`, userId, pass, []byte("salt"))
|
||||
@@ -1524,7 +1524,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
token := "password-reset-token"
|
||||
_, err = d.ExecContext(ctx, `
|
||||
INSERT INTO token (token, user_id, session_id, type, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, datetime("now"), datetime("now", "+15 minute"))`, token, userId, "", types.TokenTypePasswordReset)
|
||||
VALUES (?, ?, ?, ?, datetime("now"), datetime("now", "+15 minute"))`, token, userId, "", auth_types.TokenTypePasswordReset)
|
||||
require.NoError(t, err)
|
||||
|
||||
formData := url.Values{
|
||||
@@ -1553,7 +1553,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
d, basePath, ctx := setupIntegrationTest(t)
|
||||
userId := uuid.New()
|
||||
|
||||
pass := service.GetHashPassword("password", []byte("salt"))
|
||||
pass := authentication.GetHashPassword("password", []byte("salt"))
|
||||
_, err := d.ExecContext(ctx, `
|
||||
INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at)
|
||||
VALUES (?, "mail@mail.de", FALSE, FALSE, ?, ?, datetime())`, userId, pass, []byte("salt"))
|
||||
@@ -1590,7 +1590,7 @@ func TestIntegrationAuth(t *testing.T) {
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var token string
|
||||
err = d.QueryRowContext(ctx, "SELECT token FROM token WHERE type = ?", types.TokenTypePasswordReset).Scan(&token)
|
||||
err = d.QueryRowContext(ctx, "SELECT token FROM token WHERE type = ?", auth_types.TokenTypePasswordReset).Scan(&token)
|
||||
require.NoError(t, err)
|
||||
|
||||
formData = url.Values{
|
||||
|
||||
Reference in New Issue
Block a user