93 Commits

Author SHA1 Message Date
Cedric 4ce31a7774 Merge pull request 'Release 1.2.1' (#19) from dev into main
Reviewed-on: #19
2026-07-08 11:23:25 +02:00
Cedric b8938d521f Version 1.2.1
Build and Deploy Spring Boot Server / build (push) Successful in 1m14s
2026-07-08 10:38:09 +02:00
Cedric 4b6198ab5c Merge feature/split-modes: persist split modes + default-split endpoint
Build and Deploy Spring Boot Server / build (push) Successful in 1m17s
2026-07-08 09:18:48 +02:00
Cedric 9eb9483162 fix: validate splitPercentage bounds and cover default-split auth 2026-07-08 09:15:23 +02:00
Cedric 693289525e feat: add PUT /{id}/default-split endpoint 2026-07-07 22:03:24 +02:00
Cedric a3d66129ac feat: record split mode/percentage changes in history diff 2026-07-07 21:59:30 +02:00
Cedric da0cf48dc3 feat: persist splitMode/splitPercentage and list defaultSplitPercentage
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 21:55:55 +02:00
Cedric 9a109b4709 Merge pull request 'Dev' (#18) from dev into main
Build and Deploy Versioned Spring Boot Server / build (push) Successful in 1m25s
Reviewed-on: #18
2026-07-07 00:35:22 +02:00
Cedric 7fd7882188 version upgrade
Build and Deploy Spring Boot Server / build (push) Successful in 1m9s
2026-07-07 00:29:19 +02:00
Cedric af648bca70 feat: add GET /history/recent endpoint for cross-list activity
Build and Deploy Spring Boot Server / build (push) Successful in 1m30s
2026-07-06 19:04:40 +02:00
Cedric b7e0fa1c8b feat: add cross-list recent history query and service method 2026-07-06 18:59:32 +02:00
Cedric b58008c8bc fix: allow editing quick-add stub expenses (amount 0, no category)
Build and Deploy Spring Boot Server / build (push) Successful in 3m36s
Quick Add deliberately creates stub expenses with amount 0 and no
category (ExpenseInput allows both), but ExpenseChangeRequest required
amount >= 0.01 and a non-blank category, so every edit of a stub that
did not simultaneously fill in both fields was rejected with 400.
Update validation now accepts the same states create can produce, and
a blank category is normalized to null.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 18:52:42 +02:00
Cedric ac0118d435 fix: delete history entries when their expense list is deleted
Build and Deploy Spring Boot Server / build (push) Successful in 2m31s
2026-07-06 13:20:10 +02:00
Cedric 765c5d5b32 feat: idempotent startup backfill for lastModified and history 2026-07-06 12:50:33 +02:00
Cedric b8ca1b94ec feat: paged history endpoint GET /api/expenselist/{id}/history 2026-07-06 12:46:46 +02:00
Cedric b19cdd0264 feat: record history and lastModified on expense mutations 2026-07-06 12:40:32 +02:00
Cedric 27f747b44d fix: migrate HistoryService to Jackson 3 (Spring Boot 4) 2026-07-06 12:35:39 +02:00
Cedric 8f42add0c2 feat: HistoryService with field-level diff logic 2026-07-06 12:27:55 +02:00
Cedric 9d1cf862c7 feat: history entity, repository and Expense.lastModified 2026-07-06 12:21:05 +02:00
Cedric 003cf7e2da Merge pull request 'Fix Tag Workflow' (#17) from dev into main
Build and Deploy Versioned Spring Boot Server / build (push) Successful in 1m16s
Reviewed-on: #17
2026-07-05 00:08:49 +02:00
Cedric 6203a83af3 Fix Tag Workflow
Build and Deploy Spring Boot Server / build (push) Successful in 1m19s
2026-07-05 00:08:18 +02:00
Cedric c1c530c46b Merge pull request 'Release 1.1.0' (#16) from dev into main
Reviewed-on: #16
2026-07-05 00:03:46 +02:00
Cedric 41e32efd7e Added Rename User and Lists
Build and Deploy Spring Boot Server / build (push) Successful in 1m18s
2026-07-04 22:50:54 +02:00
Cedric d73d349a58 Release 1.1.0 Final Security Hardening
Build and Deploy Spring Boot Server / build (push) Successful in 1m11s
2026-07-04 22:14:58 +02:00
Cedric f958fb7853 Fixed Auth and Connection issues
Build and Deploy Spring Boot Server / build (push) Successful in 3m41s
2026-07-04 17:31:21 +02:00
Cedric 7ad72119a8 fix secrets no longer needed
Build and Deploy Spring Boot Server / build (push) Successful in 1m13s
2026-05-14 23:46:40 +02:00
Cedric f7f2bf5768 ci: switch to compose.deploy to force fresh image pull
Build and Deploy Spring Boot Server / build (push) Successful in 1m12s
2026-05-12 23:57:45 +02:00
Cedric 28df2a66ca fix: always pull latest image on redeploy
Build and Deploy Spring Boot Server / build (push) Successful in 1m21s
2026-05-12 23:25:07 +02:00
Cedric 29f26a8a18 feat: add /api/version endpoint returning build time and version
Build and Deploy Spring Boot Server / build (push) Successful in 1m25s
2026-05-12 23:08:37 +02:00
Cedric a3fa59f347 ci: test full pipeline end-to-end
Build and Deploy Spring Boot Server / build (push) Successful in 1m12s
2026-05-12 20:34:42 +02:00
Cedric 2880934644 ci: test full pipeline end-to-end
Build and Deploy Spring Boot Server / build (push) Successful in 1m10s
2026-05-10 23:43:13 +02:00
Cedric b42980200d ci: trigger Dokploy redeploy via API after image push
Build and Deploy Spring Boot Server / build (push) Failing after 1m48s
2026-05-10 23:38:07 +02:00
Cedric 8381cdbffa ci: test full pipeline
Build and Deploy Spring Boot Server / build (push) Successful in 1m20s
2026-05-10 22:59:53 +02:00
Cedric 5cab2fed3b ci: test Dokploy webhook
Build and Deploy Spring Boot Server / build (push) Successful in 1m13s
2026-05-10 22:36:44 +02:00
Cedric 417eef7042 ci: fix Dokploy webhook, token is in URL not Authorization header
Build and Deploy Spring Boot Server / build (push) Failing after 1m11s
2026-05-10 22:29:40 +02:00
Cedric ed5543ce61 ci: fix Java 21 in dockerfile, add Docker Hub login to avoid rate limits
Build and Deploy Spring Boot Server / build (push) Failing after 1m23s
2026-05-10 22:22:06 +02:00
Cedric 40b8f45de8 ci: test with Java 21 runner image
Build and Deploy Spring Boot Server / build (push) Failing after 1m2s
2026-05-10 22:15:16 +02:00
Cedric b221d07b48 ci: use ubuntu-java17 runner image, remove setup-java step
Build and Deploy Spring Boot Server / build (push) Failing after 2m22s
2026-05-10 22:08:23 +02:00
Cedric 0e63b6e4e6 ci: fix mvnw executable permission
Build and Deploy Spring Boot Server / build (push) Has been cancelled
2026-05-10 22:07:30 +02:00
Cedric 4a04c85fe8 ci: use Maven wrapper instead of mvn to fix command not found on Gitea runner
Build and Deploy Spring Boot Server / build (push) Failing after 4m43s
2026-05-10 21:40:25 +02:00
Cedric b8e2c9114d chore: merge main into dev, keep clean docker-compose from main
Build and Deploy Spring Boot Server / build (push) Failing after 9m2s
2026-05-10 21:29:11 +02:00
Cedric 0876eecf50 ci: improve dev pipeline with Dokploy webhook and Docker layer caching 2026-05-10 21:27:28 +02:00
Cedric 5549691d50 ci: test pipeline 2026-05-10 21:24:18 +02:00
Cedric 46c8df45d6 ci: test pipeline 2026-05-10 21:24:10 +02:00
Cedric 50d274f36a chore: resolve merge conflicts, keep Spring Boot 4.0.6 version
Kept our version over remote (security hardening PR #12) for all conflicts:
- pom.xml: Spring Boot 4.0.6 vs 3.4.1, new test deps
- SecurityConfig: new csrf/package API for SB4
- GlobalExceptionHandler: full handler set with SLF4J logging
- AppUserController/ExpenseListController: clean delegation to GlobalExceptionHandler
- Test files: SB4 package paths, extra test coverage

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 20:29:49 +02:00
Cedric ba4f365f06 chore: merge feature/security-hardening into main
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 20:25:12 +02:00
Cedric a5e5824a44 docs: write recent changes section 2026-05-10 20:18:58 +02:00
Cedric 7189e4fb08 docs: write error handling section 2026-05-10 20:18:28 +02:00
Cedric 2782823c3d docs: write data models section 2026-05-10 20:17:55 +02:00
Cedric ddf64305a5 docs: write expense lists endpoint section 2026-05-10 20:17:22 +02:00
Cedric 2b84ed0de8 docs: write home and users endpoint sections 2026-05-10 20:14:22 +02:00
Cedric 18e740bb73 docs: write rate limiting section 2026-05-10 20:13:58 +02:00
Cedric 9b93cd97a6 docs: write authentication section 2026-05-09 23:56:14 +02:00
Cedric 8fb1820bc7 docs: write API overview section 2026-05-09 23:50:42 +02:00
Cedric 9c35bb8435 docs: scaffold API.md with section headings 2026-05-09 23:49:56 +02:00
Cedric 3d456f2f81 Bugfixes 2026-05-09 23:04:27 +02:00
Cedric b1324e3048 test: add jsonPath field assertions to create validation tests 2026-05-06 14:40:11 +02:00
Cedric 8b96433b1a feat: add CreateExpenseListRequest DTO with validation to POST /create endpoint
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 17:28:47 +02:00
Cedric 19c7e1915f security hardening (#12)
Reviewed-on: #12
Co-authored-by: Cedric Hornberger <ceddi.hornberger@gmx.de>
Co-committed-by: Cedric Hornberger <ceddi.hornberger@gmx.de>
2026-05-05 17:13:53 +02:00
Cedric f0de751da4 fix: centralise error handling in GlobalExceptionHandler, add SLF4J logging, remove HTTP 417 and e.printStackTrace()
- Expand GlobalExceptionHandler with handlers for ResourceNotFoundException (404),
  UsernameAlreadyExistsException (409), ResponseStatusException (pass-through),
  RuntimeException (500), and generic Exception (500); add SLF4J logging
- Remove all bare try/catch blocks and e.printStackTrace() calls from
  ExpenseListController; add SLF4J logger field
- Add test: create_returns500_onUnexpectedServiceError

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 17:11:37 +02:00
Cedric 9b95741292 fix: add /docs/superpowers to .gitignore 2026-05-05 17:00:01 +02:00
Cedric 2bd229cc5e Remove docs from tracking 2026-05-05 16:59:35 +02:00
Cedric 797d482ebf fix: use ResourceNotFoundException for not-found cases in updateExpense, IllegalArgumentException for ownership mismatch in deleteCustomCategory 2026-05-05 16:55:01 +02:00
Cedric 906b60d264 fix: single-param JPQL queries, ResourceNotFoundException throughout ExpenseListService, remove addExpenseToList loop
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 16:40:31 +02:00
Cedric 68783cc892 fix: throw ResourceNotFoundException instead of returning null, replace full-table-scan list queries with JPQL 2026-05-05 15:20:46 +02:00
Cedric 9c91da9f30 test: fix ExpenseListRepositoryTest with H2 and proper save-then-find pattern
Added H2 as a test-scoped dependency so @DataJpaTest has an embedded
database. Rewrote the test to save an entity and assert on the returned
ID rather than assuming a record exists at ID=1.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 11:23:51 +02:00
Cedric 024b3880e7 security: add per-user/IP rate limiting via Bucket4j
RateLimitFilter (OncePerRequestFilter) enforces 60 req/min per
authenticated Google ID or client IP, using Bucket4j in-memory
token buckets. Filter is registered after BearerTokenAuthenticationFilter
in the production security chain. Added 4 unit tests covering
allow, block, per-IP isolation, and X-Forwarded-For preference.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 11:19:42 +02:00
Cedric 457efab452 security: enforce JWT-based authorization on AppUserController
Added AuthenticatedUserResolver injection and assertSelf guard to
getUser, getUserByGoogleId, and deleteUser endpoints. createUser
remains open for registration. Added 7 controller tests covering
validation failures and 403 enforcement.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 11:13:05 +02:00
Cedric 95688e5111 test: add unit tests for AuthenticatedUserResolver 2026-05-05 10:03:35 +02:00
Cedric bb2a4d70b2 feat: add ExpenseListController validation and authorization tests 2026-05-04 22:46:29 +02:00
Cedric a948bca2fc feat: add GlobalExceptionHandler, @Valid to user creation, AuthenticatedUserResolver stub, and rewrite ExpenseListController with authorization 2026-05-04 22:44:37 +02:00
Cedric 3bea06fead feat: add Bean Validation annotations to request models 2026-05-04 22:36:20 +02:00
Cedric b7db35defe build: add spring-boot-starter-validation and bucket4j-core 2026-05-04 22:34:10 +02:00
Cedric efe84942ff docs: add security hardening implementation plan
8-task TDD plan covering input validation, JWT-based authorization
enforcement, and Bucket4j rate limiting.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-04 22:22:54 +02:00
Cedric e3b8917bfc docs: add security hardening design spec
Covers input validation, JWT-based authorization enforcement, and
per-user rate limiting via Bucket4j.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-04 21:58:20 +02:00
Cedric 229a6a8a43 docker-compose.yml aktualisiert 2026-03-04 15:16:11 +01:00
Cedric 76e878ff5c docker-compose.yml aktualisiert 2026-02-04 20:25:38 +01:00
Cedric 477a5c3c70 dockerfile aktualisiert 2026-02-04 15:31:16 +01:00
Cedric 7bac694357 docker-compose.yml aktualisiert 2026-02-04 15:29:55 +01:00
Cedric f8407db3ac docker-compose.yml aktualisiert 2026-02-04 15:27:51 +01:00
Cedric 374d91f0c9 dockerfile aktualisiert 2026-02-04 15:18:40 +01:00
Cedric 8f17e8d8a8 dockerfile aktualisiert 2026-02-04 15:15:53 +01:00
Cedric 8c8eccb35e dockerfile aktualisiert 2026-02-04 15:13:23 +01:00
Cedric 3656ccc941 dockerfile aktualisiert 2026-02-04 15:07:41 +01:00
Cedric e9851ffea4 dockerfile update 2026-02-04 15:05:44 +01:00
Cedric 38b5e0f740 Merge pull request 'Vps update' (#11) from Vps-new-infrastructure into main
Reviewed-on: #11
2026-02-04 14:56:13 +01:00
Cedric 2ba7f8d5da Vps update 2026-02-04 14:55:25 +01:00
Cedric 726be3f613 bu commit
Build and Deploy Spring Boot Server / build (push) Successful in 10m16s
2025-07-11 14:16:05 +02:00
Cedric 936140e76f dockerCompose backup
Build and Deploy Spring Boot Server / build (push) Successful in 10m4s
2025-05-11 10:15:15 +02:00
Cedric b46464cd32 Merge pull request 'dev' (#8) from dev into main
Build and Deploy Versioned Spring Boot Server / build (push) Successful in 10m4s
Reviewed-on: #8
2025-05-10 16:13:59 -07:00
Cedric 15792bad28 Add CategoryService and integrate category handling in ExpenseListController
Build and Deploy Spring Boot Server / build (push) Successful in 10m8s
- Introduced CategoryService to manage standard categories.
- Updated ExpenseListController to set default categories when creating an expense list.
- Modified ExpenseChangeRequest and ExpenseInput to include category field.
- Enhanced DataInitializer to ensure standard categories are initialized.
2025-05-11 00:59:54 +02:00
Cedric 814b2221c8 #7
Build and Deploy Spring Boot Server / build (push) Successful in 10m8s
2025-05-10 19:07:50 +02:00
Cedric 011bb03d3f Merge pull request 'sync' (#3) from main into dev
Build and Deploy Spring Boot Server / build (push) Successful in 9m53s
Reviewed-on: #3
2025-01-12 05:19:50 -08:00
70 changed files with 4072 additions and 561 deletions
+8
View File
@@ -0,0 +1,8 @@
{
"permissions": {
"allow": [
"Bash(git add *)",
"Bash(git commit *)"
]
}
}
+37 -34
View File
@@ -7,48 +7,51 @@ on:
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-java17
steps: steps:
# 1. Checkout the code # 1. Checkout the code
- name: Checkout code - name: Checkout code
uses: actions/checkout@v2 uses: actions/checkout@v4
# 2. Set up Java and Maven # 2. Build the Spring Boot application using the Maven wrapper (Java 17 pre-installed in runner image)
- name: Set up JDK (Eclipse Temurin)
uses: actions/setup-java@v3
with:
distribution: "temurin"
java-version: "17"
cache: maven
# 3. Verify Maven installation
- name: Install Maven
run: |
sudo apt-get update
sudo apt-get install -y maven
mvn -version
# 4. Build the Spring Boot application
- name: Build Spring Boot Application - name: Build Spring Boot Application
run: | run: ./mvnw clean package -DskipTests
mvn clean package -DskipTests
# 5. Set up Docker # 4. Set up Docker Buildx (enables layer caching)
- name: Set up Docker - name: Set up Docker Buildx
run: | uses: docker/setup-buildx-action@v3
docker --version
# 6. Build the Docker image # 5. Login to Docker Hub to avoid pull rate limits
- name: Build and Package Docker Image - name: Login to Docker Hub
run: | uses: docker/login-action@v3
docker build -t tea.zendric.de/cedric/xpensely-server:latest . with:
username: ${{ secrets.DOCKERHUB_USER }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
# 7. Docker login # 6. Docker login to Gitea registry
- name: Login to Docker Registry - name: Login to Docker Registry
uses: docker/login-action@v3
with:
registry: tea.zendric.de
username: ${{ secrets.TEAUSER }}
password: ${{ secrets.TEAPASSWORD }}
# 7. Build and push Docker image with layer caching
- name: Build and Push Docker Image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: tea.zendric.de/cedric/xpensely-server:latest
cache-from: type=registry,ref=tea.zendric.de/cedric/xpensely-server:buildcache
cache-to: type=registry,ref=tea.zendric.de/cedric/xpensely-server:buildcache,mode=max
# 8. Trigger Dokploy to redeploy the dev server automatically via API
- name: Trigger Dokploy Redeploy
run: | run: |
echo "${{ secrets.TEAPASSWORD }}" | docker login tea.zendric.de -u ${{ secrets.TEAUSER }} --password-stdin curl -X POST "https://dokploy.zendric.de/api/compose.deploy" \
# 8. Push Docker image -H "Content-Type: application/json" \
- name: Push the Docker Image to registry -H "x-api-key: ${{ secrets.DOKPLOY_API_TOKEN }}" \
run: | -d "{\"composeId\": \"${{ secrets.DOKPLOY_COMPOSE_ID }}\"}" \
docker push tea.zendric.de/cedric/xpensely-server:latest --fail
+45 -58
View File
@@ -7,78 +7,65 @@ on:
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-java17
steps: steps:
# 1. Checkout the code # 1. Checkout the code
- name: Checkout code - name: Checkout code
uses: actions/checkout@v2 uses: actions/checkout@v4
# 2. Set up Java and Maven # 2. Build the Spring Boot application using the Maven wrapper
- name: Set up JDK (Eclipse Temurin) # (Java 17 is pre-installed in the runner image)
uses: actions/setup-java@v3
with:
distribution: "temurin"
java-version: "17"
cache: maven
# 3. Verify Maven installation
- name: Install Maven
run: |
sudo apt-get update
sudo apt-get install -y maven
mvn -version
# 4. Build the Spring Boot application
- name: Build Spring Boot Application - name: Build Spring Boot Application
run: | run: ./mvnw clean package -DskipTests
mvn clean package -DskipTests
# 5. Set up Docker # 3. Derive version tags from the pushed git tag
- name: Set up Docker # e.g. 1.1.0 -> tag_version=1.1.0, minor=1.1, major=1
- name: Extract version tags
id: ver
run: | run: |
docker --version TAG_VERSION="${{ github.ref_name }}"
# 6. Extract the tag name
- name: Extract Tag Version
id: extract_version
run: |
TAG_VERSION=$(echo "${GITHUB_REF}" | sed 's#refs/tags/##')
if [ -z "$TAG_VERSION" ]; then if [ -z "$TAG_VERSION" ]; then
echo "Error: TAG_VERSION is empty." echo "Error: TAG_VERSION is empty."
exit 1 exit 1
fi fi
echo "TAG_VERSION=$TAG_VERSION" >> $GITHUB_ENV MINOR_VERSION=$(echo "$TAG_VERSION" | cut -d. -f1,2)
MAJOR_VERSION=$(echo "$TAG_VERSION" | cut -d. -f1)
echo "tag_version=$TAG_VERSION" >> "$GITHUB_OUTPUT"
echo "minor=$MINOR_VERSION" >> "$GITHUB_OUTPUT"
echo "major=$MAJOR_VERSION" >> "$GITHUB_OUTPUT"
# Extract major and minor versions # 4. Set up Docker Buildx (enables layer caching)
MAJOR_VERSION=$(echo "${TAG_VERSION}" | cut -d. -f1) - name: Set up Docker Buildx
MINOR_VERSION=$(echo "${TAG_VERSION}" | cut -d. -f1,2) uses: docker/setup-buildx-action@v3
echo "MAJOR_VERSION=$MAJOR_VERSION" >> $GITHUB_ENV
echo "MINOR_VERSION=$MINOR_VERSION" >> $GITHUB_ENV
# 7. Build the Docker image with the tag # 5. Login to Docker Hub to avoid base-image pull rate limits
- name: Build and Package Docker Image - name: Login to Docker Hub
run: | uses: docker/login-action@v3
docker build -t tea.zendric.de/cedric/xpensely-server:${{ env.TAG_VERSION }} . with:
username: ${{ secrets.DOCKERHUB_USER }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
# 8. Tag the image with Major Version (e.g., 0) # 6. Login to the Gitea registry
- name: Tag with Major Version
run: |
docker tag tea.zendric.de/cedric/xpensely-server:${{ env.TAG_VERSION }} tea.zendric.de/cedric/xpensely-server:${{ env.MAJOR_VERSION }}
# 9. Tag the image with Minor Version (e.g., 0.1)
- name: Tag with Minor Version
run: |
docker tag tea.zendric.de/cedric/xpensely-server:${{ env.TAG_VERSION }} tea.zendric.de/cedric/xpensely-server:${{ env.MINOR_VERSION }}
# 10. Docker login
- name: Login to Docker Registry - name: Login to Docker Registry
run: | uses: docker/login-action@v3
echo "${{ secrets.TEAPASSWORD }}" | docker login tea.zendric.de -u ${{ secrets.TEAUSER }} --password-stdin with:
registry: tea.zendric.de
username: ${{ secrets.TEAUSER }}
password: ${{ secrets.TEAPASSWORD }}
# 11. Push the Docker images with the tags # 7. Build and push the versioned Docker images with layer caching.
- name: Push the Docker Image to registry # Pushes exact, minor, and major tags. The prod compose references
run: | # the major tag (":1"), so pushing here makes the new build available
docker push tea.zendric.de/cedric/xpensely-server:${{ env.TAG_VERSION }} # to pull in Dockge — deploy is triggered MANUALLY after the DB migration.
docker push tea.zendric.de/cedric/xpensely-server:${{ env.MAJOR_VERSION }} - name: Build and Push Docker Image
docker push tea.zendric.de/cedric/xpensely-server:${{ env.MINOR_VERSION }} uses: docker/build-push-action@v5
with:
context: .
push: true
tags: |
tea.zendric.de/cedric/xpensely-server:${{ steps.ver.outputs.tag_version }}
tea.zendric.de/cedric/xpensely-server:${{ steps.ver.outputs.minor }}
tea.zendric.de/cedric/xpensely-server:${{ steps.ver.outputs.major }}
cache-from: type=registry,ref=tea.zendric.de/cedric/xpensely-server:buildcache
cache-to: type=registry,ref=tea.zendric.de/cedric/xpensely-server:buildcache,mode=max
+6
View File
@@ -1,10 +1,16 @@
HELP.md HELP.md
target/ target/
/docs/superpowers
!.mvn/wrapper/maven-wrapper.jar !.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/ !**/src/main/**/target/
!**/src/test/**/target/ !**/src/test/**/target/
.env .env
# Local debugging (not for CI/prod)
.env.local
Dockerfile.local
compose.local.yml
### STS ### ### STS ###
.apt_generated .apt_generated
.classpath .classpath
+7
View File
@@ -0,0 +1,7 @@
Run it locally:
1. build the current state:
mvn clean install or mvn clean install -DskipTests
2. docker it up and run it
docker-compose -f dev-docker-compose.yml up --build
+85 -1
View File
@@ -1,6 +1,6 @@
<mxfile host="65bd71144e"> <mxfile host="65bd71144e">
<diagram id="TZX9Tq6sZIlTxQ58HocZ" name="Page-1"> <diagram id="TZX9Tq6sZIlTxQ58HocZ" name="Page-1">
<mxGraphModel dx="826" dy="472" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0"> <mxGraphModel dx="989" dy="570" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">
<root> <root>
<mxCell id="0"/> <mxCell id="0"/>
<mxCell id="1" parent="0"/> <mxCell id="1" parent="0"/>
@@ -193,6 +193,90 @@
<mxCell id="73" value="&lt;span style=&quot;font-size: 8px;&quot;&gt;24.12.24 ; Expense ; 24,12 €&lt;/span&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#76608a;fontColor=#ffffff;strokeColor=#432D57;" parent="1" vertex="1"> <mxCell id="73" value="&lt;span style=&quot;font-size: 8px;&quot;&gt;24.12.24 ; Expense ; 24,12 €&lt;/span&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#76608a;fontColor=#ffffff;strokeColor=#432D57;" parent="1" vertex="1">
<mxGeometry x="1399" y="226" width="120" height="20" as="geometry"/> <mxGeometry x="1399" y="226" width="120" height="20" as="geometry"/>
</mxCell> </mxCell>
<mxCell id="86" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="74" target="79">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="74" value="List" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#60a917;fontColor=#ffffff;strokeColor=#2D7600;" vertex="1" parent="1">
<mxGeometry x="1880" y="160" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="75" value="DB-Structure for Categories" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
<mxGeometry x="1930" y="35" width="100" height="30" as="geometry"/>
</mxCell>
<mxCell id="78" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="76" target="77">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="76" value="List Entry" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="1920" y="220" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="79" value="Available Categories" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="2160" y="150" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="83" style="edgeStyle=none;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="81" target="79">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="81" value="Standard Categories" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="2060" y="35" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="84" style="edgeStyle=none;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="82" target="79">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="82" value="Custom Categories" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="2270" y="35" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="91" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="87" target="90">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="87" value="List Entry" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="1920" y="280" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="92" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="88" target="89">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="88" value="List Entry" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="1920" y="340" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="89" value="Category" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="2150" y="370" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="90" value="Category" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="2150" y="315" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="94" value="&lt;h1 style=&quot;font-size: 18px;&quot;&gt;- list id&lt;/h1&gt;&lt;div&gt;- List &amp;lt;String&amp;gt;&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;spacing=5;spacingTop=-20;whiteSpace=wrap;overflow=hidden;rounded=0;fontSize=18;" vertex="1" parent="1">
<mxGeometry x="2410" y="50" width="130" height="70" as="geometry"/>
</mxCell>
<mxCell id="77" value="Category" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="2150" y="260" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="97" value="" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="1730" y="510" width="200" height="320" as="geometry"/>
</mxCell>
<mxCell id="98" value="ExpenseList" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="1770" y="520" width="120" height="20" as="geometry"/>
</mxCell>
<mxCell id="100" value="+" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="1880" y="790" width="30" height="30" as="geometry"/>
</mxCell>
<mxCell id="101" value="Categorie" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
<mxGeometry x="1770" y="480" width="120" height="30" as="geometry"/>
</mxCell>
<mxCell id="102" value="&lt;span style=&quot;font-size: 8px;&quot;&gt;Amount : 24,12 €&lt;br&gt;Title: Expense&lt;br&gt;Date: 24.12.24&lt;br&gt;From: Jessi&lt;br&gt;Deviation: 0 €&lt;/span&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#76608a;fontColor=#ffffff;strokeColor=#432D57;align=left;spacingLeft=12;" vertex="1" parent="1">
<mxGeometry x="1745" y="550" width="170" height="170" as="geometry"/>
</mxCell>
<mxCell id="105" value="&lt;span style=&quot;font-size: 8px;&quot;&gt;Essen&lt;/span&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#1ba1e2;fontColor=#ffffff;strokeColor=#006EAF;align=left;spacingLeft=12;" vertex="1" parent="1">
<mxGeometry x="1760" y="680" width="40" height="10" as="geometry"/>
</mxCell>
<mxCell id="106" value="&lt;span style=&quot;font-size: 8px;&quot;&gt;Trinken&lt;/span&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#a20025;fontColor=#ffffff;strokeColor=#6F0000;align=left;spacingLeft=12;" vertex="1" parent="1">
<mxGeometry x="1800" y="680" width="40" height="10" as="geometry"/>
</mxCell>
<mxCell id="107" value="&lt;span style=&quot;font-size: 8px;&quot;&gt;Auto&lt;/span&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d80073;fontColor=#ffffff;strokeColor=#A50040;align=left;spacingLeft=12;" vertex="1" parent="1">
<mxGeometry x="1840" y="680" width="40" height="10" as="geometry"/>
</mxCell>
<mxCell id="111" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;fontSize=18;" edge="1" parent="1" source="108" target="74">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="108" value="Actor" style="shape=umlActor;verticalLabelPosition=bottom;verticalAlign=top;html=1;outlineConnect=0;fontSize=18;" vertex="1" parent="1">
<mxGeometry x="1715" y="150" width="30" height="60" as="geometry"/>
</mxCell>
</root> </root>
</mxGraphModel> </mxGraphModel>
</diagram> </diagram>
+21 -28
View File
@@ -1,48 +1,41 @@
version: "3.8"
services: services:
xpensely-server: xpensely-server:
image: tea.zendric.de/cedric/xpensely-server:0 image: tea.zendric.de/cedric/xpensely-server:latest
labels: pull_policy: always
net.unraid.docker.icon: https://tea.zendric.de/Cedric/XpenselyServer/raw/branch/main/src/main/resources/static/xpensely_icon_white.png restart: always
container_name: xpensely-server
ports:
- 3636:8080
environment: environment:
GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID}
GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET}
DB_PORT: 5432 DB_PORT: 5432
DB_P_NAME: xpensely DB_P_NAME: ${POSTGRES_DB}
DB_USERNAME: ${DB_USERNAME} DB_USERNAME: ${POSTGRES_USER}
DB_PASSWORD: ${DB_PASSWORD} DB_PASSWORD: ${POSTGRES_PASSWORD}
SPRING_PROFILES_ACTIVE: ${SPRING_PROFILES_ACTIVE}
depends_on: depends_on:
postgresdb: postgresdb:
condition: service_healthy condition: service_healthy
networks: networks:
- xpensely-network - xpensely-network
postgresdb: postgresdb:
labels:
net.unraid.docker.icon: https://raw.githubusercontent.com/docker-library/docs/01c12653951b2fe592c1f93a13b4e289ada0e3a1/postgres/logo.png
image: postgres:14 image: postgres:14
container_name: postgresdb restart: unless-stopped
ports:
- 5432:5432
environment: environment:
POSTGRES_DB: xpensely POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${DB_USERNAME} POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${DB_PASSWORD} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes:
- postgres_data:/var/lib/postgresql/data
networks: networks:
- xpensely-network - xpensely-network
volumes:
- db_data:/var/lib/postgresql/data
restart: unless-stopped
healthcheck: healthcheck:
test: test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
- CMD-SHELL
- pg_isready -U ${DB_USERNAME} -d xpensely
interval: 10s interval: 10s
timeout: 5s timeout: 5s
retries: 5 retries: 5
volumes: volumes:
db_data: null postgres_data:
networks: networks:
xpensely-network: null xpensely-network:
driver: bridge
+2 -2
View File
@@ -1,7 +1,7 @@
FROM openjdk:17-jdk-slim FROM eclipse-temurin:21-jdk
COPY ./target/*.jar app.jar COPY ./target/*.jar app.jar
EXPOSE 8080 EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"] ENTRYPOINT ["java","-jar", "app.jar"]
+732
View File
@@ -0,0 +1,732 @@
# Xpensely Server — API Reference
> Last updated: 2026-05-14 · Branch: `dev`
## Table of Contents
1. [Overview](#1-overview)
2. [Authentication](#2-authentication)
3. [Rate Limiting](#3-rate-limiting)
4. [Endpoints](#4-endpoints)
- 4.1 [Home](#41-home)
- 4.2 [Users](#42-users)
- 4.3 [Expense Lists](#43-expense-lists)
5. [Data Models](#5-data-models)
6. [Error Handling](#6-error-handling)
7. [Recent Changes — `feature/security-hardening`](#7-recent-changes)
---
## 1. Overview
Xpensely Server is a Spring Boot REST API that manages shared expense lists for pairs of users. It uses Google OAuth2 JWT tokens for authentication. All protected endpoints require a valid Bearer token in the `Authorization` header.
**Base URL (local dev):** `http://localhost:8080`
**Content-Type:** `application/json` for all request and response bodies.
**Public endpoints (no auth required):**
| Method | Path | Description |
|--------|------|-------------|
| GET | `/` | Health check — returns `"Welcome"` |
| GET | `/api/version` | Returns build version and timestamp |
| POST | `/api/users/createUser` | Register a new user |
| GET | `/api/users/byName` | Look up a user by username |
All other endpoints require authentication (see [Section 2](#2-authentication)).
## 2. Authentication
The server uses **OAuth2 Resource Server** authentication with **Google ID JWT tokens**.
### How it works
1. The client authenticates with Google and receives a Google ID JWT.
2. Every protected API request must include this token in the header:
```
Authorization: Bearer <google-id-jwt>
```
3. The server validates the JWT signature and extracts the `sub` claim (Google User ID).
4. The `sub` value is used to look up the registered `AppUser` in the database via `AuthenticatedUserResolver`.
5. If no `AppUser` exists for that Google ID, the request is rejected with **403 Forbidden**.
### Test profile
When the application runs under the `test` Spring profile (`-Dspring.profiles.active=test`), **all security is disabled** — every endpoint is accessible without a token. This is used for automated tests only.
### User registration flow
Before a user can call any protected endpoint they must first be registered:
1. Authenticate with Google to obtain a Google ID JWT.
2. Call `POST /api/users/createUser` with the JWT's `sub` value as `googleId` and a chosen `username`.
3. All subsequent protected calls use the same JWT — the server resolves the caller automatically.
## 3. Rate Limiting
All requests pass through a `RateLimitFilter` (implemented with **Bucket4j**).
| Setting | Value |
|---------|-------|
| Limit | 60 requests per minute |
| Window | Rolling 1-minute bucket |
| Key (authenticated) | JWT `sub` claim (Google User ID) |
| Key (unauthenticated) | `X-Forwarded-For` header, falling back to remote IP |
When the limit is exceeded the server responds with:
```
HTTP 429 Too Many Requests
```
No `Retry-After` header is currently returned. Clients should back off and retry after 60 seconds.
> **Note:** Rate limiting applies in the `!test` profile only. Tests run without rate limiting.
## 4. Endpoints
### 4.1 Home
#### `GET /`
Health check. No authentication required.
**Response:** `200 OK`
```
Welcome
```
---
#### `GET /api/version`
Returns the application version and build timestamp. No authentication required.
**Response:** `200 OK`
```json
{
"version": "0.0.1-SNAPSHOT",
"builtAt": "2026-05-09T10:00:00Z"
}
```
| Field | Type | Notes |
|-------|------|-------|
| `version` | String | Maven project version |
| `builtAt` | String (ISO-8601) | UTC timestamp of the build |
---
### 4.2 Users
Base path: `/api/users`
---
#### `POST /api/users/createUser` — Register a user
**Auth required:** No
**Request body:**
```json
{
"username": "alice",
"googleId": "118400012345678901234"
}
```
| Field | Type | Constraints |
|-------|------|-------------|
| `username` | String | Required. 330 chars. Pattern: `^[a-zA-Z0-9_.\-]+$` |
| `googleId` | String | Required. Non-blank. Must match the JWT `sub` from Google. |
**Success response:** `201 Created` — returns the created [AppUser](#appuser) object.
**Error responses:**
| Status | Condition |
|--------|-----------|
| 400 | Validation failure (field errors returned as `{"fieldName": "message"}`) |
| 409 | `username` already taken |
---
#### `GET /api/users` — Get user by ID
**Auth required:** Yes
**Query params:**
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | Long | Yes | Database ID of the user |
**Success response:** `200 OK` — returns [AppUser](#appuser).
**Error responses:**
| Status | Condition |
|--------|-----------|
| 403 | Authenticated user's ID does not match the requested `id` |
| 404 | No user found for `id` |
---
#### `GET /api/users/byName` — Get user by username
**Auth required:** No
**Query params:**
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `username` | String | Yes | Exact username (case-sensitive) |
**Success response:** `200 OK` — returns [AppUser](#appuser).
**Error responses:**
| Status | Condition |
|--------|-----------|
| 404 | No user found for `username` |
---
#### `GET /api/users/byGoogleId` — Get user by Google ID
**Auth required:** Yes
**Query params:**
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | String | Yes | Google `sub` claim |
**Success response:** `200 OK` — returns [AppUser](#appuser).
**Error responses:**
| Status | Condition |
|--------|-----------|
| 403 | Requested Google ID does not match the authenticated user's Google ID |
| 404 | No user found for that Google ID |
---
#### `DELETE /api/users` — Delete a user
**Auth required:** Yes
**Query params:**
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | Long | Yes | Database ID of the user to delete |
**Success response:** `200 OK` — returns a plain string: `"User deleted: <username>"`.
**Error responses:**
| Status | Condition |
|--------|-----------|
| 403 | Authenticated user's ID does not match the requested `id` |
| 404 | No user found for `id` |
---
### 4.3 Expense Lists
Base path: `/api/expenselist`
All endpoints in this group require authentication. The authenticated caller is resolved from the JWT and used for ownership checks.
---
#### `GET /api/expenselist/mine` — Get caller's expense lists
Returns all expense lists where the caller is the owner **or** has been shared the list.
**Auth required:** Yes
**Request body:** None
**Success responses:**
| Status | Condition |
|--------|-----------|
| 200 OK | Returns array of [ExpenseList](#expenselist) |
| 204 No Content | Caller has no expense lists |
```json
[
{
"id": 1,
"name": "Holiday Trip",
"inviteCode": null,
"owner": { "id": 1, "username": "alice" },
"sharedWith": null,
"expenses": [],
"customCategories": []
}
]
```
---
#### `GET /api/expenselist/byId` — Get expense list by ID
**Auth required:** Yes
**Query params:**
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | Long | Yes | Expense list database ID |
The caller must be the owner or the shared user of the list.
**Success response:** `200 OK` — returns [ExpenseList](#expenselist).
**Error responses:**
| Status | Condition |
|--------|-----------|
| 403 | Caller is neither owner nor shared user |
| 404 | No list found for `id` |
---
#### `POST /api/expenselist/create` — Create an expense list
**Auth required:** Yes
**Request body:**
```json
{
"name": "Road Trip 2026"
}
```
| Field | Type | Constraints |
|-------|------|-------------|
| `name` | String | Required. Max 100 chars. |
The authenticated caller becomes the `owner` of the new list. The list is initialised with the default Xpensely standard categories.
**Success response:** `201 Created` — returns the created [ExpenseList](#expenselist).
**Error responses:**
| Status | Condition |
|--------|-----------|
| 400 | Validation failure |
---
#### `DELETE /api/expenselist/{id}` — Delete an expense list
**Auth required:** Yes
**Path params:**
| Param | Type | Description |
|-------|------|-------------|
| `id` | Long | Expense list database ID |
Only the **owner** may delete a list. Deleting a list cascades to all its expenses and custom categories.
**Success response:** `204 No Content`
**Error responses:**
| Status | Condition |
|--------|-----------|
| 403 | Caller is not the owner |
| 404 | No list found for `id` |
---
#### `POST /api/expenselist/{id}/add` — Add an expense to a list
**Auth required:** Yes
**Path params:**
| Param | Type | Description |
|-------|------|-------------|
| `id` | Long | Expense list database ID |
**Request body:**
```json
{
"title": "Dinner",
"owner": "alice",
"amount": 42.50,
"personalUseAmount": 21.25,
"otherPersonAmount": 21.25,
"date": "2026-05-09",
"category": "Food"
}
```
| Field | Type | Constraints |
|-------|------|-------------|
| `title` | String | Required. Max 100 chars. |
| `owner` | String | Required. Username of the person who paid. |
| `amount` | Double | Required. Min 0.01. |
| `personalUseAmount` | Double | Optional. Caller's share. |
| `otherPersonAmount` | Double | Optional. Other person's share. |
| `date` | String (ISO-8601) | Required. Format: `YYYY-MM-DD`. |
| `category` | String | Required. Non-blank category name. |
**Success response:** `201 Created` — returns the created [Expense](#expense).
**Error responses:**
| Status | Condition |
|--------|-----------|
| 400 | Validation failure |
| 403 | Caller is not a member (owner or sharedWith) of the list |
| 404 | List not found |
---
#### `PUT /api/expenselist/{id}/update` — Update an expense
**Auth required:** Yes
**Path params:**
| Param | Type | Description |
|-------|------|-------------|
| `id` | Long | Expense list database ID |
**Request body:**
```json
{
"id": 7,
"title": "Dinner (updated)",
"ownerName": "alice",
"amount": 50.00,
"personalUseAmount": 25.00,
"otherPersonAmount": 25.00,
"date": "2026-05-09",
"category": "Food"
}
```
| Field | Type | Constraints |
|-------|------|-------------|
| `id` | Long | Required. ID of the expense to update. |
| `title` | String | Required. Max 100 chars. |
| `ownerName` | String | Required. Username of the payer. |
| `amount` | Double | Required. Min 0.01. |
| `personalUseAmount` | Double | Optional. |
| `otherPersonAmount` | Double | Optional. |
| `date` | String (ISO-8601) | Required. `YYYY-MM-DD`. |
| `category` | String | Required. |
Caller must be a member of the list. Expense must belong to the specified list.
**Success response:** `200 OK` — returns the updated [Expense](#expense).
**Error responses:**
| Status | Condition |
|--------|-----------|
| 400 | Validation failure or expense does not belong to this list |
| 403 | Caller is not a member of the list |
| 404 | List or expense not found |
---
#### `DELETE /api/expenselist/{id}/delete` — Remove an expense from a list
**Auth required:** Yes
**Path params:**
| Param | Type | Description |
|-------|------|-------------|
| `id` | Long | Expense list database ID |
**Query params:**
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `expenseId` | Long | Yes | ID of the expense to remove |
Caller must be a member of the list.
**Success response:** `204 No Content`
**Error responses:**
| Status | Condition |
|--------|-----------|
| 403 | Caller is not a member of the list |
| 404 | List or expense not found |
---
#### `POST /api/expenselist/{listId}/invite` — Generate an invite code
Generates (or refreshes) a 6-character uppercase invite code for the list, valid for **1 week**.
**Auth required:** Yes
**Path params:**
| Param | Type | Description |
|-------|------|-------------|
| `listId` | Long | Expense list database ID |
Caller must be the **owner** of the list.
**Success response:** `200 OK` — returns the invite code as a plain string.
```
AB3X7Q
```
**Error responses:**
| Status | Condition |
|--------|-----------|
| 403 | Caller is not the owner |
| 404 | List not found |
---
#### `POST /api/expenselist/accept-invite` — Accept an invite
Joins the caller to a shared expense list using an invite code.
**Auth required:** Yes
**Request body:**
```json
{
"inviteCode": "AB3X7Q"
}
```
| Field | Type | Constraints |
|-------|------|-------------|
| `inviteCode` | String | Required. Exactly 6 characters. |
**Success response:** `200 OK` — returns a plain string: `"User added to the list"`.
**Error responses:**
| Status | Condition |
|--------|-----------|
| 400 | Validation failure or caller is already the owner of the list |
| 404 | Invite code not found or expired |
| 226 IM Used | List already has a second member (`sharedWith` is not null) |
---
## 5. Data Models
### AppUser
Returned by all `/api/users` endpoints. Sensitive fields (`googleId`, `createdAt`) are hidden from API responses via `@JsonIgnore`.
```json
{
"id": 1,
"username": "alice"
}
```
| Field | Type | Notes |
|-------|------|-------|
| `id` | Long | Auto-generated primary key |
| `username` | String | Unique. 330 chars. |
---
### ExpenseList
```json
{
"id": 1,
"name": "Road Trip",
"inviteCode": "AB3X7Q",
"owner": { "id": 1, "username": "alice" },
"sharedWith": { "id": 2, "username": "bob" },
"xpenselyStandardCategories": {
"id": 1,
"categories": [
{ "id": 1, "name": "Food", "colorCode": "#FF5733" }
]
},
"customCategories": [],
"expenses": []
}
```
| Field | Type | Notes |
|-------|------|-------|
| `id` | Long | Auto-generated primary key |
| `name` | String | Display name of the list |
| `inviteCode` | String \| null | 6-char code; `null` if not yet generated or expired |
| `owner` | AppUser | User who created the list |
| `sharedWith` | AppUser \| null | Second member of the list; `null` until an invite is accepted |
| `xpenselyStandardCategories` | XpenselyStandardCategories | Default category set assigned at creation |
| `customCategories` | XpenselyCustomCategory[] | User-defined categories, ordered A→Z |
| `expenses` | Expense[] | All expenses, ordered by date ASC then id ASC |
> `inviteCodeExpiration` is hidden from API responses (`@JsonIgnore`).
---
### Expense
```json
{
"id": 7,
"title": "Dinner",
"owner": { "id": 1, "username": "alice" },
"amount": 42.50,
"personalUseAmount": 21.25,
"otherPersonAmount": 21.25,
"category": "Food",
"date": "2026-05-09"
}
```
| Field | Type | Notes |
|-------|------|-------|
| `id` | Long | Auto-generated |
| `title` | String | Description of the expense |
| `owner` | AppUser | Who paid |
| `amount` | Double | Total amount. Min 0.01. |
| `personalUseAmount` | Double \| null | Caller's share |
| `otherPersonAmount` | Double \| null | Other member's share |
| `category` | String | Category name (free text — must match a category on the list) |
| `date` | String (ISO-8601) | `YYYY-MM-DD` |
> The `expenseList` back-reference is excluded via `@JsonBackReference` to prevent circular serialisation.
---
### XpenselyStandardCategories
A named group of standard categories assigned to every new expense list.
```json
{
"id": 1,
"categories": [
{ "id": 1, "name": "Food", "colorCode": "#FF5733" },
{ "id": 2, "name": "Transport", "colorCode": "#3498DB" }
]
}
```
---
### XpenselyCustomCategory
A user-defined category attached to a specific expense list.
```json
{
"id": 5,
"name": "Souvenirs",
"colorCode": "#9B59B6"
}
```
| Field | Type | Notes |
|-------|------|-------|
| `id` | Long | Auto-generated |
| `name` | String | Category label |
| `colorCode` | String | 7-char hex string e.g. `#RRGGBB` |
> The `expenseList` back-reference is excluded via `@JsonBackReference`.
## 6. Error Handling
All errors are returned as JSON. The `GlobalExceptionHandler` (`@RestControllerAdvice`) maps exceptions to HTTP status codes consistently across every endpoint.
### Error response format
Most errors:
```json
{
"error": "Human-readable message"
}
```
Validation errors (`400`):
```json
{
"username": "size must be between 3 and 30",
"googleId": "must not be blank"
}
```
### Status code reference
| HTTP Status | Condition | Source |
|-------------|-----------|--------|
| 400 Bad Request | Input validation failed (missing/invalid fields) | `MethodArgumentNotValidException` via `@Valid` |
| 400 Bad Request | Business rule violation (e.g. expense not in this list) | `IllegalArgumentException` |
| 403 Forbidden | User not registered in the system | `AuthenticatedUserResolver``ResponseStatusException(FORBIDDEN)` |
| 403 Forbidden | Ownership check failed (e.g. deleting someone else's list) | `ResponseStatusException(FORBIDDEN)` in controller |
| 404 Not Found | Entity does not exist (user, list, expense) | `ResourceNotFoundException` |
| 409 Conflict | Username already taken | `UsernameAlreadyExistsException` |
| 429 Too Many Requests | Rate limit exceeded | `RateLimitFilter` (returned directly, not via exception handler) |
| 500 Internal Server Error | Unexpected runtime or generic exception | `RuntimeException` / `Exception` — message is hidden from client |
## 7. Recent Changes — `feature/security-hardening`
This section summarises API-visible changes introduced on the `feature/security-hardening` branch (commits `3d456f2``b1324e3``8b96433``f0de751`). A developer or agent reading this document should be aware of these differences compared to the `main` branch.
---
### New: Centralised error handling (`GlobalExceptionHandler`)
**File:** `src/main/java/.../controller/GlobalExceptionHandler.java`
All error responses now follow the consistent JSON shape described in [Section 6](#6-error-handling). Previously, individual controllers returned ad-hoc responses, including HTTP 417 and raw stack trace output. Both have been removed. SLF4J logging has been added for server-side error visibility.
---
### New: `AuthenticatedUserResolver`
**File:** `src/main/java/.../security/AuthenticatedUserResolver.java`
A new component that extracts the Google ID from the JWT `sub` claim and resolves the corresponding `AppUser`. Injected into all protected controller methods. Returns `403 Forbidden` if the token is valid but the user has never called `POST /api/users/createUser`.
---
### New: `RateLimitFilter` — 60 req/min
**File:** `src/main/java/.../security/RateLimitFilter.java`
Rate limiting was not present on `main`. See [Section 3](#3-rate-limiting) for full details.
---
### New: `CreateExpenseListRequest` DTO with validation
**File:** `src/main/java/.../model/CreateExpenseListRequest.java`
`POST /api/expenselist/create` previously accepted a raw `ExpenseList` body. It now requires a `CreateExpenseListRequest` with a single validated `name` field (`@NotBlank`, `@Size(max=100)`). Clients must update their request body shape.
---
### Updated: Validation constraints tightened on existing DTOs
| DTO | Field | Change |
|-----|-------|--------|
| `AppUserCreateRequest` | `username` | Added `@Pattern(regexp="^[a-zA-Z0-9_.\-]+$")` — special characters (other than `_`, `.`, `-`) now rejected |
| `InviteRequest` | `inviteCode` | Added `@Size(min=6, max=6)` — non-6-char codes now rejected at binding |
| `ExpenseInput` | `amount` | Added `@DecimalMin("0.01")` — zero and negative amounts now rejected |
| `ExpenseChangeRequest` | `amount` | Added `@DecimalMin("0.01")` — zero and negative amounts now rejected |
---
### Updated: `SecurityConfig` — test-profile isolation
**File:** `src/main/java/.../security/SecurityConfig.java`
Two separate `SecurityFilterChain` beans now exist:
- `@Profile("test")` — all endpoints permitted, CSRF disabled (for automated tests only).
- `@Profile("!test")` — full JWT/OAuth2 enforcement (production behaviour).
Previously a single config was used for both, which made tests fragile.
---
### Fixed: `ExpenseListService` — JPQL and exception consistency
- Single `@Param` used in all JPQL queries (multi-param variant was broken).
- `ResourceNotFoundException` is now thrown consistently instead of returning `null` or a generic `RuntimeException`.
- `addExpenseToList` delegates directly to `ExpenseList.addExpense()` rather than looping.
---
### Fixed: `UserService` — null returns replaced with exceptions
All not-found paths in `UserService` now throw `ResourceNotFoundException` instead of returning `null`. Callers that previously needed to null-check responses will now receive a `404` response.
+148
View File
@@ -0,0 +1,148 @@
# Xpensely API — Manual test file (IntelliJ HTTP Client / VS Code REST Client)
#
# HOW TO GET A TOKEN:
# 1. Run the Flutter dev app and sign in with Google
# 2. Add a breakpoint or log in auth_interceptor.dart after _storage.read(key: 'id_token')
# 3. Paste the token value below (valid for ~1 hour)
#
# Switch between dev and prod by changing @baseUrl.
@devBaseUrl = https://dev-xpensely.zendric.de/api
@prodBaseUrl = https://xpensely.zendric.de/api
@baseUrl = {{devBaseUrl}}
# Paste your Google ID token here:
@token = PASTE_ID_TOKEN_HERE
# Your Google sub (from the JWT payload — decode at jwt.io):
@googleId = PASTE_GOOGLE_SUB_HERE
### ─── Health ────────────────────────────────────────────────────────────────
### Version (no auth required — should always return 200)
GET {{baseUrl}}/version
### ─── Auth probe ─────────────────────────────────────────────────────────────
### Any protected endpoint without a token — expect 401
GET {{baseUrl}}/users/byGoogleId?id={{googleId}}
### ─── Users ──────────────────────────────────────────────────────────────────
### Look up your account by Google ID — expect 200 if account exists, 403 if not
GET {{baseUrl}}/users/byGoogleId?id={{googleId}}
Authorization: Bearer {{token}}
###
### Get your account by DB id — replace {id} with your numeric user id
GET {{baseUrl}}/users?id=1
Authorization: Bearer {{token}}
###
### Get any user by username (no auth required)
GET {{baseUrl}}/users/byName?username=testuser
###
### Create a new account (requires valid JWT — account must not exist yet)
POST {{baseUrl}}/users/createUser
Content-Type: application/json
Authorization: Bearer {{token}}
{
"username": "myusername",
"googleId": "{{googleId}}"
}
###
### Delete your account — replace {id} with your numeric user id
DELETE {{baseUrl}}/users?id=1
Authorization: Bearer {{token}}
### ─── Expense Lists ───────────────────────────────────────────────────────────
### Get all your expense lists — expect 200 (with data) or 204 (empty)
GET {{baseUrl}}/expenselist/mine
Authorization: Bearer {{token}}
###
### Get a specific expense list by id
GET {{baseUrl}}/expenselist/byId?id=1
Authorization: Bearer {{token}}
###
### Create a new expense list
POST {{baseUrl}}/expenselist/create
Content-Type: application/json
Authorization: Bearer {{token}}
{
"name": "Groceries"
}
###
### Add an expense to a list — replace {listId} in the URL
POST {{baseUrl}}/expenselist/1/add
Content-Type: application/json
Authorization: Bearer {{token}}
{
"title": "Coffee",
"owner": "myusername",
"amount": 4.50,
"date": "2026-05-15",
"category": "Food"
}
###
### Update an expense in a list
PUT {{baseUrl}}/expenselist/1/update
Content-Type: application/json
Authorization: Bearer {{token}}
{
"id": 1,
"title": "Coffee (updated)",
"ownerName": "myusername",
"amount": 5.00,
"date": "2026-05-15",
"category": "Food",
"expenseListId": 1
}
###
### Delete an expense from a list
DELETE {{baseUrl}}/expenselist/1/delete?expenseId=1
Authorization: Bearer {{token}}
###
### Generate an invite code for a list (you must be the owner)
POST {{baseUrl}}/expenselist/1/invite
Authorization: Bearer {{token}}
###
### Accept an invite
POST {{baseUrl}}/expenselist/accept-invite
Content-Type: application/json
Authorization: Bearer {{token}}
{
"inviteCode": "PASTE_6_CHAR_CODE_HERE"
}
###
### Delete an expense list (you must be the owner)
DELETE {{baseUrl}}/expenselist/1
Authorization: Bearer {{token}}
Vendored Regular → Executable
View File
+133 -105
View File
@@ -1,110 +1,138 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.1</version> <version>4.0.6</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath/>
</parent> </parent>
<groupId>de.zendric.app</groupId> <groupId>de.zendric.app</groupId>
<artifactId>XpenselyServer</artifactId> <artifactId>XpenselyServer</artifactId>
<version>1.0.0</version> <version>1.2.1</version>
<name>XpenselyServer</name> <name>XpenselyServer</name>
<description>XpenselyServer used to handle the Xpensely App</description> <description>XpenselyServer used to handle the Xpensely App</description>
<url/> <url/>
<licenses> <licenses>
<license/> <license/>
</licenses> </licenses>
<developers> <developers>
<developer/> <developer/>
</developers> </developers>
<scm> <scm>
<connection/> <connection/>
<developerConnection/> <developerConnection/>
<tag/> <tag/>
<url/> <url/>
</scm> </scm>
<properties> <properties>
<java.version>17</java.version> <java.version>21</java.version>
</properties> <lombok.version>1.18.46</lombok.version>
<dependencies> </properties>
<dependency> <dependencies>
<groupId>org.springframework.boot</groupId> <dependency>
<artifactId>spring-boot-starter-data-jpa</artifactId> <groupId>org.springframework.boot</groupId>
</dependency> <artifactId>spring-boot-starter-data-jpa</artifactId>
<dependency> </dependency>
<groupId>org.springframework.boot</groupId> <dependency>
<artifactId>spring-boot-starter-security</artifactId> <groupId>org.springframework.boot</groupId>
</dependency> <artifactId>spring-boot-starter-security</artifactId>
<dependency> </dependency>
<groupId>org.springframework.boot</groupId> <dependency>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId> <groupId>org.springframework.boot</groupId>
</dependency> <artifactId>spring-boot-starter-validation</artifactId>
<dependency> </dependency>
<groupId>org.springframework.boot</groupId> <dependency>
<artifactId>spring-boot-starter-oauth2-client</artifactId> <groupId>com.bucket4j</groupId>
</dependency> <artifactId>bucket4j-core</artifactId>
<dependency> <version>8.10.1</version>
<groupId>org.springframework.boot</groupId> </dependency>
<artifactId>spring-boot-starter-web</artifactId> <dependency>
</dependency> <groupId>org.springframework.boot</groupId>
<dependency> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
<groupId>org.springframework.boot</groupId> </dependency>
<artifactId>spring-boot-devtools</artifactId> <dependency>
<scope>runtime</scope> <groupId>org.springframework.boot</groupId>
<optional>true</optional> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.postgresql</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>postgresql</artifactId> <artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> <optional>true</optional>
<dependency> </dependency>
<groupId>org.projectlombok</groupId> <dependency>
<artifactId>lombok</artifactId> <groupId>org.postgresql</groupId>
<optional>true</optional> <artifactId>postgresql</artifactId>
</dependency> <scope>runtime</scope>
<dependency> </dependency>
<groupId>org.springframework.boot</groupId> <dependency>
<artifactId>spring-boot-starter-test</artifactId> <groupId>org.projectlombok</groupId>
<scope>test</scope> <artifactId>lombok</artifactId>
</dependency> <optional>true</optional>
<dependency> </dependency>
<groupId>org.springframework.security</groupId> <dependency>
<artifactId>spring-security-test</artifactId> <groupId>org.springframework.boot</groupId>
<scope>test</scope> <artifactId>spring-boot-starter-test</artifactId>
</dependency> <scope>test</scope>
</dependencies> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<configuration> <configuration>
<annotationProcessorPaths> <annotationProcessorPaths>
<path> <path>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
</path> </path>
</annotationProcessorPaths> </annotationProcessorPaths>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<configuration> <configuration>
<excludes> <excludes>
<exclude> <exclude>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
</exclude> </exclude>
</excludes> </excludes>
</configuration> </configuration>
</plugin> <executions>
</plugins> <execution>
</build> <goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project> </project>
@@ -1,73 +1,70 @@
package de.zendric.app.xpensely_server.controller; package de.zendric.app.xpensely_server.controller;
import org.springframework.beans.factory.annotation.Autowired; import jakarta.validation.Valid;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import de.zendric.app.xpensely_server.model.AppUser; import de.zendric.app.xpensely_server.model.AppUser;
import de.zendric.app.xpensely_server.model.AppUserCreateRequest; import de.zendric.app.xpensely_server.model.AppUserCreateRequest;
import de.zendric.app.xpensely_server.model.UsernameAlreadyExistsException; import de.zendric.app.xpensely_server.model.UsernameUpdateRequest;
import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver;
import de.zendric.app.xpensely_server.services.UserService; import de.zendric.app.xpensely_server.services.UserService;
@RestController @RestController
@RequestMapping("/api/users") @RequestMapping("/api/users")
public class AppUserController { public class AppUserController {
private UserService userService; private final UserService userService;
private final AuthenticatedUserResolver authenticatedUserResolver;
@Autowired public AppUserController(UserService userService, AuthenticatedUserResolver authenticatedUserResolver) {
public AppUserController(UserService userService) {
this.userService = userService; this.userService = userService;
this.authenticatedUserResolver = authenticatedUserResolver;
} }
@GetMapping @GetMapping
public AppUser getUser(@RequestParam Long id) { public ResponseEntity<AppUser> getUser(@RequestParam Long id, Authentication authentication) {
return userService.getUser(id); AppUser self = authenticatedUserResolver.resolveCurrentUser(authentication);
} assertSelf(self, id);
return ResponseEntity.ok(userService.getUser(id));
@GetMapping("/byName")
public AppUser getUserByName(@RequestParam String username) {
return userService.getUserByName(username);
} }
@GetMapping("/byGoogleId") @GetMapping("/byGoogleId")
public ResponseEntity<AppUser> getUserByGoogleId(@RequestParam String id) { public ResponseEntity<AppUser> getUserByGoogleId(@RequestParam String id, Authentication authentication) {
try { AppUser self = authenticatedUserResolver.resolveCurrentUser(authentication);
AppUser userByGoogleId = userService.getUserByGoogleId(id); if (!self.getGoogleId().equals(id))
return new ResponseEntity<>(userByGoogleId, HttpStatus.OK); throw new ResponseStatusException(HttpStatus.FORBIDDEN);
return ResponseEntity.ok(self);
} catch (IllegalArgumentException e) {
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
} }
@PostMapping("/createUser") @PostMapping("/createUser")
public ResponseEntity<AppUser> createUser(@RequestBody AppUserCreateRequest userRequest) { public ResponseEntity<AppUser> createUser(@RequestBody @Valid AppUserCreateRequest userRequest) {
try { AppUser convertedUser = userRequest.convertToAppUser();
AppUser convertedUser = userRequest.convertToAppUser(); AppUser nUser = userService.createUser(convertedUser);
return new ResponseEntity<>(nUser, HttpStatus.CREATED);
AppUser nUser = userService.createUser(convertedUser); }
return new ResponseEntity<>(nUser, HttpStatus.CREATED);
} catch (UsernameAlreadyExistsException e) {
return new ResponseEntity<>(null, HttpStatus.CONFLICT);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
@PutMapping("/username")
public ResponseEntity<AppUser> updateUsername(@RequestBody @Valid UsernameUpdateRequest request,
Authentication authentication) {
AppUser self = authenticatedUserResolver.resolveCurrentUser(authentication);
AppUser updated = userService.updateUsername(self.getId(), request.getUsername());
return ResponseEntity.ok(updated);
} }
@DeleteMapping @DeleteMapping
public String deleteUser(@RequestParam Long id) { public ResponseEntity<String> deleteUser(@RequestParam Long id, Authentication authentication) {
AppUser self = authenticatedUserResolver.resolveCurrentUser(authentication);
assertSelf(self, id);
AppUser user = userService.deleteUserById(id); AppUser user = userService.deleteUserById(id);
return "User deleted : " + user.getUsername(); return ResponseEntity.ok("User deleted: " + user.getUsername());
}
private void assertSelf(AppUser authenticated, Long requestedId) {
if (!authenticated.getId().equals(requestedId))
throw new ResponseStatusException(HttpStatus.FORBIDDEN);
} }
} }
@@ -1,188 +1,176 @@
package de.zendric.app.xpensely_server.controller; package de.zendric.app.xpensely_server.controller;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired; import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import de.zendric.app.xpensely_server.model.AppUser; import de.zendric.app.xpensely_server.model.*;
import de.zendric.app.xpensely_server.model.Expense; import de.zendric.app.xpensely_server.model.DTO.HistoryPageDto;
import de.zendric.app.xpensely_server.model.ExpenseChangeRequest; import de.zendric.app.xpensely_server.model.DTO.RecentHistoryEntryDto;
import de.zendric.app.xpensely_server.model.ExpenseInput; import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver;
import de.zendric.app.xpensely_server.model.ExpenseList; import de.zendric.app.xpensely_server.services.CategoryService;
import de.zendric.app.xpensely_server.model.InviteRequest;
import de.zendric.app.xpensely_server.services.ExpenseListService; import de.zendric.app.xpensely_server.services.ExpenseListService;
import de.zendric.app.xpensely_server.services.UserService; import de.zendric.app.xpensely_server.services.HistoryService;
@RestController @RestController
@RequestMapping("/api/expenselist") @RequestMapping("/api/expenselist")
class ExpenseListController { public class ExpenseListController {
private ExpenseListService expenseListService; private static final Logger log = LoggerFactory.getLogger(ExpenseListController.class);
private UserService userService;
@Autowired private final ExpenseListService expenseListService;
public ExpenseListController(ExpenseListService expenseListService, UserService userService) { private final CategoryService categoryService;
private final AuthenticatedUserResolver authenticatedUserResolver;
private final HistoryService historyService;
public ExpenseListController(ExpenseListService expenseListService,
CategoryService categoryService, AuthenticatedUserResolver authenticatedUserResolver,
HistoryService historyService) {
this.expenseListService = expenseListService; this.expenseListService = expenseListService;
this.userService = userService; this.categoryService = categoryService;
this.authenticatedUserResolver = authenticatedUserResolver;
this.historyService = historyService;
} }
@GetMapping("/all") @GetMapping("/mine")
public ResponseEntity<List<ExpenseList>> getAll() { public ResponseEntity<List<ExpenseList>> getMine(Authentication authentication) {
try { AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
List<ExpenseList> items = new ArrayList<>(); List<ExpenseList> items = expenseListService.findByUserId(user.getId());
if (items.isEmpty())
expenseListService.findAll().forEach(items::add); return new ResponseEntity<>(HttpStatus.NO_CONTENT);
return new ResponseEntity<>(items, HttpStatus.OK);
if (items.isEmpty())
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
return new ResponseEntity<>(items, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/byUser")
public ResponseEntity<List<ExpenseList>> getByUser(@RequestParam Long userId) {
try {
List<ExpenseList> items = expenseListService.findByUserId(userId);
if (items.isEmpty())
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
return new ResponseEntity<>(items, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/byUsername")
public ResponseEntity<List<ExpenseList>> getByUser(@RequestParam String username) {
try {
List<ExpenseList> items = expenseListService.findByUsername(username);
if (items.isEmpty())
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
return new ResponseEntity<>(items, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
} }
@GetMapping("/byId") @GetMapping("/byId")
public ResponseEntity<ExpenseList> getById(@RequestParam Long id) { public ResponseEntity<ExpenseList> getById(@RequestParam Long id, Authentication authentication) {
AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
Optional<ExpenseList> existingItemOptional = expenseListService.findById(id); Optional<ExpenseList> existingItemOptional = expenseListService.findById(id);
if (existingItemOptional.isEmpty())
if (existingItemOptional.isPresent()) {
return new ResponseEntity<>(existingItemOptional.get(), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND); return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} assertMember(user, existingItemOptional.get());
return new ResponseEntity<>(existingItemOptional.get(), HttpStatus.OK);
} }
@PostMapping("/create") @PostMapping("/create")
public ResponseEntity<ExpenseList> create(@RequestBody ExpenseList expenseList) { public ResponseEntity<ExpenseList> create(@RequestBody @Valid CreateExpenseListRequest request,
try { Authentication authentication) {
if (expenseList.getOwner() != null) { AppUser authenticatedUser = authenticatedUserResolver.resolveCurrentUser(authentication);
AppUser existingOwner = userService.getUser(expenseList.getOwner().getId()); ExpenseList expenseList = new ExpenseList();
if (existingOwner == null) { expenseList.setName(request.getName());
throw new IllegalArgumentException("Owner does not exist."); expenseList.setOwner(authenticatedUser);
} XpenselyStandardCategories standardCategories = categoryService.getDefaultCategories();
expenseList.setOwner(existingOwner); expenseList.setXpenselyStandardCategories(standardCategories);
} else { expenseList.setSharedWith(null);
throw new IllegalArgumentException("Owner is required."); ExpenseList savedItem = expenseListService.createList(expenseList);
} log.debug("Created expense list '{}' for user {}", savedItem.getName(), authenticatedUser.getId());
return new ResponseEntity<>(savedItem, HttpStatus.CREATED);
expenseList.setSharedWith(null);
ExpenseList savedItem = expenseListService.createList(expenseList);
return new ResponseEntity<>(savedItem, HttpStatus.CREATED);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(null, HttpStatus.EXPECTATION_FAILED);
}
} }
@DeleteMapping("{id}") @DeleteMapping("{id}")
public ResponseEntity<HttpStatus> delete(@PathVariable("id") Long id) { public ResponseEntity<HttpStatus> delete(@PathVariable("id") Long id, Authentication authentication) {
try { AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
expenseListService.deleteById(id); Optional<ExpenseList> listOpt = expenseListService.findById(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT); if (listOpt.isEmpty())
} catch (Exception e) { return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(HttpStatus.EXPECTATION_FAILED); assertOwner(user, listOpt.get());
} expenseListService.deleteById(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@PutMapping("/{id}/rename")
public ResponseEntity<ExpenseList> rename(@PathVariable("id") Long id,
@RequestBody @Valid CreateExpenseListRequest request, Authentication authentication) {
AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
Optional<ExpenseList> listOpt = expenseListService.findById(id);
if (listOpt.isEmpty())
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
assertOwner(user, listOpt.get());
ExpenseList renamed = expenseListService.renameList(id, request.getName());
return new ResponseEntity<>(renamed, HttpStatus.OK);
}
@PutMapping("/{id}/default-split")
public ResponseEntity<ExpenseList> updateDefaultSplit(@PathVariable("id") Long id,
@RequestBody @Valid DefaultSplitRequest request, Authentication authentication) {
AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
Optional<ExpenseList> listOpt = expenseListService.findById(id);
if (listOpt.isEmpty())
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
assertMember(user, listOpt.get());
ExpenseList updated = expenseListService.updateDefaultSplit(id, request.getPercentage());
return new ResponseEntity<>(updated, HttpStatus.OK);
} }
@PostMapping("/{id}/add") @PostMapping("/{id}/add")
public ResponseEntity<Expense> addExpenseToList( public ResponseEntity<Expense> addExpenseToList(
@PathVariable("id") Long expenseListId, @PathVariable("id") Long expenseListId,
@RequestBody ExpenseInput expenseInput) { @RequestBody @Valid ExpenseInput expenseInput,
try { Authentication authentication) {
AppUser expenseOwner = userService.getUserByName(expenseInput.getOwner()); AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
Expense expense = expenseInput.convertToExpense(expenseOwner.getId()); Optional<ExpenseList> listOpt = expenseListService.findById(expenseListId);
if (listOpt.isEmpty())
Expense addedExpense = expenseListService.addExpenseToList(expenseListId, expense); return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(addedExpense, HttpStatus.CREATED); assertMember(user, listOpt.get());
} catch (Exception e) { AppUser expenseOwner = resolveListMember(listOpt.get(), expenseInput.getOwner());
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); Expense expense = expenseInput.convertToExpense(expenseOwner.getId());
} Expense addedExpense = expenseListService.addExpenseToList(expenseListId, expense, user);
return new ResponseEntity<>(addedExpense, HttpStatus.CREATED);
} }
@PutMapping("/{id}/update") @PutMapping("/{id}/update")
public ResponseEntity<Expense> updateExpenseInList( public ResponseEntity<Expense> updateExpenseInList(
@PathVariable("id") Long expenseListId, @PathVariable("id") Long expenseListId,
@RequestBody ExpenseChangeRequest expenseChangeRequest) { @RequestBody @Valid ExpenseChangeRequest expenseChangeRequest,
try { Authentication authentication) {
AppUser expenseOwner = userService.getUserByName(expenseChangeRequest.getOwnerName()); AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
Optional<ExpenseList> expenseList = expenseListService.findById(expenseListId); Optional<ExpenseList> expenseListOpt = expenseListService.findById(expenseListId);
if (expenseList.isPresent()) { if (expenseListOpt.isEmpty())
Expense expense = expenseChangeRequest.convertToExpense(expenseOwner.getId(), expenseList.get()); return new ResponseEntity<>(HttpStatus.NOT_FOUND);
assertMember(user, expenseListOpt.get());
Expense addedExpense = expenseListService.updateExpense(expenseListId, expense); AppUser expenseOwner = resolveListMember(expenseListOpt.get(), expenseChangeRequest.getOwnerName());
return new ResponseEntity<>(addedExpense, HttpStatus.CREATED); Expense expense = expenseChangeRequest.convertToExpense(expenseOwner.getId(), expenseListOpt.get());
} Expense updatedExpense = expenseListService.updateExpense(expenseListId, expense, user);
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); return new ResponseEntity<>(updatedExpense, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
} }
@DeleteMapping("/{id}/delete") @DeleteMapping("/{id}/delete")
public ResponseEntity<Expense> deleteExpenseFromList( public ResponseEntity<Expense> deleteExpenseFromList(
@PathVariable("id") Long expenseListId, @PathVariable("id") Long expenseListId,
@RequestParam("expenseId") Long expenseId) { @RequestParam("expenseId") Long expenseId,
try { Authentication authentication) {
expenseListService.deleteExpenseFromList(expenseListId, expenseId); AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
return new ResponseEntity<>(HttpStatus.NO_CONTENT); Optional<ExpenseList> listOpt = expenseListService.findById(expenseListId);
} catch (Exception e) { if (listOpt.isEmpty())
return new ResponseEntity<>(null, HttpStatus.EXPECTATION_FAILED); return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} assertMember(user, listOpt.get());
expenseListService.deleteExpenseFromList(expenseListId, expenseId, user);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} }
@PostMapping("/{listId}/invite") @PostMapping("/{listId}/invite")
public ResponseEntity<String> generateInvite(@PathVariable Long listId) { public ResponseEntity<String> generateInvite(@PathVariable Long listId, Authentication authentication) {
AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
Optional<ExpenseList> listOpt = expenseListService.findById(listId);
if (listOpt.isEmpty())
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
assertOwner(user, listOpt.get());
String inviteCode = expenseListService.generateInviteCode(listId); String inviteCode = expenseListService.generateInviteCode(listId);
return ResponseEntity.ok(inviteCode); return ResponseEntity.ok(inviteCode);
} }
@PostMapping("/accept-invite") @PostMapping("/accept-invite")
public ResponseEntity<?> acceptInvite(@RequestBody InviteRequest inviteRequest) { public ResponseEntity<?> acceptInvite(@RequestBody @Valid InviteRequest inviteRequest,
Authentication authentication) {
AppUser authenticatedUser = authenticatedUserResolver.resolveCurrentUser(authentication);
ExpenseList list = expenseListService.findByInviteCode(inviteRequest.getInviteCode()); ExpenseList list = expenseListService.findByInviteCode(inviteRequest.getInviteCode());
if (list == null || list.getInviteCodeExpiration() == null || if (list == null || list.getInviteCodeExpiration() == null ||
@@ -192,21 +180,67 @@ class ExpenseListController {
if (list.getSharedWith() != null) { if (list.getSharedWith() != null) {
return ResponseEntity.status(HttpStatus.IM_USED).body("List has already been shared"); return ResponseEntity.status(HttpStatus.IM_USED).body("List has already been shared");
} }
if (list.getOwner().getId() == inviteRequest.getUserId()) { if (list.getOwner().getId().equals(authenticatedUser.getId())) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("You cant join your own List"); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("You cannot join your own list");
} }
AppUser user = null; if (list.getOwner().getUsername().equals(authenticatedUser.getUsername())) {
try { return ResponseEntity.status(HttpStatus.CONFLICT).body(
user = userService.getUser(inviteRequest.getUserId()); "You and the list owner both use the username \"" + authenticatedUser.getUsername()
} catch (Exception e) { + "\". Please change your username before joining this list.");
throw new RuntimeException("User not found");
}
if (user != null) {
list.setSharedWith(user);
expenseListService.save(list);
} else {
throw new RuntimeException("User not found");
} }
list.setSharedWith(authenticatedUser);
expenseListService.save(list);
return ResponseEntity.ok("User added to the list"); return ResponseEntity.ok("User added to the list");
} }
@GetMapping("/{id}/history")
public ResponseEntity<HistoryPageDto> getHistory(
@PathVariable("id") Long id,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "30") int size,
Authentication authentication) {
AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
Optional<ExpenseList> listOpt = expenseListService.findById(id);
if (listOpt.isEmpty())
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
assertMember(user, listOpt.get());
return ResponseEntity.ok(historyService.getHistory(id, page, size));
}
@GetMapping("/history/recent")
public ResponseEntity<List<RecentHistoryEntryDto>> getRecentHistory(
@RequestParam(defaultValue = "4") int limit,
Authentication authentication) {
AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
return ResponseEntity.ok(historyService.getRecentForUser(user, limit));
}
private void assertOwner(AppUser authenticated, ExpenseList list) {
if (!list.getOwner().getId().equals(authenticated.getId()))
throw new ResponseStatusException(HttpStatus.FORBIDDEN);
}
private void assertMember(AppUser authenticated, ExpenseList list) {
boolean isOwner = list.getOwner().getId().equals(authenticated.getId());
boolean isShared = list.getSharedWith() != null
&& list.getSharedWith().getId().equals(authenticated.getId());
if (!isOwner && !isShared)
throw new ResponseStatusException(HttpStatus.FORBIDDEN);
}
/**
* Resolves an expense owner by username among the list's members. Usernames are
* not globally unique, so the owner must be one of this list's (at most two)
* members — never a global lookup.
*/
private AppUser resolveListMember(ExpenseList list, String username) {
if (list.getOwner() != null && list.getOwner().getUsername().equals(username)) {
return list.getOwner();
}
if (list.getSharedWith() != null && list.getSharedWith().getUsername().equals(username)) {
return list.getSharedWith();
}
throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
"Expense owner must be a member of this list");
}
} }
@@ -0,0 +1,77 @@
package de.zendric.app.xpensely_server.controller;
import de.zendric.app.xpensely_server.model.Exception.GoogleAccountAlreadyRegisteredException;
import de.zendric.app.xpensely_server.model.Exception.ResourceNotFoundException;
import de.zendric.app.xpensely_server.model.Exception.UsernameAlreadyExistsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ResponseStatusException;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidationErrors(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
errors.put(fieldError.getField(), fieldError.getDefaultMessage());
}
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors);
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Map<String, String>> handleIllegalArgument(IllegalArgumentException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", ex.getMessage()));
}
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<Map<String, String>> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(Map.of("error", ex.getMessage()));
}
@ExceptionHandler(UsernameAlreadyExistsException.class)
public ResponseEntity<Map<String, String>> handleUsernameConflict(UsernameAlreadyExistsException ex) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body(Map.of("error", ex.getMessage()));
}
@ExceptionHandler(GoogleAccountAlreadyRegisteredException.class)
public ResponseEntity<Map<String, String>> handleGoogleAccountConflict(
GoogleAccountAlreadyRegisteredException ex) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body(Map.of("error", ex.getMessage()));
}
@ExceptionHandler(ResponseStatusException.class)
public ResponseEntity<Map<String, String>> handleResponseStatus(ResponseStatusException ex) {
return ResponseEntity.status(ex.getStatusCode())
.body(Map.of("error", ex.getReason() != null ? ex.getReason() : ex.getMessage()));
}
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<Map<String, String>> handleRuntime(RuntimeException ex) {
log.error("Unhandled runtime exception", ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "An unexpected error occurred"));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, String>> handleGeneric(Exception ex) {
log.error("Unhandled exception", ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "An unexpected error occurred"));
}
}
@@ -1,13 +1,30 @@
package de.zendric.app.xpensely_server.controller; package de.zendric.app.xpensely_server.controller;
import org.springframework.boot.info.BuildProperties;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController @RestController
class HomeController { class HomeController {
private final BuildProperties buildProperties;
HomeController(BuildProperties buildProperties) {
this.buildProperties = buildProperties;
}
@GetMapping("/") @GetMapping("/")
public String getAll() { public String getAll() {
return "Welcome"; return "Welcome";
} }
@GetMapping("/api/version")
public Map<String, String> version() {
return Map.of(
"version", buildProperties.getVersion(),
"builtAt", buildProperties.getTime().toString()
);
}
} }
@@ -26,9 +26,10 @@ public class AppUser {
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
@Column(name = "username", nullable = false, unique = true) @Column(name = "username", nullable = false)
private String username; private String username;
@Column(name = "google_id", unique = true)
@JsonIgnore @JsonIgnore
private String googleId; private String googleId;
@@ -1,21 +1,25 @@
package de.zendric.app.xpensely_server.model; package de.zendric.app.xpensely_server.model;
import jakarta.persistence.Column; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.Data; import lombok.Data;
@Data @Data
public class AppUserCreateRequest { public class AppUserCreateRequest {
@Column(name = "username", nullable = false, unique = true) @NotBlank(message = "Username is required")
@Size(min = 3, max = 30, message = "Username must be between 3 and 30 characters")
@Pattern(regexp = "^[a-zA-Z0-9_.\\-]+$", message = "Username may only contain letters, digits, underscores, dots, and hyphens")
private String username; private String username;
@NotBlank(message = "Google ID is required")
private String googleId; private String googleId;
public AppUser convertToAppUser() { public AppUser convertToAppUser() {
AppUser appUser = new AppUser(); AppUser appUser = new AppUser();
appUser.setGoogleId(googleId); appUser.setGoogleId(googleId);
appUser.setUsername(username); appUser.setUsername(username);
return appUser; return appUser;
} }
} }
@@ -0,0 +1,17 @@
package de.zendric.app.xpensely_server.model;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class CreateExpenseListRequest {
@NotBlank(message = "List name is required")
@Size(max = 100, message = "List name must not exceed 100 characters")
private String name;
}
@@ -0,0 +1,8 @@
package de.zendric.app.xpensely_server.model.DTO;
public class ExpenseListDTO {
// TODO should combine the two categories to one;
// private List<CategoryDTO> availableCategories;
}
@@ -0,0 +1,14 @@
package de.zendric.app.xpensely_server.model.DTO;
import java.time.LocalDateTime;
import java.util.List;
import de.zendric.app.xpensely_server.model.FieldChange;
public record HistoryEntryDto(
String type,
String actorUsername,
String expenseTitle,
LocalDateTime timestamp,
List<FieldChange> changes) {
}
@@ -0,0 +1,6 @@
package de.zendric.app.xpensely_server.model.DTO;
import java.util.List;
public record HistoryPageDto(List<HistoryEntryDto> entries, boolean hasMore) {
}
@@ -0,0 +1,12 @@
package de.zendric.app.xpensely_server.model.DTO;
import java.time.LocalDateTime;
public record RecentHistoryEntryDto(
String type,
String actorUsername,
String expenseTitle,
LocalDateTime timestamp,
Long listId,
String listName) {
}
@@ -0,0 +1,17 @@
package de.zendric.app.xpensely_server.model;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class DefaultSplitRequest {
@NotNull(message = "Percentage is required")
@Min(value = 0, message = "Percentage must be between 0 and 100")
@Max(value = 100, message = "Percentage must be between 0 and 100")
private Integer percentage;
}
@@ -0,0 +1,11 @@
package de.zendric.app.xpensely_server.model.Exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.CONFLICT)
public class GoogleAccountAlreadyRegisteredException extends RuntimeException {
public GoogleAccountAlreadyRegisteredException(String message) {
super(message);
}
}
@@ -0,0 +1,11 @@
package de.zendric.app.xpensely_server.model.Exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
@@ -1,4 +1,4 @@
package de.zendric.app.xpensely_server.model; package de.zendric.app.xpensely_server.model.Exception;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.ResponseStatus;
@@ -1,10 +1,13 @@
package de.zendric.app.xpensely_server.model; package de.zendric.app.xpensely_server.model;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime;
import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.GeneratedValue; import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType; import jakarta.persistence.GenerationType;
import jakarta.persistence.Id; import jakarta.persistence.Id;
@@ -34,8 +37,15 @@ public class Expense {
private Double amount; private Double amount;
private Double personalUseAmount; private Double personalUseAmount;
private Double otherPersonAmount; private Double otherPersonAmount;
private String category;
@Enumerated(EnumType.STRING)
private SplitMode splitMode;
private Integer splitPercentage;
private LocalDate date; private LocalDate date;
private LocalDateTime lastModified;
@ManyToOne @ManyToOne
@JoinColumn(name = "expense_list_id", nullable = false) @JoinColumn(name = "expense_list_id", nullable = false)
@@ -2,6 +2,12 @@ package de.zendric.app.xpensely_server.model;
import java.time.LocalDate; import java.time.LocalDate;
import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
@@ -12,13 +18,34 @@ import lombok.NoArgsConstructor;
public class ExpenseChangeRequest { public class ExpenseChangeRequest {
private Long id; private Long id;
@NotBlank(message = "Title is required")
@Size(max = 100, message = "Title must not exceed 100 characters")
private String title; private String title;
@NotBlank(message = "Owner name is required")
private String ownerName; private String ownerName;
// Same bounds as ExpenseInput: Quick Add creates stub expenses with amount 0
// and no category, and those stubs must remain editable.
@NotNull(message = "Amount is required")
@DecimalMin(value = "0.00", message = "Amount must not be negative")
private Double amount; private Double amount;
private Double personalUseAmount; private Double personalUseAmount;
private Double otherPersonAmount; private Double otherPersonAmount;
private SplitMode splitMode;
@Min(0)
@Max(100)
private Integer splitPercentage;
@NotNull(message = "Date is required")
private LocalDate date; private LocalDate date;
private String category;
public Expense convertToExpense(Long userId, ExpenseList expenseList) { public Expense convertToExpense(Long userId, ExpenseList expenseList) {
AppUser appUser = new AppUser(); AppUser appUser = new AppUser();
appUser.setId(userId); appUser.setId(userId);
@@ -33,6 +60,11 @@ public class ExpenseChangeRequest {
expense.setId(id); expense.setId(id);
expense.setOwner(appUser); expense.setOwner(appUser);
expense.setTitle(title); expense.setTitle(title);
// The edit dialog sends "" for a missing category; store null so the
// stub state stays uniform and history diffs don't report null -> "".
expense.setCategory(category == null || category.isBlank() ? null : category);
expense.setSplitMode(splitMode == null ? SplitMode.DETAILED : splitMode);
expense.setSplitPercentage(splitPercentage);
return expense; return expense;
} }
@@ -0,0 +1,52 @@
package de.zendric.app.xpensely_server.model;
import java.time.LocalDateTime;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name = "expense_history_entry", indexes = @Index(name = "idx_history_list_timestamp", columnList = "expense_list_id, timestamp DESC"))
public class ExpenseHistoryEntry {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "expense_list_id", nullable = false)
private ExpenseList expenseList;
/** Plain column on purpose — no FK, so history survives expense deletion. */
private Long expenseId;
/** Denormalized so entries for deleted expenses still render. */
private String expenseTitle;
@ManyToOne
private AppUser actor;
@Enumerated(EnumType.STRING)
private HistoryEntryType type;
private LocalDateTime timestamp;
/** JSON array of FieldChange; null for CREATED/DELETED. */
@Column(columnDefinition = "TEXT")
private String changes;
}
@@ -2,9 +2,12 @@ package de.zendric.app.xpensely_server.model;
import java.time.LocalDate; import java.time.LocalDate;
import jakarta.persistence.GeneratedValue; import jakarta.validation.constraints.DecimalMin;
import jakarta.persistence.GenerationType; import jakarta.validation.constraints.Max;
import jakarta.persistence.Id; import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
@@ -16,20 +19,34 @@ import lombok.Setter;
@NoArgsConstructor @NoArgsConstructor
public class ExpenseInput { public class ExpenseInput {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
@NotBlank(message = "Title is required")
@Size(max = 100, message = "Title must not exceed 100 characters")
private String title; private String title;
@NotBlank(message = "Owner is required")
private String owner; private String owner;
@NotNull(message = "Amount is required")
@DecimalMin(value = "0.00", message = "Amount must not be negative")
private Double amount; private Double amount;
private Double personalUseAmount; private Double personalUseAmount;
private Double otherPersonAmount; private Double otherPersonAmount;
private SplitMode splitMode;
@Min(0)
@Max(100)
private Integer splitPercentage;
@NotNull(message = "Date is required")
private LocalDate date; private LocalDate date;
// Optional: Quick Add creates stub expenses without a category, to be filled in later.
private String category;
private ExpenseList expenseList; private ExpenseList expenseList;
public Expense convertToExpense(Long userId) { public Expense convertToExpense(Long userId) {
@@ -46,6 +63,9 @@ public class ExpenseInput {
expense.setId(id); expense.setId(id);
expense.setOwner(appUser); expense.setOwner(appUser);
expense.setTitle(title); expense.setTitle(title);
expense.setCategory(category);
expense.setSplitMode(splitMode == null ? SplitMode.DETAILED : splitMode);
expense.setSplitPercentage(splitPercentage);
return expense; return expense;
} }
@@ -8,6 +8,7 @@ import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.CascadeType; import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue; import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType; import jakarta.persistence.GenerationType;
import jakarta.persistence.Id; import jakarta.persistence.Id;
@@ -30,6 +31,8 @@ public class ExpenseList {
private String name; private String name;
private Integer defaultSplitPercentage = 50;
private String inviteCode; private String inviteCode;
@JsonIgnore @JsonIgnore
private LocalDateTime inviteCodeExpiration; private LocalDateTime inviteCodeExpiration;
@@ -40,6 +43,14 @@ public class ExpenseList {
@ManyToOne @ManyToOne
private AppUser sharedWith; private AppUser sharedWith;
@ManyToOne(fetch = FetchType.EAGER)
private XpenselyStandardCategories xpenselyStandardCategories;
@OneToMany(mappedBy = "expenseList", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference
@jakarta.persistence.OrderBy("name ASC")
private List<XpenselyCustomCategory> customCategories;
@OneToMany(mappedBy = "expenseList", cascade = CascadeType.ALL, orphanRemoval = true) @OneToMany(mappedBy = "expenseList", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference @JsonManagedReference
@jakarta.persistence.OrderBy("date ASC, id ASC") @jakarta.persistence.OrderBy("date ASC, id ASC")
@@ -0,0 +1,9 @@
package de.zendric.app.xpensely_server.model;
import com.fasterxml.jackson.annotation.JsonProperty;
public record FieldChange(
String field,
@JsonProperty("old") String oldValue,
@JsonProperty("new") String newValue) {
}
@@ -0,0 +1,5 @@
package de.zendric.app.xpensely_server.model;
public enum HistoryEntryType {
CREATED, UPDATED, DELETED
}
@@ -1,5 +1,7 @@
package de.zendric.app.xpensely_server.model; package de.zendric.app.xpensely_server.model;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
@@ -8,6 +10,8 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
public class InviteRequest { public class InviteRequest {
@NotBlank(message = "Invite code is required")
@Size(min = 6, max = 6, message = "Invite code must be exactly 6 characters")
private String inviteCode; private String inviteCode;
private Long userId;
} }
@@ -0,0 +1,6 @@
package de.zendric.app.xpensely_server.model;
public enum SplitMode {
DETAILED,
PERCENTAGE
}
@@ -0,0 +1,15 @@
package de.zendric.app.xpensely_server.model;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.Data;
@Data
public class UsernameUpdateRequest {
@NotBlank(message = "Username is required")
@Size(min = 3, max = 30, message = "Username must be between 3 and 30 characters")
@Pattern(regexp = "^[a-zA-Z0-9_.\\-]+$", message = "Username may only contain letters, digits, underscores, dots, and hyphens")
private String username;
}
@@ -0,0 +1,37 @@
package de.zendric.app.xpensely_server.model;
import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class XpenselyCustomCategory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Column(name = "color_code", length = 7, nullable = false)
private String colorCode;
@ManyToOne
@JoinColumn(name = "expense_list_id", nullable = false)
@JsonBackReference
private ExpenseList expenseList;
}
@@ -0,0 +1,29 @@
package de.zendric.app.xpensely_server.model;
import java.util.List;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class XpenselyStandardCategories {
@Id
private Long id;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinColumn(name = "global_categories_id")
private List<XpenselyStandardCategory> categories;
}
@@ -0,0 +1,27 @@
package de.zendric.app.xpensely_server.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class XpenselyStandardCategory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Column(name = "color_code", length = 7, nullable = false)
private String colorCode;
}
@@ -0,0 +1,40 @@
package de.zendric.app.xpensely_server.preparation;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import de.zendric.app.xpensely_server.model.XpenselyStandardCategories;
import de.zendric.app.xpensely_server.model.XpenselyStandardCategory;
import de.zendric.app.xpensely_server.repo.XpenselyStandardCategoriesRepository;
@Component
public class DataInitializer implements CommandLineRunner {
@Autowired
private XpenselyStandardCategoriesRepository globalRepo;
@Override
public void run(String... args) throws Exception {
Optional<XpenselyStandardCategories> optional = globalRepo.findById(1L);
XpenselyStandardCategories global = optional.orElseGet(() -> {
XpenselyStandardCategories g = new XpenselyStandardCategories();
g.setId(1L);
return g;
});
List<XpenselyStandardCategory> categories = List.of(
new XpenselyStandardCategory(null, "Food", "#FF5733"),
new XpenselyStandardCategory(null, "Transportation", "#33C3FF"),
new XpenselyStandardCategory(null, "Entertainment", "#33FF57"),
new XpenselyStandardCategory(null, "Shopping", "#FF33A8"),
new XpenselyStandardCategory(null, "Household", "#FFC733"),
new XpenselyStandardCategory(null, "Other", "#9D33FF"));
global.setCategories(categories);
globalRepo.save(global);
}
}
@@ -0,0 +1,61 @@
package de.zendric.app.xpensely_server.preparation;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import de.zendric.app.xpensely_server.model.Expense;
import de.zendric.app.xpensely_server.model.ExpenseHistoryEntry;
import de.zendric.app.xpensely_server.model.HistoryEntryType;
import de.zendric.app.xpensely_server.repo.ExpenseHistoryRepository;
import de.zendric.app.xpensely_server.repo.ExpenseRepository;
/**
* One-time (idempotent) backfill for the history feature: fills
* Expense.lastModified from the expense date and creates a synthetic CREATED
* history entry for every expense that predates change logging. Both steps
* are no-ops on every startup after the first.
*/
@Component
public class HistoryBackfillRunner implements CommandLineRunner {
private final ExpenseRepository expenseRepository;
private final ExpenseHistoryRepository historyRepository;
public HistoryBackfillRunner(ExpenseRepository expenseRepository,
ExpenseHistoryRepository historyRepository) {
this.expenseRepository = expenseRepository;
this.historyRepository = historyRepository;
}
@Override
@Transactional
public void run(String... args) {
for (Expense expense : expenseRepository.findByLastModifiedIsNull()) {
expense.setLastModified(startOfDayOrNow(expense));
expenseRepository.save(expense);
}
Set<Long> loggedExpenseIds = new HashSet<>(historyRepository.findAllExpenseIds());
for (Expense expense : expenseRepository.findAll()) {
if (loggedExpenseIds.contains(expense.getId()))
continue;
ExpenseHistoryEntry entry = new ExpenseHistoryEntry();
entry.setExpenseList(expense.getExpenseList());
entry.setExpenseId(expense.getId());
entry.setExpenseTitle(expense.getTitle());
entry.setActor(expense.getOwner());
entry.setType(HistoryEntryType.CREATED);
entry.setTimestamp(startOfDayOrNow(expense));
historyRepository.save(entry);
}
}
private LocalDateTime startOfDayOrNow(Expense expense) {
return expense.getDate() == null ? LocalDateTime.now() : expense.getDate().atStartOfDay();
}
}
@@ -0,0 +1,23 @@
package de.zendric.app.xpensely_server.repo;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import de.zendric.app.xpensely_server.model.ExpenseHistoryEntry;
public interface ExpenseHistoryRepository extends JpaRepository<ExpenseHistoryEntry, Long> {
Page<ExpenseHistoryEntry> findByExpenseListIdOrderByTimestampDescIdDesc(Long expenseListId, Pageable pageable);
Page<ExpenseHistoryEntry> findByExpenseListOwnerIdOrExpenseListSharedWithIdOrderByTimestampDescIdDesc(
Long ownerId, Long sharedWithId, Pageable pageable);
@Query("select h.expenseId from ExpenseHistoryEntry h")
List<Long> findAllExpenseIds();
void deleteByExpenseListId(Long expenseListId);
}
@@ -3,13 +3,22 @@ package de.zendric.app.xpensely_server.repo;
import java.util.List; import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import de.zendric.app.xpensely_server.model.ExpenseList; import de.zendric.app.xpensely_server.model.ExpenseList;
@Repository @Repository
public interface ExpenseListRepository extends JpaRepository<ExpenseList, Long> { public interface ExpenseListRepository extends JpaRepository<ExpenseList, Long> {
List<ExpenseList> findByOwnerId(Long ownerId); List<ExpenseList> findByOwnerId(Long ownerId);
ExpenseList findByInviteCode(String inviteCode); ExpenseList findByInviteCode(String inviteCode);
@Query("SELECT el FROM ExpenseList el WHERE el.owner.id = :userId OR el.sharedWith.id = :userId")
List<ExpenseList> findByOwnerIdOrSharedWithId(@Param("userId") Long userId);
@Query("SELECT el FROM ExpenseList el WHERE el.owner.username = :username OR el.sharedWith.username = :username")
List<ExpenseList> findByOwnerUsernameOrSharedWithUsername(@Param("username") String username);
} }
@@ -10,4 +10,6 @@ import de.zendric.app.xpensely_server.model.Expense;
@Repository @Repository
public interface ExpenseRepository extends JpaRepository<Expense, Long> { public interface ExpenseRepository extends JpaRepository<Expense, Long> {
List<Expense> findAllByOrderByDateAsc(); List<Expense> findAllByOrderByDateAsc();
List<Expense> findByLastModifiedIsNull();
} }
@@ -14,4 +14,6 @@ public interface UserRepository extends JpaRepository<AppUser, Long> {
Optional<AppUser> findByGoogleId(String id); Optional<AppUser> findByGoogleId(String id);
Boolean existsByUsername(String username); Boolean existsByUsername(String username);
Boolean existsByGoogleId(String googleId);
} }
@@ -0,0 +1,10 @@
package de.zendric.app.xpensely_server.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import de.zendric.app.xpensely_server.model.XpenselyCustomCategory;
@Repository
public interface XpenselyCustomCategoryRepository extends JpaRepository<XpenselyCustomCategory, Long> {
}
@@ -0,0 +1,11 @@
package de.zendric.app.xpensely_server.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import de.zendric.app.xpensely_server.model.XpenselyStandardCategories;
@Repository
public interface XpenselyStandardCategoriesRepository extends JpaRepository<XpenselyStandardCategories, Long> {
}
@@ -0,0 +1,33 @@
package de.zendric.app.xpensely_server.security;
import de.zendric.app.xpensely_server.model.AppUser;
import de.zendric.app.xpensely_server.model.Exception.ResourceNotFoundException;
import de.zendric.app.xpensely_server.services.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
@Component
public class AuthenticatedUserResolver {
private final UserService userService;
public AuthenticatedUserResolver(UserService userService) {
this.userService = userService;
}
public AppUser resolveCurrentUser(Authentication authentication) {
if (authentication == null) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Not authenticated");
}
Jwt jwt = (Jwt) authentication.getPrincipal();
String googleId = jwt.getSubject();
try {
return userService.getUserByGoogleId(googleId);
} catch (IllegalArgumentException | ResourceNotFoundException e) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "User not registered");
}
}
}
@@ -0,0 +1,61 @@
package de.zendric.app.xpensely_server.security;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class RateLimitFilter extends OncePerRequestFilter {
private static final int REQUESTS_PER_MINUTE = 60;
private final Map<String, Bucket> buckets = new ConcurrentHashMap<>();
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String key = resolveKey(request);
Bucket bucket = buckets.computeIfAbsent(key, k -> newBucket());
if (bucket.tryConsume(1)) {
filterChain.doFilter(request, response);
} else {
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.getWriter().write("Rate limit exceeded");
}
}
private String resolveKey(HttpServletRequest request) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.getPrincipal() instanceof Jwt jwt) {
return "user:" + jwt.getSubject();
}
String ip = request.getHeader("X-Forwarded-For");
if (ip != null && !ip.isBlank()) {
return "ip:" + ip.split(",")[0].trim();
}
return "ip:" + request.getRemoteAddr();
}
private Bucket newBucket() {
return Bucket.builder()
.addLimit(Bandwidth.builder()
.capacity(REQUESTS_PER_MINUTE)
.refillGreedy(REQUESTS_PER_MINUTE, Duration.ofMinutes(1))
.build())
.build();
}
}
@@ -2,33 +2,38 @@ package de.zendric.app.xpensely_server.security;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.Customizer; import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter;
import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.SecurityFilterChain;
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
public class SecurityConfig { public class SecurityConfig {
// @Bean @Bean
// public SecurityFilterChain securityFilterChain(HttpSecurity http) throws @Profile("test") // Only enable this for testing
// Exception { public SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception {
// http.authorizeHttpRequests(auth -> auth http
// .anyRequest().permitAll()).csrf().disable(); .authorizeHttpRequests(auth -> auth
// ; .anyRequest().permitAll())
.csrf(csrf -> csrf.disable());
// return http.build(); return http.build();
// } }
@Bean @Bean
@Profile("!test")
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http http
.authorizeHttpRequests(auth -> auth .authorizeHttpRequests(auth -> auth
.requestMatchers("/api/version").permitAll()
.anyRequest().authenticated()) .anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2 .oauth2ResourceServer(oauth2 -> oauth2
.jwt(Customizer.withDefaults())) .jwt(Customizer.withDefaults()))
.oauth2Login(Customizer.withDefaults()) .addFilterAfter(new RateLimitFilter(), BearerTokenAuthenticationFilter.class)
.csrf().disable(); .csrf(csrf -> csrf.disable());
return http.build(); return http.build();
} }
@@ -0,0 +1,24 @@
package de.zendric.app.xpensely_server.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.zendric.app.xpensely_server.model.XpenselyStandardCategories;
import de.zendric.app.xpensely_server.repo.XpenselyStandardCategoriesRepository;
@Service
public class CategoryService {
private final XpenselyStandardCategoriesRepository standardCategoriesRepo;
@Autowired
public CategoryService(XpenselyStandardCategoriesRepository standardCategoriesRepo) {
this.standardCategoriesRepo = standardCategoriesRepo;
}
public XpenselyStandardCategories getDefaultCategories() {
return standardCategoriesRepo.findById(1L)
.orElseThrow(() -> new IllegalStateException("Standard categories not found"));
}
}
@@ -1,129 +1,91 @@
package de.zendric.app.xpensely_server.services; package de.zendric.app.xpensely_server.services;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import de.zendric.app.xpensely_server.model.AppUser; import de.zendric.app.xpensely_server.model.AppUser;
import de.zendric.app.xpensely_server.model.Expense; import de.zendric.app.xpensely_server.model.Expense;
import de.zendric.app.xpensely_server.model.ExpenseList; import de.zendric.app.xpensely_server.model.ExpenseList;
import de.zendric.app.xpensely_server.model.Exception.ResourceNotFoundException;
import de.zendric.app.xpensely_server.model.XpenselyCustomCategory;
import de.zendric.app.xpensely_server.repo.ExpenseListRepository; import de.zendric.app.xpensely_server.repo.ExpenseListRepository;
import de.zendric.app.xpensely_server.repo.ExpenseRepository; import de.zendric.app.xpensely_server.repo.ExpenseRepository;
import jakarta.persistence.EntityManager; import de.zendric.app.xpensely_server.repo.XpenselyCustomCategoryRepository;
@Service @Service
@Transactional @Transactional
public class ExpenseListService { public class ExpenseListService {
private ExpenseListRepository repository; private final ExpenseListRepository repository;
private final ExpenseRepository expenseRepository; private final ExpenseRepository expenseRepository;
private final XpenselyCustomCategoryRepository customCategoryRepository;
private final HistoryService historyService;
@Autowired public ExpenseListService(ExpenseListRepository repository, ExpenseRepository expenseRepository,
private EntityManager entityManager; XpenselyCustomCategoryRepository customCategoryRepository, HistoryService historyService) {
@Autowired
public ExpenseListService(ExpenseListRepository repository, ExpenseRepository expenseRepository) {
this.repository = repository; this.repository = repository;
this.expenseRepository = expenseRepository; this.expenseRepository = expenseRepository;
} this.customCategoryRepository = customCategoryRepository;
this.historyService = historyService;
public List<ExpenseList> getAllLists() {
return repository.findAll();
} }
public ExpenseList createList(ExpenseList list) { public ExpenseList createList(ExpenseList list) {
return repository.save(list); return repository.save(list);
} }
public void deleteList(Long id) { public void deleteById(Long id) {
historyService.deleteForList(id);
repository.deleteById(id); repository.deleteById(id);
} }
public void deleteById(Long id) { public ExpenseList renameList(Long id, String newName) {
repository.deleteById(id); ExpenseList list = repository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("ExpenseList not found with id: " + id));
list.setName(newName);
return repository.save(list);
}
public ExpenseList updateDefaultSplit(Long id, int percentage) {
ExpenseList list = repository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("ExpenseList not found with id: " + id));
list.setDefaultSplitPercentage(percentage);
return repository.save(list);
} }
public Optional<ExpenseList> findById(Long id) { public Optional<ExpenseList> findById(Long id) {
return repository.findById(id); return repository.findById(id);
} }
public Iterable<ExpenseList> findAll() {
return repository.findAll();
}
public ExpenseList save(ExpenseList expenseList) { public ExpenseList save(ExpenseList expenseList) {
return repository.save(expenseList); return repository.save(expenseList);
} }
public List<ExpenseList> findByUserId(Long id) { public List<ExpenseList> findByUserId(Long id) {
List<ExpenseList> allLists = repository.findAll(); return repository.findByOwnerIdOrSharedWithId(id);
List<ExpenseList> userSpecificList = new ArrayList<>();
for (ExpenseList expenseList : allLists) {
AppUser sharedWith = expenseList.getSharedWith();
if (expenseList.getOwner().getId().equals(id)) {
userSpecificList.add(expenseList);
} else {
if (sharedWith != null && sharedWith.getId().equals(id)) {
userSpecificList.add(expenseList);
}
}
}
return userSpecificList;
} }
public List<ExpenseList> findByUsername(String username) { public List<ExpenseList> findByUsername(String username) {
List<ExpenseList> allLists = repository.findAll(); return repository.findByOwnerUsernameOrSharedWithUsername(username);
List<ExpenseList> userSpecificList = new ArrayList<>();
for (ExpenseList expenseList : allLists) {
AppUser sharedWith = expenseList.getSharedWith();
if (expenseList.getOwner().getUsername().equals(username)) {
userSpecificList.add(expenseList);
} else {
if (sharedWith != null && sharedWith.getUsername().equals(username)) {
userSpecificList.add(expenseList);
}
}
}
return userSpecificList;
} }
public Expense addExpenseToList(Long expenseListId, Expense expense) { public Expense addExpenseToList(Long expenseListId, Expense expense, AppUser actor) {
// find expenseList
ExpenseList expenseList = repository.findById(expenseListId) ExpenseList expenseList = repository.findById(expenseListId)
.orElseThrow(() -> new RuntimeException("ExpenseList not found with id: " + expenseListId)); .orElseThrow(() -> new ResourceNotFoundException("ExpenseList not found with id: " + expenseListId));
// get all added expenses expense.setLastModified(LocalDateTime.now());
HashSet<Long> existingId = new HashSet<>();
for (Expense e : expenseList.getExpenses()) {
existingId.add(e.getId());
}
// add the new expense
expenseList.addExpense(expense); expenseList.addExpense(expense);
// save
repository.save(expenseList); repository.save(expenseList);
historyService.recordCreated(expenseList, expense, actor);
Expense newExpense = new Expense(); return expense;
for (Expense e : expenseList.getExpenses()) {
if (!existingId.contains(e.getId())) {
newExpense = e;
break;
}
}
return newExpense;
} }
public void deleteExpenseFromList(Long expenseListId, Long expenseId) { public void deleteExpenseFromList(Long expenseListId, Long expenseId, AppUser actor) {
ExpenseList expenseList = repository.findById(expenseListId) ExpenseList expenseList = repository.findById(expenseListId)
.orElseThrow(() -> new RuntimeException("ExpenseList not found with id: " + expenseListId)); .orElseThrow(() -> new ResourceNotFoundException("ExpenseList not found with id: " + expenseListId));
Expense expenseToRemove = null; Expense expenseToRemove = null;
for (Expense expense : expenseList.getExpenses()) { for (Expense expense : expenseList.getExpenses()) {
if (expense.getId().equals(expenseId)) { if (expense.getId().equals(expenseId)) {
@@ -131,17 +93,17 @@ public class ExpenseListService {
break; break;
} }
} }
if (expenseToRemove != null) { if (expenseToRemove == null) {
expenseList.removeExpense(expenseToRemove); throw new ResourceNotFoundException("Expense not found with id: " + expenseId);
} else {
throw new RuntimeException("Expense not found with id: " + expenseId);
} }
historyService.recordDeleted(expenseList, expenseToRemove, actor);
expenseList.removeExpense(expenseToRemove);
repository.save(expenseList); repository.save(expenseList);
} }
public String generateInviteCode(Long listId) { public String generateInviteCode(Long listId) {
ExpenseList list = repository.findById(listId) ExpenseList list = repository.findById(listId)
.orElseThrow(() -> new RuntimeException("List not found")); .orElseThrow(() -> new ResourceNotFoundException("List not found"));
String inviteCode; String inviteCode;
if (list.getInviteCode() == null || list.getInviteCodeExpiration().isBefore(LocalDateTime.now())) { if (list.getInviteCode() == null || list.getInviteCodeExpiration().isBefore(LocalDateTime.now())) {
@@ -161,9 +123,9 @@ public class ExpenseListService {
return repository.findByInviteCode(inviteCode); return repository.findByInviteCode(inviteCode);
} }
public Expense updateExpense(Long expenseListId, Expense updatedExpense) { public Expense updateExpense(Long expenseListId, Expense updatedExpense, AppUser actor) {
ExpenseList expenseList = repository.findById(expenseListId) ExpenseList expenseList = repository.findById(expenseListId)
.orElseThrow(() -> new IllegalArgumentException("ExpenseList not found")); .orElseThrow(() -> new ResourceNotFoundException("ExpenseList not found with id: " + expenseListId));
if (!expenseList.getExpenses().stream() if (!expenseList.getExpenses().stream()
.anyMatch(expense -> expense.getId().equals(updatedExpense.getId()))) { .anyMatch(expense -> expense.getId().equals(updatedExpense.getId()))) {
@@ -171,14 +133,59 @@ public class ExpenseListService {
} }
Expense existingExpense = expenseRepository.findById(updatedExpense.getId()) Expense existingExpense = expenseRepository.findById(updatedExpense.getId())
.orElseThrow(() -> new IllegalArgumentException("Expense not found")); .orElseThrow(() -> new ResourceNotFoundException("Expense not found with id: " + updatedExpense.getId()));
Expense before = snapshot(existingExpense);
existingExpense.setTitle(updatedExpense.getTitle()); existingExpense.setTitle(updatedExpense.getTitle());
existingExpense.setAmount(updatedExpense.getAmount()); existingExpense.setAmount(updatedExpense.getAmount());
existingExpense.setPersonalUseAmount(updatedExpense.getPersonalUseAmount()); existingExpense.setPersonalUseAmount(updatedExpense.getPersonalUseAmount());
existingExpense.setOtherPersonAmount(updatedExpense.getOtherPersonAmount()); existingExpense.setOtherPersonAmount(updatedExpense.getOtherPersonAmount());
existingExpense.setDate(updatedExpense.getDate()); existingExpense.setDate(updatedExpense.getDate());
existingExpense.setOwner(updatedExpense.getOwner()); existingExpense.setOwner(updatedExpense.getOwner());
existingExpense.setCategory(updatedExpense.getCategory());
existingExpense.setSplitMode(updatedExpense.getSplitMode());
existingExpense.setSplitPercentage(updatedExpense.getSplitPercentage());
existingExpense.setLastModified(LocalDateTime.now());
return expenseRepository.save(existingExpense); Expense saved = expenseRepository.save(existingExpense);
historyService.recordUpdated(expenseList, before, saved, actor);
return saved;
} }
/** Detached copy of the mutable fields, taken before applying an update. */
private Expense snapshot(Expense e) {
Expense copy = new Expense();
copy.setId(e.getId());
copy.setTitle(e.getTitle());
copy.setAmount(e.getAmount());
copy.setPersonalUseAmount(e.getPersonalUseAmount());
copy.setOtherPersonAmount(e.getOtherPersonAmount());
copy.setCategory(e.getCategory());
copy.setSplitMode(e.getSplitMode());
copy.setSplitPercentage(e.getSplitPercentage());
copy.setDate(e.getDate());
copy.setOwner(e.getOwner());
return copy;
}
// TODO implement API for this
public XpenselyCustomCategory addCustomCategory(Long expenseListId, XpenselyCustomCategory customCategory) {
ExpenseList expenseList = repository.findById(expenseListId)
.orElseThrow(() -> new ResourceNotFoundException("Expense List not found"));
customCategory.setExpenseList(expenseList);
return customCategoryRepository.save(customCategory);
}
// TODO implement API for this
public void deleteCustomCategory(Long expenseListId, Long categoryId) {
XpenselyCustomCategory category = customCategoryRepository.findById(categoryId)
.orElseThrow(() -> new ResourceNotFoundException("Custom Category not found"));
if (!category.getExpenseList().getId().equals(expenseListId)) {
throw new IllegalArgumentException("Category does not belong to the specified Expense List");
}
customCategoryRepository.delete(category);
}
} }
@@ -0,0 +1,147 @@
package de.zendric.app.xpensely_server.services;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tools.jackson.core.JacksonException;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.ObjectMapper;
import de.zendric.app.xpensely_server.model.AppUser;
import de.zendric.app.xpensely_server.model.DTO.HistoryEntryDto;
import de.zendric.app.xpensely_server.model.DTO.HistoryPageDto;
import de.zendric.app.xpensely_server.model.DTO.RecentHistoryEntryDto;
import de.zendric.app.xpensely_server.model.Expense;
import de.zendric.app.xpensely_server.model.ExpenseHistoryEntry;
import de.zendric.app.xpensely_server.model.ExpenseList;
import de.zendric.app.xpensely_server.model.FieldChange;
import de.zendric.app.xpensely_server.model.HistoryEntryType;
import de.zendric.app.xpensely_server.repo.ExpenseHistoryRepository;
@Service
@Transactional
public class HistoryService {
private final ExpenseHistoryRepository historyRepository;
private final ObjectMapper objectMapper;
public HistoryService(ExpenseHistoryRepository historyRepository, ObjectMapper objectMapper) {
this.historyRepository = historyRepository;
this.objectMapper = objectMapper;
}
public void recordCreated(ExpenseList list, Expense expense, AppUser actor) {
historyRepository.save(baseEntry(list, expense, actor, HistoryEntryType.CREATED));
}
public void recordUpdated(ExpenseList list, Expense before, Expense after, AppUser actor) {
List<FieldChange> changes = diff(before, after);
if (changes.isEmpty())
return;
ExpenseHistoryEntry entry = baseEntry(list, after, actor, HistoryEntryType.UPDATED);
try {
entry.setChanges(objectMapper.writeValueAsString(changes));
} catch (JacksonException e) {
throw new IllegalStateException("Failed to serialize history changes", e);
}
historyRepository.save(entry);
}
public void recordDeleted(ExpenseList list, Expense expense, AppUser actor) {
historyRepository.save(baseEntry(list, expense, actor, HistoryEntryType.DELETED));
}
public void deleteForList(Long listId) {
historyRepository.deleteByExpenseListId(listId);
}
public List<FieldChange> diff(Expense before, Expense after) {
List<FieldChange> changes = new ArrayList<>();
addIfChanged(changes, "title", before.getTitle(), after.getTitle());
addIfChanged(changes, "amount", before.getAmount(), after.getAmount());
addIfChanged(changes, "personalUseAmount", before.getPersonalUseAmount(), after.getPersonalUseAmount());
addIfChanged(changes, "otherPersonAmount", before.getOtherPersonAmount(), after.getOtherPersonAmount());
addIfChanged(changes, "category", before.getCategory(), after.getCategory());
addIfChanged(changes, "splitMode",
before.getSplitMode() == null ? null : before.getSplitMode().name(),
after.getSplitMode() == null ? null : after.getSplitMode().name());
addIfChanged(changes, "splitPercentage", before.getSplitPercentage(), after.getSplitPercentage());
addIfChanged(changes, "date", before.getDate(), after.getDate());
addIfChanged(changes, "owner",
before.getOwner() == null ? null : before.getOwner().getUsername(),
after.getOwner() == null ? null : after.getOwner().getUsername());
return changes;
}
private ExpenseHistoryEntry baseEntry(ExpenseList list, Expense expense, AppUser actor, HistoryEntryType type) {
ExpenseHistoryEntry entry = new ExpenseHistoryEntry();
entry.setExpenseList(list);
entry.setExpenseId(expense.getId());
entry.setExpenseTitle(expense.getTitle());
entry.setActor(actor);
entry.setType(type);
entry.setTimestamp(LocalDateTime.now());
return entry;
}
private void addIfChanged(List<FieldChange> changes, String field, Object oldVal, Object newVal) {
if (!Objects.equals(oldVal, newVal)) {
changes.add(new FieldChange(field,
oldVal == null ? null : String.valueOf(oldVal),
newVal == null ? null : String.valueOf(newVal)));
}
}
@Transactional(readOnly = true)
public HistoryPageDto getHistory(Long listId, int page, int size) {
int cappedSize = Math.min(Math.max(size, 1), 100);
Page<ExpenseHistoryEntry> result = historyRepository
.findByExpenseListIdOrderByTimestampDescIdDesc(listId,
PageRequest.of(Math.max(page, 0), cappedSize));
List<HistoryEntryDto> entries = result.getContent().stream().map(this::toDto).toList();
return new HistoryPageDto(entries, result.hasNext());
}
@Transactional(readOnly = true)
public List<RecentHistoryEntryDto> getRecentForUser(AppUser user, int limit) {
int cappedLimit = Math.min(Math.max(limit, 1), 20);
Page<ExpenseHistoryEntry> result = historyRepository
.findByExpenseListOwnerIdOrExpenseListSharedWithIdOrderByTimestampDescIdDesc(
user.getId(), user.getId(), PageRequest.of(0, cappedLimit));
return result.getContent().stream()
.map(e -> new RecentHistoryEntryDto(
e.getType().name(),
e.getActor() == null ? null : e.getActor().getUsername(),
e.getExpenseTitle(),
e.getTimestamp(),
e.getExpenseList().getId(),
e.getExpenseList().getName()))
.toList();
}
private HistoryEntryDto toDto(ExpenseHistoryEntry entry) {
List<FieldChange> changes = List.of();
if (entry.getChanges() != null) {
try {
changes = objectMapper.readValue(entry.getChanges(),
new TypeReference<List<FieldChange>>() {
});
} catch (JacksonException e) {
throw new IllegalStateException("Corrupt history changes for entry " + entry.getId(), e);
}
}
return new HistoryEntryDto(
entry.getType().name(),
entry.getActor() == null ? null : entry.getActor().getUsername(),
entry.getExpenseTitle(),
entry.getTimestamp(),
changes);
}
}
@@ -1,12 +1,12 @@
package de.zendric.app.xpensely_server.services; package de.zendric.app.xpensely_server.services;
import java.util.List; import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import de.zendric.app.xpensely_server.model.AppUser; import de.zendric.app.xpensely_server.model.AppUser;
import de.zendric.app.xpensely_server.model.UsernameAlreadyExistsException; import de.zendric.app.xpensely_server.model.Exception.GoogleAccountAlreadyRegisteredException;
import de.zendric.app.xpensely_server.model.Exception.ResourceNotFoundException;
import de.zendric.app.xpensely_server.repo.UserRepository; import de.zendric.app.xpensely_server.repo.UserRepository;
@Service @Service
@@ -22,43 +22,40 @@ public class UserService {
} }
public AppUser createUser(AppUser user) { public AppUser createUser(AppUser user) {
if (Boolean.TRUE.equals(userRepository.existsByUsername(user.getUsername()))) { if (Boolean.TRUE.equals(userRepository.existsByGoogleId(user.getGoogleId()))) {
throw new UsernameAlreadyExistsException("Username already exists"); throw new GoogleAccountAlreadyRegisteredException(
"An account already exists for this Google account");
} }
// Usernames are not unique — identity is the Google account (googleId).
return userRepository.save(user);
}
public AppUser updateUsername(Long userId, String newUsername) {
AppUser user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + userId));
user.setUsername(newUsername);
return userRepository.save(user); return userRepository.save(user);
} }
public AppUser getUser(Long id) { public AppUser getUser(Long id) {
Optional<AppUser> user = userRepository.findById(id); return userRepository.findById(id)
if (user.isPresent()) { .orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + id));
return user.get();
} else
return null;
} }
public AppUser deleteUserById(Long id) { public AppUser deleteUserById(Long id) {
Optional<AppUser> user = userRepository.findById(id); AppUser user = userRepository.findById(id)
if (user.isPresent()) { .orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + id));
userRepository.deleteById(id); userRepository.deleteById(id);
return user.get(); return user;
} else
return null;
} }
public AppUser getUserByName(String username) { public AppUser getUserByName(String username) {
Optional<AppUser> optUser = userRepository.findByUsername(username); return userRepository.findByUsername(username)
if (optUser.isPresent()) { .orElseThrow(() -> new ResourceNotFoundException("User not found: " + username));
return optUser.get();
} else
return null;
} }
public AppUser getUserByGoogleId(String id) { public AppUser getUserByGoogleId(String id) {
Optional<AppUser> optUser = userRepository.findByGoogleId(id); return userRepository.findByGoogleId(id)
if (optUser.isPresent()) { .orElseThrow(() -> new ResourceNotFoundException("User not found with Google ID: " + id));
return optUser.get();
} else
return null;
} }
} }
@@ -3,8 +3,6 @@ spring.application.name=XpenselyServer
#Security #Security
spring.security.enabled=false spring.security.enabled=false
spring.security.oauth2.client.registration.google.client-id=${GOOGLE_CLIENT_ID}
spring.security.oauth2.client.registration.google.client-secret=${GOOGLE_CLIENT_SECRET}
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://accounts.google.com spring.security.oauth2.resourceserver.jwt.issuer-uri=https://accounts.google.com
# PostgreSQL Configuration # PostgreSQL Configuration
@@ -0,0 +1,47 @@
package de.zendric.app.xpensely_Server;
import de.zendric.app.xpensely_server.model.ExpenseList;
import de.zendric.app.xpensely_server.repo.ExpenseListRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
@DataJpaTest
class ExpenseListRepositoryTest {
@Autowired
private ExpenseListRepository expenseListRepository;
@Test
void saveAndFindById_returnsExpenseList() {
ExpenseList list = new ExpenseList();
list.setName("Groceries");
ExpenseList saved = expenseListRepository.save(list);
Optional<ExpenseList> found = expenseListRepository.findById(saved.getId());
assertTrue(found.isPresent());
assertEquals("Groceries", found.get().getName());
}
@Test
void findById_nonExistentId_returnsEmpty() {
Optional<ExpenseList> found = expenseListRepository.findById(999L);
assertTrue(found.isEmpty());
}
@Test
void delete_removesFromRepository() {
ExpenseList list = new ExpenseList();
list.setName("To Delete");
ExpenseList saved = expenseListRepository.save(list);
expenseListRepository.deleteById(saved.getId());
assertTrue(expenseListRepository.findById(saved.getId()).isEmpty());
}
}
@@ -1,13 +0,0 @@
package de.zendric.app.xpensely_Server;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class XpenselyServerApplicationTests {
@Test
void contextLoads() {
}
}
@@ -0,0 +1,24 @@
package de.zendric.app.xpensely_Server.config;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtException;
/**
* Provides a no-op JwtDecoder so the application context starts without
* fetching Google's JWKS endpoint. Tests use SecurityMockMvcRequestPostProcessors.jwt()
* which populates the SecurityContext directly and never calls this decoder.
*/
@TestConfiguration
public class TestJwtDecoderConfig {
@Bean
@Primary
public JwtDecoder jwtDecoder() {
return token -> {
throw new JwtException("Real JWT validation is disabled in integration tests — use jwt() post-processor");
};
}
}
@@ -0,0 +1,132 @@
package de.zendric.app.xpensely_Server.controller;
import de.zendric.app.xpensely_server.controller.AppUserController;
import de.zendric.app.xpensely_server.model.AppUser;
import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver;
import de.zendric.app.xpensely_server.services.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.security.oauth2.server.resource.autoconfigure.servlet.OAuth2ResourceServerAutoConfiguration;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(value = AppUserController.class, excludeAutoConfiguration = {
OAuth2ResourceServerAutoConfiguration.class
})
@AutoConfigureMockMvc(addFilters = false)
@ActiveProfiles("test")
class AppUserControllerTest {
@Autowired MockMvc mockMvc;
@MockitoBean UserService userService;
@MockitoBean AuthenticatedUserResolver authenticatedUserResolver;
@Test
void createUser_blankUsername_returns400WithFieldError() throws Exception {
mockMvc.perform(post("/api/users/createUser")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"\",\"googleId\":\"gid123\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.username").exists());
}
@Test
void createUser_invalidUsernamePattern_returns400() throws Exception {
mockMvc.perform(post("/api/users/createUser")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"hello world!\",\"googleId\":\"gid123\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.username").exists());
}
@Test
void createUser_usernameTooShort_returns400() throws Exception {
mockMvc.perform(post("/api/users/createUser")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"ab\",\"googleId\":\"gid123\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.username").exists());
}
@Test
void createUser_blankGoogleId_returns400() throws Exception {
mockMvc.perform(post("/api/users/createUser")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"validuser\",\"googleId\":\"\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.googleId").exists());
}
// --- Authorization tests ---
@Test
void getUser_differentUser_returns403() throws Exception {
AppUser self = new AppUser(); self.setId(1L);
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(self);
mockMvc.perform(get("/api/users").param("id", "99"))
.andExpect(status().isForbidden());
}
@Test
void getUser_sameUser_returns200() throws Exception {
AppUser self = new AppUser(); self.setId(1L);
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(self);
when(userService.getUser(1L)).thenReturn(self);
mockMvc.perform(get("/api/users").param("id", "1"))
.andExpect(status().isOk());
}
@Test
void deleteUser_differentUser_returns403() throws Exception {
AppUser self = new AppUser(); self.setId(1L);
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(self);
mockMvc.perform(delete("/api/users").param("id", "99"))
.andExpect(status().isForbidden());
}
// --- Rename username ---
@Test
void updateUsername_valid_returns200WithUpdatedUser() throws Exception {
AppUser self = new AppUser(); self.setId(1L); self.setUsername("old");
AppUser updated = new AppUser(); updated.setId(1L); updated.setUsername("newname");
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(self);
when(userService.updateUsername(1L, "newname")).thenReturn(updated);
mockMvc.perform(put("/api/users/username")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"newname\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.username").value("newname"));
}
@Test
void updateUsername_invalidPattern_returns400() throws Exception {
mockMvc.perform(put("/api/users/username")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"bad name!\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.username").exists());
}
@Test
void updateUsername_tooShort_returns400() throws Exception {
mockMvc.perform(put("/api/users/username")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"ab\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.username").exists());
}
}
@@ -0,0 +1,453 @@
package de.zendric.app.xpensely_Server.controller;
import de.zendric.app.xpensely_server.controller.ExpenseListController;
import de.zendric.app.xpensely_server.model.AppUser;
import de.zendric.app.xpensely_server.model.DTO.HistoryPageDto;
import de.zendric.app.xpensely_server.model.DTO.RecentHistoryEntryDto;
import de.zendric.app.xpensely_server.model.Expense;
import de.zendric.app.xpensely_server.model.ExpenseList;
import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver;
import de.zendric.app.xpensely_server.services.CategoryService;
import de.zendric.app.xpensely_server.services.ExpenseListService;
import de.zendric.app.xpensely_server.services.HistoryService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.security.oauth2.server.resource.autoconfigure.servlet.OAuth2ResourceServerAutoConfiguration;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(value = ExpenseListController.class, excludeAutoConfiguration = {
OAuth2ResourceServerAutoConfiguration.class
})
@AutoConfigureMockMvc(addFilters = false)
@ActiveProfiles("test")
class ExpenseListControllerTest {
@Autowired MockMvc mockMvc;
@MockitoBean ExpenseListService expenseListService;
@MockitoBean CategoryService categoryService;
@MockitoBean AuthenticatedUserResolver authenticatedUserResolver;
@MockitoBean HistoryService historyService;
// --- Validation tests ---
@Test
void addExpense_blankTitle_returns400() throws Exception {
mockMvc.perform(post("/api/expenselist/1/add")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"\",\"owner\":\"alice\",\"amount\":10.0,\"date\":\"2026-05-04\",\"category\":\"Food\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.title").exists());
}
// Quick Add creates stub expenses (amount 0, no category); updating such a
// stub must be allowed so the user can fill in the details afterwards.
@Test
void updateExpense_quickAddStub_zeroAmountAndNoCategory_returns200() throws Exception {
AppUser owner = new AppUser(); owner.setId(1L); owner.setUsername("alice");
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(owner);
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(owner);
when(expenseListService.updateExpense(eq(1L), any(Expense.class), eq(owner)))
.thenAnswer(inv -> inv.getArgument(1));
mockMvc.perform(put("/api/expenselist/1/update")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"id\":42,\"title\":\"Groceries\",\"ownerName\":\"alice\",\"amount\":0.0,"
+ "\"personalUseAmount\":0.0,\"otherPersonAmount\":0.0,\"date\":\"2026-07-06\"}"))
.andExpect(status().isOk());
}
@Test
void updateExpense_blankCategory_isStoredAsNull() throws Exception {
AppUser owner = new AppUser(); owner.setId(1L); owner.setUsername("alice");
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(owner);
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(owner);
when(expenseListService.updateExpense(eq(1L), any(Expense.class), eq(owner)))
.thenAnswer(inv -> inv.getArgument(1));
mockMvc.perform(put("/api/expenselist/1/update")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"id\":42,\"title\":\"Groceries\",\"ownerName\":\"alice\",\"amount\":0.0,"
+ "\"personalUseAmount\":0.0,\"otherPersonAmount\":0.0,\"date\":\"2026-07-06\",\"category\":\"\"}"))
.andExpect(status().isOk());
org.mockito.ArgumentCaptor<Expense> captor = org.mockito.ArgumentCaptor.forClass(Expense.class);
org.mockito.Mockito.verify(expenseListService).updateExpense(eq(1L), captor.capture(), eq(owner));
org.assertj.core.api.Assertions.assertThat(captor.getValue().getCategory()).isNull();
}
@Test
void updateExpense_negativeAmount_returns400() throws Exception {
mockMvc.perform(put("/api/expenselist/1/update")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"id\":42,\"title\":\"Groceries\",\"ownerName\":\"alice\",\"amount\":-5.0,"
+ "\"personalUseAmount\":0.0,\"otherPersonAmount\":0.0,\"date\":\"2026-07-06\",\"category\":\"Food\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.amount").exists());
}
@Test
void addExpense_negativeAmount_returns400() throws Exception {
mockMvc.perform(post("/api/expenselist/1/add")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"Lunch\",\"owner\":\"alice\",\"amount\":-5.0,\"date\":\"2026-05-04\",\"category\":\"Food\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.amount").exists());
}
@Test
void addExpense_nullDate_returns400() throws Exception {
mockMvc.perform(post("/api/expenselist/1/add")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"Lunch\",\"owner\":\"alice\",\"amount\":10.0,\"category\":\"Food\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.date").exists());
}
@Test
void acceptInvite_blankCode_returns400() throws Exception {
mockMvc.perform(post("/api/expenselist/accept-invite")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"inviteCode\":\"\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.inviteCode").exists());
}
@Test
void acceptInvite_wrongCodeLength_returns400() throws Exception {
mockMvc.perform(post("/api/expenselist/accept-invite")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"inviteCode\":\"ABC\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.inviteCode").exists());
}
// --- Authorization tests ---
@Test
void getById_authenticatedUserNotMember_returns403() throws Exception {
AppUser owner = new AppUser(); owner.setId(1L);
AppUser requester = new AppUser(); requester.setId(2L);
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(owner);
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(requester);
mockMvc.perform(get("/api/expenselist/byId").param("id", "1"))
.andExpect(status().isForbidden());
}
@Test
void getById_authenticatedUserIsOwner_returns200() throws Exception {
AppUser owner = new AppUser(); owner.setId(1L);
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(owner);
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(owner);
mockMvc.perform(get("/api/expenselist/byId").param("id", "1"))
.andExpect(status().isOk());
}
@Test
void deleteList_nonOwner_returns403() throws Exception {
AppUser owner = new AppUser(); owner.setId(1L);
AppUser nonOwner = new AppUser(); nonOwner.setId(2L);
ExpenseList list = new ExpenseList(); list.setId(5L); list.setOwner(owner);
when(expenseListService.findById(5L)).thenReturn(Optional.of(list));
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(nonOwner);
mockMvc.perform(delete("/api/expenselist/5"))
.andExpect(status().isForbidden());
}
@Test
void getMine_returnsCurrentUserLists() throws Exception {
AppUser user = new AppUser(); user.setId(3L);
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(user);
when(expenseListService.findByUserId(3L)).thenReturn(List.of(new ExpenseList()));
mockMvc.perform(get("/api/expenselist/mine"))
.andExpect(status().isOk());
}
@Test
void create_returns500_onUnexpectedServiceError() throws Exception {
AppUser user = new AppUser();
user.setId(1L);
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(user);
when(categoryService.getDefaultCategories()).thenThrow(new RuntimeException("db down"));
mockMvc.perform(post("/api/expenselist/create")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Groceries\"}"))
.andExpect(status().isInternalServerError());
}
@Test
void create_returns400_whenNameIsBlank() throws Exception {
AppUser user = new AppUser();
user.setId(1L);
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(user);
mockMvc.perform(post("/api/expenselist/create")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.name").exists());
}
@Test
void create_returns400_whenBodyIsEmpty() throws Exception {
AppUser user = new AppUser();
user.setId(1L);
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(user);
mockMvc.perform(post("/api/expenselist/create")
.contentType(MediaType.APPLICATION_JSON)
.content("{}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.name").exists());
}
// --- Owner resolution within list members ---
@Test
void addExpense_ownerNotAListMember_returns400() throws Exception {
AppUser member = new AppUser(); member.setId(1L); member.setUsername("alice");
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(member);
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(member);
mockMvc.perform(post("/api/expenselist/1/add")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"Lunch\",\"owner\":\"ghost\",\"amount\":10.0,\"date\":\"2026-05-04\",\"category\":\"Food\"}"))
.andExpect(status().isBadRequest());
}
@Test
void addExpense_ownerIsAListMember_returns201() throws Exception {
AppUser member = new AppUser(); member.setId(1L); member.setUsername("alice");
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(member);
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(member);
when(expenseListService.addExpenseToList(eq(1L), any(), any())).thenReturn(new Expense());
mockMvc.perform(post("/api/expenselist/1/add")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"Lunch\",\"owner\":\"alice\",\"amount\":10.0,\"date\":\"2026-05-04\",\"category\":\"Food\"}"))
.andExpect(status().isCreated());
}
// --- Rename list ---
@Test
void renameList_owner_returns200WithRenamedList() throws Exception {
AppUser owner = new AppUser(); owner.setId(1L);
ExpenseList list = new ExpenseList(); list.setId(5L); list.setOwner(owner);
ExpenseList renamed = new ExpenseList(); renamed.setId(5L); renamed.setName("Groceries");
when(expenseListService.findById(5L)).thenReturn(Optional.of(list));
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(owner);
when(expenseListService.renameList(5L, "Groceries")).thenReturn(renamed);
mockMvc.perform(put("/api/expenselist/5/rename")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Groceries\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Groceries"));
}
@Test
void renameList_nonOwner_returns403() throws Exception {
AppUser owner = new AppUser(); owner.setId(1L);
AppUser nonOwner = new AppUser(); nonOwner.setId(2L);
ExpenseList list = new ExpenseList(); list.setId(5L); list.setOwner(owner);
when(expenseListService.findById(5L)).thenReturn(Optional.of(list));
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(nonOwner);
mockMvc.perform(put("/api/expenselist/5/rename")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Groceries\"}"))
.andExpect(status().isForbidden());
}
@Test
void renameList_blankName_returns400() throws Exception {
mockMvc.perform(put("/api/expenselist/5/rename")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.name").exists());
}
@Test
void renameList_notFound_returns404() throws Exception {
AppUser owner = new AppUser(); owner.setId(1L);
when(expenseListService.findById(9L)).thenReturn(Optional.empty());
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(owner);
mockMvc.perform(put("/api/expenselist/9/rename")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Groceries\"}"))
.andExpect(status().isNotFound());
}
// --- Default split ---
@Test
void updateDefaultSplit_setsPercentageForMember() throws Exception {
AppUser owner = new AppUser(); owner.setId(1L);
ExpenseList list = new ExpenseList(); list.setId(5L); list.setOwner(owner);
when(expenseListService.findById(5L)).thenReturn(Optional.of(list));
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(owner);
when(expenseListService.updateDefaultSplit(5L, 60)).thenReturn(list);
mockMvc.perform(put("/api/expenselist/5/default-split")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"percentage\":60}"))
.andExpect(status().isOk());
org.mockito.Mockito.verify(expenseListService).updateDefaultSplit(5L, 60);
}
@Test
void updateDefaultSplit_nonMember_returns403() throws Exception {
AppUser owner = new AppUser(); owner.setId(1L);
AppUser stranger = new AppUser(); stranger.setId(2L);
ExpenseList list = new ExpenseList(); list.setId(5L); list.setOwner(owner);
when(expenseListService.findById(5L)).thenReturn(Optional.of(list));
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(stranger);
mockMvc.perform(put("/api/expenselist/5/default-split")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"percentage\":60}"))
.andExpect(status().isForbidden());
}
// --- Duplicate-username invite guard ---
@Test
void acceptInvite_sameUsernameAsOwner_returns409() throws Exception {
AppUser owner = new AppUser(); owner.setId(1L); owner.setUsername("cedric");
AppUser joiner = new AppUser(); joiner.setId(2L); joiner.setUsername("cedric");
ExpenseList list = new ExpenseList();
list.setId(1L);
list.setOwner(owner);
list.setInviteCodeExpiration(LocalDateTime.now().plusHours(1));
when(expenseListService.findByInviteCode("ABC123")).thenReturn(list);
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(joiner);
mockMvc.perform(post("/api/expenselist/accept-invite")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"inviteCode\":\"ABC123\"}"))
.andExpect(status().isConflict());
}
// --- History endpoint ---
@Test
void getHistory_member_returns200WithPage() throws Exception {
AppUser owner = new AppUser(); owner.setId(1L); owner.setUsername("alice");
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(owner);
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(owner);
when(historyService.getHistory(1L, 0, 30))
.thenReturn(new HistoryPageDto(List.of(), false));
mockMvc.perform(get("/api/expenselist/1/history"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.entries").isArray())
.andExpect(jsonPath("$.hasMore").value(false));
}
@Test
void getHistory_nonMember_returns403() throws Exception {
AppUser owner = new AppUser(); owner.setId(1L);
AppUser stranger = new AppUser(); stranger.setId(2L);
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(owner);
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(stranger);
mockMvc.perform(get("/api/expenselist/1/history"))
.andExpect(status().isForbidden());
}
@Test
void getHistory_unknownList_returns404() throws Exception {
when(expenseListService.findById(99L)).thenReturn(Optional.empty());
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(new AppUser());
mockMvc.perform(get("/api/expenselist/99/history"))
.andExpect(status().isNotFound());
}
// --- Recent history endpoint ---
@Test
void getRecentHistory_returnsArrayWithListInfo() throws Exception {
AppUser user = new AppUser(); user.setId(1L); user.setUsername("alice");
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(user);
when(historyService.getRecentForUser(user, 4)).thenReturn(List.of(
new RecentHistoryEntryDto("UPDATED", "alice", "Groceries",
LocalDateTime.of(2026, 7, 6, 12, 0), 10L, "Trip to Rome")));
mockMvc.perform(get("/api/expenselist/history/recent"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].type").value("UPDATED"))
.andExpect(jsonPath("$[0].actorUsername").value("alice"))
.andExpect(jsonPath("$[0].expenseTitle").value("Groceries"))
.andExpect(jsonPath("$[0].listId").value(10))
.andExpect(jsonPath("$[0].listName").value("Trip to Rome"));
}
@Test
void getRecentHistory_passesLimitParam() throws Exception {
AppUser user = new AppUser(); user.setId(1L);
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(user);
when(historyService.getRecentForUser(user, 10)).thenReturn(List.of());
mockMvc.perform(get("/api/expenselist/history/recent").param("limit", "10"))
.andExpect(status().isOk())
.andExpect(jsonPath("$").isEmpty());
}
@Test
void getRecentHistory_doesNotClashWithPerListHistoryRoute() throws Exception {
// /api/expenselist/1/history must still hit the per-list handler.
AppUser owner = new AppUser(); owner.setId(1L); owner.setUsername("alice");
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(owner);
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(owner);
when(historyService.getHistory(1L, 0, 30))
.thenReturn(new HistoryPageDto(List.of(), false));
mockMvc.perform(get("/api/expenselist/1/history"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.entries").isArray());
}
}
@@ -0,0 +1,92 @@
package de.zendric.app.xpensely_Server.preparation;
import java.time.LocalDate;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import de.zendric.app.xpensely_server.model.AppUser;
import de.zendric.app.xpensely_server.model.Expense;
import de.zendric.app.xpensely_server.model.ExpenseHistoryEntry;
import de.zendric.app.xpensely_server.model.ExpenseList;
import de.zendric.app.xpensely_server.model.HistoryEntryType;
import de.zendric.app.xpensely_server.preparation.HistoryBackfillRunner;
import de.zendric.app.xpensely_server.repo.ExpenseHistoryRepository;
import de.zendric.app.xpensely_server.repo.ExpenseRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class HistoryBackfillRunnerTest {
@Mock ExpenseRepository expenseRepository;
@Mock ExpenseHistoryRepository historyRepository;
@InjectMocks
HistoryBackfillRunner runner;
private Expense expense(long id, LocalDate date) {
AppUser owner = new AppUser(); owner.setId(1L); owner.setUsername("alice");
ExpenseList list = new ExpenseList(); list.setId(10L);
Expense e = new Expense();
e.setId(id);
e.setTitle("Groceries");
e.setDate(date);
e.setOwner(owner);
e.setExpenseList(list);
return e;
}
@Test
void fillsLastModifiedFromDate_forExpensesMissingIt() throws Exception {
Expense e = expense(42L, LocalDate.of(2026, 6, 1));
when(expenseRepository.findByLastModifiedIsNull()).thenReturn(List.of(e));
when(expenseRepository.findAll()).thenReturn(List.of(e));
when(historyRepository.findAllExpenseIds()).thenReturn(List.of(42L));
runner.run();
assertThat(e.getLastModified()).isEqualTo(LocalDate.of(2026, 6, 1).atStartOfDay());
verify(expenseRepository).save(e);
}
@Test
void createsSyntheticCreatedEntry_forExpensesWithoutHistory() throws Exception {
Expense e = expense(42L, LocalDate.of(2026, 6, 1));
when(expenseRepository.findByLastModifiedIsNull()).thenReturn(List.of());
when(expenseRepository.findAll()).thenReturn(List.of(e));
when(historyRepository.findAllExpenseIds()).thenReturn(List.of());
runner.run();
ArgumentCaptor<ExpenseHistoryEntry> captor = ArgumentCaptor.forClass(ExpenseHistoryEntry.class);
verify(historyRepository).save(captor.capture());
ExpenseHistoryEntry entry = captor.getValue();
assertThat(entry.getType()).isEqualTo(HistoryEntryType.CREATED);
assertThat(entry.getExpenseId()).isEqualTo(42L);
assertThat(entry.getExpenseTitle()).isEqualTo("Groceries");
assertThat(entry.getActor().getUsername()).isEqualTo("alice");
assertThat(entry.getTimestamp()).isEqualTo(LocalDate.of(2026, 6, 1).atStartOfDay());
}
@Test
void isIdempotent_skipsExpensesThatAlreadyHaveHistory() throws Exception {
Expense e = expense(42L, LocalDate.of(2026, 6, 1));
when(expenseRepository.findByLastModifiedIsNull()).thenReturn(List.of());
when(expenseRepository.findAll()).thenReturn(List.of(e));
when(historyRepository.findAllExpenseIds()).thenReturn(List.of(42L));
runner.run();
verify(historyRepository, never()).save(any());
}
}
@@ -0,0 +1,80 @@
package de.zendric.app.xpensely_Server.security;
import de.zendric.app.xpensely_server.model.AppUser;
import de.zendric.app.xpensely_server.model.Exception.ResourceNotFoundException;
import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver;
import de.zendric.app.xpensely_server.services.UserService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.web.server.ResponseStatusException;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class AuthenticatedUserResolverTest {
UserService userService;
AuthenticatedUserResolver resolver;
@BeforeEach
void setUp() {
userService = mock(UserService.class);
resolver = new AuthenticatedUserResolver(userService);
}
@Test
void resolveCurrentUser_validJwt_returnsAppUser() {
Jwt jwt = Jwt.withTokenValue("token")
.header("alg", "RS256")
.subject("google-id-123")
.build();
JwtAuthenticationToken auth = new JwtAuthenticationToken(jwt);
AppUser user = new AppUser();
user.setId(1L);
user.setGoogleId("google-id-123");
when(userService.getUserByGoogleId("google-id-123")).thenReturn(user);
AppUser result = resolver.resolveCurrentUser(auth);
assertEquals(user, result);
}
@Test
void resolveCurrentUser_userNotFound_throws403() {
Jwt jwt = Jwt.withTokenValue("token")
.header("alg", "RS256")
.subject("unknown-id")
.build();
JwtAuthenticationToken auth = new JwtAuthenticationToken(jwt);
when(userService.getUserByGoogleId("unknown-id"))
.thenThrow(new ResourceNotFoundException("User not found with Google ID: unknown-id"));
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
() -> resolver.resolveCurrentUser(auth));
assertEquals(HttpStatus.FORBIDDEN, ex.getStatusCode());
}
@Test
void resolveCurrentUser_userServiceThrows_throws403() {
Jwt jwt = Jwt.withTokenValue("token")
.header("alg", "RS256")
.subject("gone-id")
.build();
JwtAuthenticationToken auth = new JwtAuthenticationToken(jwt);
when(userService.getUserByGoogleId("gone-id")).thenThrow(new IllegalArgumentException("not found"));
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
() -> resolver.resolveCurrentUser(auth));
assertEquals(HttpStatus.FORBIDDEN, ex.getStatusCode());
}
@Test
void resolveCurrentUser_nullAuthentication_throws403() {
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
() -> resolver.resolveCurrentUser(null));
assertEquals(HttpStatus.FORBIDDEN, ex.getStatusCode());
}
}
@@ -0,0 +1,89 @@
package de.zendric.app.xpensely_Server.security;
import de.zendric.app.xpensely_server.security.RateLimitFilter;
import jakarta.servlet.FilterChain;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
class RateLimitFilterTest {
RateLimitFilter filter;
FilterChain chain;
@BeforeEach
void setUp() {
filter = new RateLimitFilter();
chain = mock(FilterChain.class);
}
@Test
void allowsRequestUnderLimit() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRemoteAddr("1.2.3.4");
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, chain);
verify(chain, times(1)).doFilter(request, response);
assertEquals(200, response.getStatus());
}
@Test
void blocksRequestOverLimit() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRemoteAddr("5.6.7.8");
for (int i = 0; i < 60; i++) {
filter.doFilter(request, new MockHttpServletResponse(), chain);
}
MockHttpServletResponse blockedResponse = new MockHttpServletResponse();
filter.doFilter(request, blockedResponse, chain);
assertEquals(429, blockedResponse.getStatus());
verify(chain, times(60)).doFilter(eq(request), any());
}
@Test
void differentIpsBucketedSeparately() throws Exception {
MockHttpServletRequest req1 = new MockHttpServletRequest();
req1.setRemoteAddr("10.0.0.1");
MockHttpServletRequest req2 = new MockHttpServletRequest();
req2.setRemoteAddr("10.0.0.2");
for (int i = 0; i < 60; i++) {
filter.doFilter(req1, new MockHttpServletResponse(), chain);
}
MockHttpServletResponse response2 = new MockHttpServletResponse();
filter.doFilter(req2, response2, chain);
assertEquals(200, response2.getStatus());
}
@Test
void prefersXForwardedForHeader() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRemoteAddr("192.168.1.1");
request.addHeader("X-Forwarded-For", "203.0.113.5, 10.0.0.1");
for (int i = 0; i < 60; i++) {
filter.doFilter(request, new MockHttpServletResponse(), chain);
}
MockHttpServletResponse blocked = new MockHttpServletResponse();
filter.doFilter(request, blocked, chain);
assertEquals(429, blocked.getStatus());
MockHttpServletRequest directRequest = new MockHttpServletRequest();
directRequest.setRemoteAddr("192.168.1.1");
MockHttpServletResponse directResponse = new MockHttpServletResponse();
filter.doFilter(directRequest, directResponse, chain);
assertEquals(200, directResponse.getStatus());
}
}
@@ -0,0 +1,153 @@
package de.zendric.app.xpensely_Server.security;
import de.zendric.app.xpensely_Server.config.TestJwtDecoderConfig;
import de.zendric.app.xpensely_server.model.AppUser;
import de.zendric.app.xpensely_server.repo.ExpenseListRepository;
import de.zendric.app.xpensely_server.repo.UserRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Full-stack integration tests for the security filter chain.
* Runs with the real securityFilterChain (not the test permit-all chain).
* Uses an H2 in-memory database (see application-integration.properties).
* JWT validation is bypassed via jwt() post-processor — no real Google token needed.
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
@ActiveProfiles("integration")
@Import(TestJwtDecoderConfig.class)
class SecurityFilterChainIntegrationTest {
@Autowired MockMvc mockMvc;
@Autowired UserRepository userRepository;
@Autowired ExpenseListRepository expenseListRepository;
private static final String KNOWN_GOOGLE_ID = "google-integration-test-123";
private static final String UNKNOWN_GOOGLE_ID = "google-unknown-999";
@BeforeEach
void setUp() {
expenseListRepository.deleteAll();
userRepository.deleteAll();
AppUser user = new AppUser();
user.setGoogleId(KNOWN_GOOGLE_ID);
user.setUsername("integrationtestuser");
userRepository.save(user);
}
@AfterEach
void tearDown() {
expenseListRepository.deleteAll();
userRepository.deleteAll();
}
// --- Public endpoints ---
@Test
void versionEndpoint_noAuth_returns200() throws Exception {
mockMvc.perform(get("/api/version"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.version").exists());
}
// --- Unauthenticated access (no JWT) → 401 ---
@Test
void byGoogleId_noJwt_returns401() throws Exception {
mockMvc.perform(get("/api/users/byGoogleId").param("id", KNOWN_GOOGLE_ID))
.andExpect(status().isUnauthorized());
}
@Test
void createUser_noJwt_returns401() throws Exception {
mockMvc.perform(post("/api/users/createUser")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"newuser\",\"googleId\":\"new-google-id\"}"))
.andExpect(status().isUnauthorized());
}
@Test
void expenseListMine_noJwt_returns401() throws Exception {
mockMvc.perform(get("/api/expenselist/mine"))
.andExpect(status().isUnauthorized());
}
// --- Authenticated, user exists in DB → success ---
@Test
void byGoogleId_withJwt_userInDb_returns200() throws Exception {
mockMvc.perform(get("/api/users/byGoogleId")
.param("id", KNOWN_GOOGLE_ID)
.with(jwt().jwt(j -> j.subject(KNOWN_GOOGLE_ID))))
.andExpect(status().isOk());
}
@Test
void expenseListMine_withJwt_userInDb_emptyList_returns204() throws Exception {
mockMvc.perform(get("/api/expenselist/mine")
.with(jwt().jwt(j -> j.subject(KNOWN_GOOGLE_ID))))
.andExpect(status().isNoContent());
}
@Test
void createUser_withJwt_validBody_returns201() throws Exception {
mockMvc.perform(post("/api/users/createUser")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"newuser123\",\"googleId\":\"brand-new-google-id\"}")
.with(jwt().jwt(j -> j.subject("brand-new-google-id"))))
.andExpect(status().isCreated());
}
// --- Authenticated, user NOT in DB → 403 ---
@Test
void byGoogleId_withJwt_userNotInDb_returns403() throws Exception {
mockMvc.perform(get("/api/users/byGoogleId")
.param("id", UNKNOWN_GOOGLE_ID)
.with(jwt().jwt(j -> j.subject(UNKNOWN_GOOGLE_ID))))
.andExpect(status().isForbidden());
}
@Test
void expenseListMine_withJwt_userNotInDb_returns403() throws Exception {
mockMvc.perform(get("/api/expenselist/mine")
.with(jwt().jwt(j -> j.subject(UNKNOWN_GOOGLE_ID))))
.andExpect(status().isForbidden());
}
// --- Authenticated, accessing another user's resource → 403 ---
@Test
void byGoogleId_withJwt_differentId_returns403() throws Exception {
mockMvc.perform(get("/api/users/byGoogleId")
.param("id", UNKNOWN_GOOGLE_ID)
.with(jwt().jwt(j -> j.subject(KNOWN_GOOGLE_ID))))
.andExpect(status().isForbidden());
}
// --- Validation errors still return 400 with JWT ---
@Test
void createUser_withJwt_blankUsername_returns400() throws Exception {
mockMvc.perform(post("/api/users/createUser")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"\",\"googleId\":\"some-id\"}")
.with(jwt().jwt(j -> j.subject("some-id"))))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.username").exists());
}
}
@@ -0,0 +1,157 @@
package de.zendric.app.xpensely_Server.services;
import de.zendric.app.xpensely_server.model.AppUser;
import de.zendric.app.xpensely_server.model.Expense;
import de.zendric.app.xpensely_server.model.ExpenseList;
import de.zendric.app.xpensely_server.model.SplitMode;
import de.zendric.app.xpensely_server.repo.ExpenseListRepository;
import de.zendric.app.xpensely_server.repo.ExpenseRepository;
import de.zendric.app.xpensely_server.repo.XpenselyCustomCategoryRepository;
import de.zendric.app.xpensely_server.services.ExpenseListService;
import de.zendric.app.xpensely_server.services.HistoryService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.never;
@ExtendWith(MockitoExtension.class)
class ExpenseListServiceTest {
@Mock ExpenseListRepository repository;
@Mock ExpenseRepository expenseRepository;
@Mock XpenselyCustomCategoryRepository customCategoryRepository;
@Mock HistoryService historyService;
@InjectMocks
ExpenseListService service;
@Test
void findByUserId_usesRepositoryQuery_notFindAll() {
AppUser owner = new AppUser(); owner.setId(1L);
ExpenseList list = new ExpenseList(); list.setId(10L); list.setOwner(owner);
when(repository.findByOwnerIdOrSharedWithId(1L)).thenReturn(List.of(list));
List<ExpenseList> result = service.findByUserId(1L);
assertThat(result).hasSize(1);
verify(repository).findByOwnerIdOrSharedWithId(1L);
verify(repository, never()).findAll();
}
@Test
void findByUsername_usesRepositoryQuery_notFindAll() {
AppUser owner = new AppUser(); owner.setId(1L); owner.setUsername("alice");
ExpenseList list = new ExpenseList(); list.setId(10L); list.setOwner(owner);
when(repository.findByOwnerUsernameOrSharedWithUsername("alice")).thenReturn(List.of(list));
List<ExpenseList> result = service.findByUsername("alice");
assertThat(result).hasSize(1);
verify(repository).findByOwnerUsernameOrSharedWithUsername("alice");
verify(repository, never()).findAll();
}
private Expense makeExpense(Long id, String title, double amount) {
Expense e = new Expense();
e.setId(id);
e.setTitle(title);
e.setAmount(amount);
e.setPersonalUseAmount(0.0);
e.setOtherPersonAmount(0.0);
e.setDate(LocalDate.of(2026, 7, 1));
return e;
}
@Test
void addExpenseToList_setsLastModified_andRecordsCreated() {
AppUser actor = new AppUser(); actor.setId(1L);
ExpenseList list = new ExpenseList(); list.setId(10L);
list.setExpenses(new ArrayList<>());
when(repository.findById(10L)).thenReturn(Optional.of(list));
Expense expense = makeExpense(null, "Lunch", 10.0);
service.addExpenseToList(10L, expense, actor);
assertThat(expense.getLastModified()).isNotNull();
verify(historyService).recordCreated(list, expense, actor);
}
@Test
void updateExpense_setsLastModified_andRecordsUpdatedWithBeforeSnapshot() {
AppUser actor = new AppUser(); actor.setId(1L);
ExpenseList list = new ExpenseList(); list.setId(10L);
Expense existing = makeExpense(42L, "Old title", 12.0);
list.setExpenses(new ArrayList<>(List.of(existing)));
when(repository.findById(10L)).thenReturn(Optional.of(list));
when(expenseRepository.findById(42L)).thenReturn(Optional.of(existing));
when(expenseRepository.save(any(Expense.class))).thenAnswer(inv -> inv.getArgument(0));
Expense updated = makeExpense(42L, "New title", 15.0);
service.updateExpense(10L, updated, actor);
assertThat(existing.getLastModified()).isNotNull();
org.mockito.ArgumentCaptor<Expense> beforeCaptor =
org.mockito.ArgumentCaptor.forClass(Expense.class);
verify(historyService).recordUpdated(eq(list), beforeCaptor.capture(), eq(existing), eq(actor));
assertThat(beforeCaptor.getValue().getTitle()).isEqualTo("Old title");
assertThat(beforeCaptor.getValue().getAmount()).isEqualTo(12.0);
}
@Test
void updateExpense_persistsSplitModeAndPercentage() {
AppUser actor = new AppUser(); actor.setId(1L);
ExpenseList list = new ExpenseList(); list.setId(10L); list.setOwner(actor);
Expense existing = makeExpense(5L, "Groceries", 100.0);
list.setExpenses(new ArrayList<>(List.of(existing)));
Expense incoming = makeExpense(5L, "Groceries", 100.0);
incoming.setDate(LocalDate.now());
incoming.setOwner(list.getOwner());
incoming.setSplitMode(SplitMode.PERCENTAGE);
incoming.setSplitPercentage(70);
when(repository.findById(10L)).thenReturn(Optional.of(list));
when(expenseRepository.findById(5L)).thenReturn(Optional.of(existing));
when(expenseRepository.save(any(Expense.class))).thenAnswer(inv -> inv.getArgument(0));
Expense saved = service.updateExpense(10L, incoming, actor);
assertThat(saved.getSplitMode()).isEqualTo(SplitMode.PERCENTAGE);
assertThat(saved.getSplitPercentage()).isEqualTo(70);
}
@Test
void deleteById_deletesHistoryEntriesBeforeDeletingList() {
service.deleteById(10L);
org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(historyService, repository);
inOrder.verify(historyService).deleteForList(10L);
inOrder.verify(repository).deleteById(10L);
}
@Test
void deleteExpenseFromList_recordsDeleted() {
AppUser actor = new AppUser(); actor.setId(1L);
ExpenseList list = new ExpenseList(); list.setId(10L);
Expense existing = makeExpense(42L, "Taxi", 9.0);
list.setExpenses(new ArrayList<>(List.of(existing)));
when(repository.findById(10L)).thenReturn(Optional.of(list));
service.deleteExpenseFromList(10L, 42L, actor);
verify(historyService).recordDeleted(eq(list), any(Expense.class), eq(actor));
}
}
@@ -0,0 +1,298 @@
package de.zendric.app.xpensely_Server.services;
import java.time.LocalDate;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import tools.jackson.databind.ObjectMapper;
import de.zendric.app.xpensely_server.model.AppUser;
import de.zendric.app.xpensely_server.model.DTO.HistoryPageDto;
import de.zendric.app.xpensely_server.model.DTO.RecentHistoryEntryDto;
import de.zendric.app.xpensely_server.model.Expense;
import de.zendric.app.xpensely_server.model.ExpenseHistoryEntry;
import de.zendric.app.xpensely_server.model.ExpenseList;
import de.zendric.app.xpensely_server.model.FieldChange;
import de.zendric.app.xpensely_server.model.HistoryEntryType;
import de.zendric.app.xpensely_server.model.SplitMode;
import de.zendric.app.xpensely_server.repo.ExpenseHistoryRepository;
import de.zendric.app.xpensely_server.services.HistoryService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class HistoryServiceTest {
@Mock ExpenseHistoryRepository historyRepository;
@Spy ObjectMapper objectMapper = new ObjectMapper();
@InjectMocks
HistoryService service;
private AppUser user(long id, String name) {
AppUser u = new AppUser();
u.setId(id);
u.setUsername(name);
return u;
}
private Expense expense(String title, double amount, String category, LocalDate date, AppUser owner) {
Expense e = new Expense();
e.setId(42L);
e.setTitle(title);
e.setAmount(amount);
e.setPersonalUseAmount(0.0);
e.setOtherPersonAmount(0.0);
e.setCategory(category);
e.setDate(date);
e.setOwner(owner);
return e;
}
@Test
void diff_detectsChangedFields_withOldAndNewValues() {
AppUser alice = user(1L, "alice");
Expense before = expense("Groceries", 12.0, "Food", LocalDate.of(2026, 7, 1), alice);
Expense after = expense("Groceries", 15.5, "Household", LocalDate.of(2026, 7, 1), alice);
List<FieldChange> changes = service.diff(before, after);
assertThat(changes).containsExactlyInAnyOrder(
new FieldChange("amount", "12.0", "15.5"),
new FieldChange("category", "Food", "Household"));
}
@Test
void diff_ownerChange_isReportedByUsername() {
Expense before = expense("Taxi", 9.0, null, LocalDate.of(2026, 7, 1), user(1L, "alice"));
Expense after = expense("Taxi", 9.0, null, LocalDate.of(2026, 7, 1), user(2L, "ben"));
List<FieldChange> changes = service.diff(before, after);
assertThat(changes).containsExactly(new FieldChange("owner", "alice", "ben"));
}
@Test
void diff_reportsSplitModeAndPercentageChanges() {
Expense before = new Expense();
before.setSplitMode(SplitMode.DETAILED);
before.setSplitPercentage(null);
Expense after = new Expense();
after.setSplitMode(SplitMode.PERCENTAGE);
after.setSplitPercentage(70);
List<FieldChange> changes = service.diff(before, after);
assertThat(changes).contains(new FieldChange("splitMode", "DETAILED", "PERCENTAGE"));
assertThat(changes).contains(new FieldChange("splitPercentage", null, "70"));
}
@Test
void diff_nullToValue_isReported() {
Expense before = expense("Taxi", 9.0, null, LocalDate.of(2026, 7, 1), user(1L, "alice"));
Expense after = expense("Taxi", 9.0, "Transportation", LocalDate.of(2026, 7, 1), user(1L, "alice"));
assertThat(service.diff(before, after))
.containsExactly(new FieldChange("category", null, "Transportation"));
}
@Test
void recordUpdated_noChanges_writesNothing() {
AppUser alice = user(1L, "alice");
Expense same = expense("Groceries", 12.0, "Food", LocalDate.of(2026, 7, 1), alice);
ExpenseList list = new ExpenseList();
list.setId(5L);
service.recordUpdated(list, same, same, alice);
verify(historyRepository, never()).save(any());
}
@Test
void recordUpdated_savesEntryWithJsonChanges() {
AppUser alice = user(1L, "alice");
ExpenseList list = new ExpenseList();
list.setId(5L);
Expense before = expense("Groceries", 12.0, "Food", LocalDate.of(2026, 7, 1), alice);
Expense after = expense("Groceries", 15.5, "Food", LocalDate.of(2026, 7, 1), alice);
service.recordUpdated(list, before, after, alice);
ArgumentCaptor<ExpenseHistoryEntry> captor = ArgumentCaptor.forClass(ExpenseHistoryEntry.class);
verify(historyRepository).save(captor.capture());
ExpenseHistoryEntry entry = captor.getValue();
assertThat(entry.getType()).isEqualTo(HistoryEntryType.UPDATED);
assertThat(entry.getExpenseId()).isEqualTo(42L);
assertThat(entry.getExpenseTitle()).isEqualTo("Groceries");
assertThat(entry.getActor()).isEqualTo(alice);
assertThat(entry.getExpenseList()).isEqualTo(list);
assertThat(entry.getTimestamp()).isNotNull();
assertThat(entry.getChanges())
.isEqualTo("[{\"field\":\"amount\",\"old\":\"12.0\",\"new\":\"15.5\"}]");
}
@Test
void recordCreated_savesEntryWithoutChanges() {
AppUser alice = user(1L, "alice");
ExpenseList list = new ExpenseList();
list.setId(5L);
Expense e = expense("Groceries", 12.0, "Food", LocalDate.of(2026, 7, 1), alice);
service.recordCreated(list, e, alice);
ArgumentCaptor<ExpenseHistoryEntry> captor = ArgumentCaptor.forClass(ExpenseHistoryEntry.class);
verify(historyRepository).save(captor.capture());
assertThat(captor.getValue().getType()).isEqualTo(HistoryEntryType.CREATED);
assertThat(captor.getValue().getChanges()).isNull();
}
@Test
void recordDeleted_savesEntry() {
AppUser alice = user(1L, "alice");
ExpenseList list = new ExpenseList();
list.setId(5L);
Expense e = expense("Taxi", 9.0, null, LocalDate.of(2026, 7, 1), alice);
service.recordDeleted(list, e, alice);
ArgumentCaptor<ExpenseHistoryEntry> captor = ArgumentCaptor.forClass(ExpenseHistoryEntry.class);
verify(historyRepository).save(captor.capture());
assertThat(captor.getValue().getType()).isEqualTo(HistoryEntryType.DELETED);
assertThat(captor.getValue().getExpenseTitle()).isEqualTo("Taxi");
}
@Test
void getHistory_mapsEntriesToDto_andParsesChangesJson() {
ExpenseHistoryEntry entry = new ExpenseHistoryEntry();
entry.setType(HistoryEntryType.UPDATED);
entry.setActor(user(1L, "alice"));
entry.setExpenseTitle("Groceries");
entry.setTimestamp(java.time.LocalDateTime.of(2026, 7, 6, 14, 31));
entry.setChanges("[{\"field\":\"amount\",\"old\":\"12.0\",\"new\":\"15.5\"}]");
when(historyRepository.findByExpenseListIdOrderByTimestampDescIdDesc(eq(5L), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of(entry), PageRequest.of(0, 30), 31));
HistoryPageDto page = service.getHistory(5L, 0, 30);
assertThat(page.hasMore()).isTrue();
assertThat(page.entries()).hasSize(1);
assertThat(page.entries().get(0).type()).isEqualTo("UPDATED");
assertThat(page.entries().get(0).actorUsername()).isEqualTo("alice");
assertThat(page.entries().get(0).changes())
.containsExactly(new FieldChange("amount", "12.0", "15.5"));
}
@Test
void getHistory_capsPageSizeAt100() {
when(historyRepository.findByExpenseListIdOrderByTimestampDescIdDesc(eq(5L), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of()));
service.getHistory(5L, 0, 5000);
ArgumentCaptor<Pageable> captor = ArgumentCaptor.forClass(Pageable.class);
verify(historyRepository).findByExpenseListIdOrderByTimestampDescIdDesc(eq(5L), captor.capture());
assertThat(captor.getValue().getPageSize()).isEqualTo(100);
}
@Test
void getHistory_nullChanges_yieldsEmptyList() {
ExpenseHistoryEntry entry = new ExpenseHistoryEntry();
entry.setType(HistoryEntryType.CREATED);
entry.setActor(user(1L, "alice"));
entry.setExpenseTitle("Groceries");
entry.setTimestamp(java.time.LocalDateTime.of(2026, 7, 6, 14, 31));
when(historyRepository.findByExpenseListIdOrderByTimestampDescIdDesc(eq(5L), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of(entry)));
HistoryPageDto page = service.getHistory(5L, 0, 30);
assertThat(page.entries().get(0).changes()).isEmpty();
}
private ExpenseHistoryEntry historyEntry(Long id, ExpenseList list, AppUser actor,
HistoryEntryType type, String title, java.time.LocalDateTime timestamp) {
ExpenseHistoryEntry e = new ExpenseHistoryEntry();
e.setId(id);
e.setExpenseList(list);
e.setActor(actor);
e.setType(type);
e.setExpenseTitle(title);
e.setTimestamp(timestamp);
return e;
}
@Test
void getRecentForUser_mapsEntriesWithListIdAndName() {
AppUser alice = user(1L, "alice");
ExpenseList list = new ExpenseList();
list.setId(10L);
list.setName("Trip to Rome");
ExpenseHistoryEntry entry = historyEntry(100L, list, alice,
HistoryEntryType.UPDATED, "Groceries", java.time.LocalDateTime.of(2026, 7, 6, 12, 0));
when(historyRepository
.findByExpenseListOwnerIdOrExpenseListSharedWithIdOrderByTimestampDescIdDesc(
eq(1L), eq(1L), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of(entry)));
List<RecentHistoryEntryDto> result = service.getRecentForUser(alice, 4);
assertThat(result).containsExactly(new RecentHistoryEntryDto(
"UPDATED", "alice", "Groceries",
java.time.LocalDateTime.of(2026, 7, 6, 12, 0), 10L, "Trip to Rome"));
}
@Test
void getRecentForUser_nullActor_mapsToNullUsername() {
AppUser alice = user(1L, "alice");
ExpenseList list = new ExpenseList();
list.setId(10L);
list.setName("Trip to Rome");
ExpenseHistoryEntry entry = historyEntry(100L, list, null,
HistoryEntryType.CREATED, "Taxi", java.time.LocalDateTime.of(2026, 7, 6, 12, 0));
when(historyRepository
.findByExpenseListOwnerIdOrExpenseListSharedWithIdOrderByTimestampDescIdDesc(
eq(1L), eq(1L), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of(entry)));
List<RecentHistoryEntryDto> result = service.getRecentForUser(alice, 4);
assertThat(result.get(0).actorUsername()).isNull();
}
@Test
void getRecentForUser_clampsLimitBetween1And20() {
AppUser alice = user(1L, "alice");
when(historyRepository
.findByExpenseListOwnerIdOrExpenseListSharedWithIdOrderByTimestampDescIdDesc(
eq(1L), eq(1L), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of()));
service.getRecentForUser(alice, 500);
verify(historyRepository)
.findByExpenseListOwnerIdOrExpenseListSharedWithIdOrderByTimestampDescIdDesc(
1L, 1L, PageRequest.of(0, 20));
service.getRecentForUser(alice, 0);
verify(historyRepository)
.findByExpenseListOwnerIdOrExpenseListSharedWithIdOrderByTimestampDescIdDesc(
1L, 1L, PageRequest.of(0, 1));
}
}
@@ -0,0 +1,75 @@
package de.zendric.app.xpensely_Server.services;
import de.zendric.app.xpensely_server.model.AppUser;
import de.zendric.app.xpensely_server.model.Exception.ResourceNotFoundException;
import de.zendric.app.xpensely_server.repo.UserRepository;
import de.zendric.app.xpensely_server.services.UserService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
UserRepository userRepository;
@InjectMocks
UserService userService;
@Test
void getUserByName_throwsResourceNotFound_whenUserMissing() {
when(userRepository.findByUsername("ghost")).thenReturn(Optional.empty());
assertThatThrownBy(() -> userService.getUserByName("ghost"))
.isInstanceOf(ResourceNotFoundException.class)
.hasMessageContaining("ghost");
}
@Test
void getUserByName_returnsUser_whenFound() {
AppUser user = new AppUser();
user.setId(1L);
user.setUsername("alice");
when(userRepository.findByUsername("alice")).thenReturn(Optional.of(user));
AppUser result = userService.getUserByName("alice");
assertThat(result.getUsername()).isEqualTo("alice");
}
@Test
void getUser_throwsResourceNotFound_whenIdMissing() {
when(userRepository.findById(99L)).thenReturn(Optional.empty());
assertThatThrownBy(() -> userService.getUser(99L))
.isInstanceOf(ResourceNotFoundException.class)
.hasMessageContaining("99");
}
@Test
void deleteUserById_throwsResourceNotFound_whenIdMissing() {
when(userRepository.findById(99L)).thenReturn(Optional.empty());
assertThatThrownBy(() -> userService.deleteUserById(99L))
.isInstanceOf(ResourceNotFoundException.class)
.hasMessageContaining("99");
}
@Test
void getUserByGoogleId_throwsResourceNotFound_whenMissing() {
when(userRepository.findByGoogleId("gid-404")).thenReturn(Optional.empty());
assertThatThrownBy(() -> userService.getUserByGoogleId("gid-404"))
.isInstanceOf(ResourceNotFoundException.class)
.hasMessageContaining("gid-404");
}
}
@@ -0,0 +1,5 @@
build.artifact=xpensely-server
build.group=de.zendric.app
build.name=XpenselyServer
build.time=2026-01-01T00\:00\:00.000Z
build.version=test
@@ -0,0 +1,10 @@
# H2 in-memory database replaces PostgreSQL for integration tests
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;MODE=PostgreSQL
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop
# Placeholder URI — TestJwtDecoderConfig overrides the decoder bean so this URI is never fetched
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://placeholder.invalid/jwks