Compare commits
10 Commits
024b3880e7
...
3d456f2f81
| Author | SHA1 | Date | |
|---|---|---|---|
| 3d456f2f81 | |||
| b1324e3048 | |||
| 8b96433b1a | |||
| f0de751da4 | |||
| 9b95741292 | |||
| 2bd229cc5e | |||
| 797d482ebf | |||
| 906b60d264 | |||
| 68783cc892 | |||
| 9c91da9f30 |
@@ -1,5 +1,6 @@
|
|||||||
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/
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,166 +0,0 @@
|
|||||||
# Security Hardening Design — XpenselyServer
|
|
||||||
**Date:** 2026-05-04
|
|
||||||
**Scope:** Input validation, authorization enforcement, rate limiting
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Problem Statement
|
|
||||||
|
|
||||||
The XpenselyServer has three security gaps:
|
|
||||||
|
|
||||||
1. **No input validation** — request bodies are accepted without any field constraints, allowing null fields, negative amounts, oversized strings, and malformed data to reach the database layer.
|
|
||||||
2. **Authorization bypass** — every endpoint trusts caller-supplied user IDs from query params or request bodies rather than the authenticated JWT. Any authenticated user can read or destroy another user's expense lists.
|
|
||||||
3. **No rate limiting** — no protection against brute-force or abuse of sensitive endpoints (invite generation, account creation, invite acceptance).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Section 1 — Input Validation
|
|
||||||
|
|
||||||
### Dependency
|
|
||||||
Add `spring-boot-starter-validation` to `pom.xml`.
|
|
||||||
|
|
||||||
### Request Model Constraints
|
|
||||||
|
|
||||||
**`AppUserCreateRequest`**
|
|
||||||
- `username`: `@NotBlank @Size(min=3, max=30) @Pattern(regexp="^[a-zA-Z0-9_.-]+$")`
|
|
||||||
- `googleId`: `@NotBlank`
|
|
||||||
|
|
||||||
**`ExpenseInput`**
|
|
||||||
- `title`: `@NotBlank @Size(max=100)`
|
|
||||||
- `owner`: `@NotBlank`
|
|
||||||
- `amount`: `@NotNull @DecimalMin("0.01")`
|
|
||||||
- `date`: `@NotNull`
|
|
||||||
- `category`: `@NotBlank`
|
|
||||||
|
|
||||||
**`ExpenseChangeRequest`** — same constraints as `ExpenseInput` for the corresponding fields.
|
|
||||||
|
|
||||||
**`InviteRequest`**
|
|
||||||
- `inviteCode`: `@NotBlank @Size(min=6, max=6)`
|
|
||||||
- `userId` field removed (derived from JWT — see Section 2)
|
|
||||||
|
|
||||||
### Controller Changes
|
|
||||||
Add `@Valid` to every `@RequestBody` parameter in `AppUserController` and `ExpenseListController`.
|
|
||||||
|
|
||||||
### Error Handling
|
|
||||||
Add a `@ControllerAdvice` class `GlobalExceptionHandler` that:
|
|
||||||
- Catches `MethodArgumentNotValidException` → returns `400 Bad Request` with a map of `{ field: errorMessage }` pairs
|
|
||||||
- Catches `IllegalArgumentException` → returns `400 Bad Request` with the exception message
|
|
||||||
|
|
||||||
This replaces the current pattern of returning `500 INTERNAL_SERVER_ERROR` or `417 EXPECTATION_FAILED` for validation failures.
|
|
||||||
|
|
||||||
### Cleanup
|
|
||||||
Remove the stray `@Id` and `@GeneratedValue` JPA annotations from `ExpenseInput` — it is a DTO, not an entity.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Section 2 — Authorization Model
|
|
||||||
|
|
||||||
### Core Principle
|
|
||||||
Stop trusting caller-supplied user IDs. Derive the authenticated user from the JWT on every request.
|
|
||||||
|
|
||||||
### New Component: `AuthenticatedUserResolver`
|
|
||||||
A `@Component` with a single method:
|
|
||||||
```java
|
|
||||||
AppUser resolveCurrentUser(Authentication auth)
|
|
||||||
```
|
|
||||||
- Extracts the `sub` claim (Google ID) from the JWT
|
|
||||||
- Calls `UserService.getUserByGoogleId(sub)` to return the `AppUser`
|
|
||||||
- Throws `ResponseStatusException(403)` if no user is found for the JWT subject
|
|
||||||
|
|
||||||
### Endpoint Changes
|
|
||||||
|
|
||||||
| Endpoint | Change |
|
|
||||||
|---|---|
|
|
||||||
| `GET /api/expenselist/all` | **Removed** — no legitimate non-admin use case |
|
|
||||||
| `GET /api/expenselist/byUser?userId=X` | **Replaced** by `GET /api/expenselist/mine` — returns lists for the JWT user, no param |
|
|
||||||
| `GET /api/expenselist/byUsername?username=X` | **Removed** — redundant with `/mine` |
|
|
||||||
| `GET /api/expenselist/byId?id=X` | **Guard added** — 403 if authenticated user is neither owner nor sharedWith |
|
|
||||||
| `DELETE /api/expenselist/{id}` | **Guard added** — 403 if authenticated user is not the owner |
|
|
||||||
| `POST /api/expenselist/{id}/add` | **Guard added** — 403 if authenticated user is not owner or sharedWith |
|
|
||||||
| `PUT /api/expenselist/{id}/update` | **Guard added** — 403 if authenticated user is not owner or sharedWith |
|
|
||||||
| `DELETE /api/expenselist/{id}/delete` | **Guard added** — 403 if authenticated user is not owner or sharedWith |
|
|
||||||
| `POST /api/expenselist/{listId}/invite` | **Guard added** — 403 if authenticated user is not the owner |
|
|
||||||
| `POST /api/expenselist/accept-invite` | **`userId` removed from body** — derived from JWT instead |
|
|
||||||
| `GET /api/users?id=X` | **Guard added** — 403 if id doesn't match JWT user's id |
|
|
||||||
| `GET /api/users/byGoogleId?id=X` | **Guard added** — 403 if id doesn't match JWT sub |
|
|
||||||
| `DELETE /api/users?id=X` | **Guard added** — 403 if id doesn't match JWT user's id |
|
|
||||||
|
|
||||||
### Ownership Check Helper
|
|
||||||
Each guard is implemented as a private method in its controller (2–3 lines):
|
|
||||||
```java
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Test Profile
|
|
||||||
The `@Profile("test")` security chain in `SecurityConfig` is untouched. Existing tests continue to work without authentication.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Section 3 — Rate Limiting
|
|
||||||
|
|
||||||
### Dependency
|
|
||||||
Add `bucket4j-core` to `pom.xml`. In-memory storage — no external cache needed for single-instance deployment.
|
|
||||||
|
|
||||||
### Implementation
|
|
||||||
A `RateLimitFilter` extending `OncePerRequestFilter`, registered as a `@Component` with `@Profile("!test")`:
|
|
||||||
|
|
||||||
- **Key for authenticated requests:** JWT `sub` claim (per-user bucket)
|
|
||||||
- **Key for unauthenticated requests:** remote IP address (pre-auth fallback)
|
|
||||||
- Buckets stored in a `ConcurrentHashMap<String, Bucket>`
|
|
||||||
|
|
||||||
### Limits
|
|
||||||
|
|
||||||
| Endpoint pattern | Limit |
|
|
||||||
|---|---|
|
|
||||||
| All endpoints (default) | 60 requests / minute |
|
|
||||||
| `POST /api/expenselist/*/invite` | 5 requests / minute |
|
|
||||||
| `POST /api/expenselist/accept-invite` | 10 requests / minute |
|
|
||||||
| `POST /api/users/createUser` | 3 requests / minute |
|
|
||||||
|
|
||||||
Sensitive endpoints get their own per-user bucket independent of the general bucket.
|
|
||||||
|
|
||||||
### Response
|
|
||||||
When a bucket is exhausted: `429 Too Many Requests` with a `Retry-After: <seconds>` header indicating time until refill.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Architecture Summary
|
|
||||||
|
|
||||||
```
|
|
||||||
Request
|
|
||||||
└── RateLimitFilter (per-user/IP buckets)
|
|
||||||
└── SecurityFilterChain (JWT validation)
|
|
||||||
└── Controller
|
|
||||||
├── @Valid on @RequestBody → GlobalExceptionHandler on failure
|
|
||||||
├── AuthenticatedUserResolver → AppUser from JWT sub
|
|
||||||
└── assertOwner / assertMember → 403 on violation
|
|
||||||
```
|
|
||||||
|
|
||||||
No new service layer is introduced. The authorization checks are lightweight and local to each controller method.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Files Affected
|
|
||||||
|
|
||||||
| File | Change |
|
|
||||||
|---|---|
|
|
||||||
| `pom.xml` | Add `spring-boot-starter-validation`, `bucket4j-core` |
|
|
||||||
| `model/AppUserCreateRequest.java` | Add validation annotations |
|
|
||||||
| `model/ExpenseInput.java` | Add validation annotations, remove JPA annotations |
|
|
||||||
| `model/ExpenseChangeRequest.java` | Add validation annotations |
|
|
||||||
| `model/InviteRequest.java` | Add validation annotations, remove `userId` field |
|
|
||||||
| `controller/AppUserController.java` | Add `@Valid`, ownership guards, use `AuthenticatedUserResolver` |
|
|
||||||
| `controller/ExpenseListController.java` | Add `@Valid`, ownership guards, remove/rename endpoints, use `AuthenticatedUserResolver` |
|
|
||||||
| `security/AuthenticatedUserResolver.java` | **New** — resolves JWT sub to `AppUser` |
|
|
||||||
| `security/RateLimitFilter.java` | **New** — per-user/IP rate limiting |
|
|
||||||
| `controller/GlobalExceptionHandler.java` | **New** — structured 400/403 error responses |
|
|
||||||
@@ -1,119 +1,135 @@
|
|||||||
<?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/> <!-- lookup parent from repository -->
|
||||||
</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.0.0</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-validation</artifactId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
</dependency>
|
<artifactId>spring-boot-starter-validation</artifactId>
|
||||||
<dependency>
|
</dependency>
|
||||||
<groupId>com.bucket4j</groupId>
|
<dependency>
|
||||||
<artifactId>bucket4j-core</artifactId>
|
<groupId>com.bucket4j</groupId>
|
||||||
<version>8.10.1</version>
|
<artifactId>bucket4j-core</artifactId>
|
||||||
</dependency>
|
<version>8.10.1</version>
|
||||||
<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-oauth2-resource-server</artifactId>
|
||||||
<dependency>
|
</dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<dependency>
|
||||||
<artifactId>spring-boot-starter-oauth2-client</artifactId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
</dependency>
|
<artifactId>spring-boot-starter-oauth2-client</artifactId>
|
||||||
<dependency>
|
</dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<dependency>
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
</dependency>
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
<dependency>
|
</dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<dependency>
|
||||||
<artifactId>spring-boot-devtools</artifactId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<scope>runtime</scope>
|
<artifactId>spring-boot-devtools</artifactId>
|
||||||
<optional>true</optional>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
<optional>true</optional>
|
||||||
<dependency>
|
</dependency>
|
||||||
<groupId>org.postgresql</groupId>
|
<dependency>
|
||||||
<artifactId>postgresql</artifactId>
|
<groupId>org.postgresql</groupId>
|
||||||
<scope>runtime</scope>
|
<artifactId>postgresql</artifactId>
|
||||||
</dependency>
|
<scope>runtime</scope>
|
||||||
<dependency>
|
</dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<dependency>
|
||||||
<artifactId>lombok</artifactId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<optional>true</optional>
|
<artifactId>lombok</artifactId>
|
||||||
</dependency>
|
<optional>true</optional>
|
||||||
<dependency>
|
</dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<dependency>
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<scope>test</scope>
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
</dependency>
|
<scope>test</scope>
|
||||||
<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-webmvc-test</artifactId>
|
||||||
</dependency>
|
<scope>test</scope>
|
||||||
</dependencies>
|
</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>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import org.springframework.web.server.ResponseStatusException;
|
|||||||
|
|
||||||
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.Exception.UsernameAlreadyExistsException;
|
|
||||||
import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver;
|
import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver;
|
||||||
import de.zendric.app.xpensely_server.services.UserService;
|
import de.zendric.app.xpensely_server.services.UserService;
|
||||||
|
|
||||||
@@ -47,15 +46,9 @@ public class AppUserController {
|
|||||||
|
|
||||||
@PostMapping("/createUser")
|
@PostMapping("/createUser")
|
||||||
public ResponseEntity<AppUser> createUser(@RequestBody @Valid AppUserCreateRequest userRequest) {
|
public ResponseEntity<AppUser> createUser(@RequestBody @Valid AppUserCreateRequest userRequest) {
|
||||||
try {
|
AppUser convertedUser = userRequest.convertToAppUser();
|
||||||
AppUser convertedUser = userRequest.convertToAppUser();
|
AppUser nUser = userService.createUser(convertedUser);
|
||||||
AppUser nUser = userService.createUser(convertedUser);
|
return new ResponseEntity<>(nUser, HttpStatus.CREATED);
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping
|
@DeleteMapping
|
||||||
|
|||||||
+28
-44
@@ -5,6 +5,8 @@ import java.util.List;
|
|||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
import jakarta.validation.Valid;
|
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.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
@@ -21,6 +23,8 @@ import de.zendric.app.xpensely_server.services.UserService;
|
|||||||
@RequestMapping("/api/expenselist")
|
@RequestMapping("/api/expenselist")
|
||||||
public class ExpenseListController {
|
public class ExpenseListController {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(ExpenseListController.class);
|
||||||
|
|
||||||
private final ExpenseListService expenseListService;
|
private final ExpenseListService expenseListService;
|
||||||
private final UserService userService;
|
private final UserService userService;
|
||||||
private final CategoryService categoryService;
|
private final CategoryService categoryService;
|
||||||
@@ -54,22 +58,18 @@ public class ExpenseListController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/create")
|
@PostMapping("/create")
|
||||||
public ResponseEntity<ExpenseList> create(@RequestBody ExpenseList expenseList,
|
public ResponseEntity<ExpenseList> create(@RequestBody @Valid CreateExpenseListRequest request,
|
||||||
Authentication authentication) {
|
Authentication authentication) {
|
||||||
try {
|
AppUser authenticatedUser = authenticatedUserResolver.resolveCurrentUser(authentication);
|
||||||
AppUser authenticatedUser = authenticatedUserResolver.resolveCurrentUser(authentication);
|
ExpenseList expenseList = new ExpenseList();
|
||||||
expenseList.setOwner(authenticatedUser);
|
expenseList.setName(request.getName());
|
||||||
XpenselyStandardCategories standardCategories = categoryService.getDefaultCategories();
|
expenseList.setOwner(authenticatedUser);
|
||||||
expenseList.setXpenselyStandardCategories(standardCategories);
|
XpenselyStandardCategories standardCategories = categoryService.getDefaultCategories();
|
||||||
expenseList.setSharedWith(null);
|
expenseList.setXpenselyStandardCategories(standardCategories);
|
||||||
ExpenseList savedItem = expenseListService.createList(expenseList);
|
expenseList.setSharedWith(null);
|
||||||
return new ResponseEntity<>(savedItem, HttpStatus.CREATED);
|
ExpenseList savedItem = expenseListService.createList(expenseList);
|
||||||
} catch (ResponseStatusException e) {
|
log.debug("Created expense list '{}' for user {}", savedItem.getName(), authenticatedUser.getId());
|
||||||
throw e;
|
return new ResponseEntity<>(savedItem, HttpStatus.CREATED);
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
return new ResponseEntity<>(null, HttpStatus.EXPECTATION_FAILED);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("{id}")
|
@DeleteMapping("{id}")
|
||||||
@@ -79,12 +79,8 @@ public class ExpenseListController {
|
|||||||
if (listOpt.isEmpty())
|
if (listOpt.isEmpty())
|
||||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||||
assertOwner(user, listOpt.get());
|
assertOwner(user, listOpt.get());
|
||||||
try {
|
expenseListService.deleteById(id);
|
||||||
expenseListService.deleteById(id);
|
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
|
||||||
} catch (Exception e) {
|
|
||||||
return new ResponseEntity<>(HttpStatus.EXPECTATION_FAILED);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/{id}/add")
|
@PostMapping("/{id}/add")
|
||||||
@@ -97,14 +93,10 @@ public class ExpenseListController {
|
|||||||
if (listOpt.isEmpty())
|
if (listOpt.isEmpty())
|
||||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||||
assertMember(user, listOpt.get());
|
assertMember(user, listOpt.get());
|
||||||
try {
|
AppUser expenseOwner = userService.getUserByName(expenseInput.getOwner());
|
||||||
AppUser expenseOwner = userService.getUserByName(expenseInput.getOwner());
|
Expense expense = expenseInput.convertToExpense(expenseOwner.getId());
|
||||||
Expense expense = expenseInput.convertToExpense(expenseOwner.getId());
|
Expense addedExpense = expenseListService.addExpenseToList(expenseListId, expense);
|
||||||
Expense addedExpense = expenseListService.addExpenseToList(expenseListId, expense);
|
return new ResponseEntity<>(addedExpense, HttpStatus.CREATED);
|
||||||
return new ResponseEntity<>(addedExpense, HttpStatus.CREATED);
|
|
||||||
} catch (Exception e) {
|
|
||||||
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/{id}/update")
|
@PutMapping("/{id}/update")
|
||||||
@@ -115,16 +107,12 @@ public class ExpenseListController {
|
|||||||
AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
|
AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
|
||||||
Optional<ExpenseList> expenseListOpt = expenseListService.findById(expenseListId);
|
Optional<ExpenseList> expenseListOpt = expenseListService.findById(expenseListId);
|
||||||
if (expenseListOpt.isEmpty())
|
if (expenseListOpt.isEmpty())
|
||||||
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
|
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||||
assertMember(user, expenseListOpt.get());
|
assertMember(user, expenseListOpt.get());
|
||||||
try {
|
AppUser expenseOwner = userService.getUserByName(expenseChangeRequest.getOwnerName());
|
||||||
AppUser expenseOwner = userService.getUserByName(expenseChangeRequest.getOwnerName());
|
Expense expense = expenseChangeRequest.convertToExpense(expenseOwner.getId(), expenseListOpt.get());
|
||||||
Expense expense = expenseChangeRequest.convertToExpense(expenseOwner.getId(), expenseListOpt.get());
|
Expense updatedExpense = expenseListService.updateExpense(expenseListId, expense);
|
||||||
Expense updatedExpense = expenseListService.updateExpense(expenseListId, expense);
|
return new ResponseEntity<>(updatedExpense, HttpStatus.OK);
|
||||||
return new ResponseEntity<>(updatedExpense, HttpStatus.OK);
|
|
||||||
} catch (Exception e) {
|
|
||||||
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("/{id}/delete")
|
@DeleteMapping("/{id}/delete")
|
||||||
@@ -137,12 +125,8 @@ public class ExpenseListController {
|
|||||||
if (listOpt.isEmpty())
|
if (listOpt.isEmpty())
|
||||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||||
assertMember(user, listOpt.get());
|
assertMember(user, listOpt.get());
|
||||||
try {
|
expenseListService.deleteExpenseFromList(expenseListId, expenseId);
|
||||||
expenseListService.deleteExpenseFromList(expenseListId, expenseId);
|
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
|
||||||
} catch (Exception e) {
|
|
||||||
return new ResponseEntity<>(null, HttpStatus.EXPECTATION_FAILED);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/{listId}/invite")
|
@PostMapping("/{listId}/invite")
|
||||||
|
|||||||
@@ -1,11 +1,16 @@
|
|||||||
package de.zendric.app.xpensely_server.controller;
|
package de.zendric.app.xpensely_server.controller;
|
||||||
|
|
||||||
|
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.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.validation.FieldError;
|
import org.springframework.validation.FieldError;
|
||||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -13,6 +18,8 @@ import java.util.Map;
|
|||||||
@RestControllerAdvice
|
@RestControllerAdvice
|
||||||
public class GlobalExceptionHandler {
|
public class GlobalExceptionHandler {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||||
|
|
||||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||||
public ResponseEntity<Map<String, String>> handleValidationErrors(MethodArgumentNotValidException ex) {
|
public ResponseEntity<Map<String, String>> handleValidationErrors(MethodArgumentNotValidException ex) {
|
||||||
Map<String, String> errors = new HashMap<>();
|
Map<String, String> errors = new HashMap<>();
|
||||||
@@ -27,4 +34,36 @@ public class GlobalExceptionHandler {
|
|||||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||||
.body(Map.of("error", ex.getMessage()));
|
.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(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"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
+11
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
}
|
}
|
||||||
@@ -6,7 +6,7 @@ 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.BearerTokenAuthenticationFilter;
|
import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter;
|
||||||
import org.springframework.security.web.SecurityFilterChain;
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@@ -18,7 +18,7 @@ public class SecurityConfig {
|
|||||||
http
|
http
|
||||||
.authorizeHttpRequests(auth -> auth
|
.authorizeHttpRequests(auth -> auth
|
||||||
.anyRequest().permitAll())
|
.anyRequest().permitAll())
|
||||||
.csrf().disable();
|
.csrf(csrf -> csrf.disable());
|
||||||
|
|
||||||
return http.build();
|
return http.build();
|
||||||
}
|
}
|
||||||
@@ -33,7 +33,7 @@ public class SecurityConfig {
|
|||||||
.jwt(Customizer.withDefaults()))
|
.jwt(Customizer.withDefaults()))
|
||||||
.oauth2Login(Customizer.withDefaults())
|
.oauth2Login(Customizer.withDefaults())
|
||||||
.addFilterAfter(new RateLimitFilter(), BearerTokenAuthenticationFilter.class)
|
.addFilterAfter(new RateLimitFilter(), BearerTokenAuthenticationFilter.class)
|
||||||
.csrf().disable();
|
.csrf(csrf -> csrf.disable());
|
||||||
|
|
||||||
return http.build();
|
return http.build();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,37 +1,29 @@
|
|||||||
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.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.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 de.zendric.app.xpensely_server.repo.XpenselyCustomCategoryRepository;
|
import de.zendric.app.xpensely_server.repo.XpenselyCustomCategoryRepository;
|
||||||
import jakarta.persistence.EntityManager;
|
|
||||||
|
|
||||||
@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 XpenselyCustomCategoryRepository customCategoryRepository;
|
private final XpenselyCustomCategoryRepository customCategoryRepository;
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private EntityManager entityManager;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
public ExpenseListService(ExpenseListRepository repository, ExpenseRepository expenseRepository,
|
public ExpenseListService(ExpenseListRepository repository, ExpenseRepository expenseRepository,
|
||||||
XpenselyCustomCategoryRepository customCategoryRepository) {
|
XpenselyCustomCategoryRepository customCategoryRepository) {
|
||||||
this.repository = repository;
|
this.repository = repository;
|
||||||
@@ -39,18 +31,10 @@ public class ExpenseListService {
|
|||||||
this.customCategoryRepository = customCategoryRepository;
|
this.customCategoryRepository = customCategoryRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
|
||||||
repository.deleteById(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void deleteById(Long id) {
|
public void deleteById(Long id) {
|
||||||
repository.deleteById(id);
|
repository.deleteById(id);
|
||||||
}
|
}
|
||||||
@@ -59,76 +43,29 @@ public class ExpenseListService {
|
|||||||
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) {
|
||||||
// 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
|
|
||||||
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);
|
||||||
|
return expense;
|
||||||
Expense newExpense = new 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) {
|
||||||
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)) {
|
||||||
@@ -139,14 +76,14 @@ public class ExpenseListService {
|
|||||||
if (expenseToRemove != null) {
|
if (expenseToRemove != null) {
|
||||||
expenseList.removeExpense(expenseToRemove);
|
expenseList.removeExpense(expenseToRemove);
|
||||||
} else {
|
} else {
|
||||||
throw new RuntimeException("Expense not found with id: " + expenseId);
|
throw new ResourceNotFoundException("Expense not found with id: " + expenseId);
|
||||||
}
|
}
|
||||||
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())) {
|
||||||
|
|
||||||
@@ -168,7 +105,7 @@ public class ExpenseListService {
|
|||||||
|
|
||||||
public Expense updateExpense(Long expenseListId, Expense updatedExpense) {
|
public Expense updateExpense(Long expenseListId, Expense updatedExpense) {
|
||||||
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()))) {
|
||||||
@@ -176,7 +113,7 @@ 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()));
|
||||||
existingExpense.setTitle(updatedExpense.getTitle());
|
existingExpense.setTitle(updatedExpense.getTitle());
|
||||||
existingExpense.setAmount(updatedExpense.getAmount());
|
existingExpense.setAmount(updatedExpense.getAmount());
|
||||||
existingExpense.setPersonalUseAmount(updatedExpense.getPersonalUseAmount());
|
existingExpense.setPersonalUseAmount(updatedExpense.getPersonalUseAmount());
|
||||||
@@ -191,7 +128,7 @@ public class ExpenseListService {
|
|||||||
// TODO implement API for this
|
// TODO implement API for this
|
||||||
public XpenselyCustomCategory addCustomCategory(Long expenseListId, XpenselyCustomCategory customCategory) {
|
public XpenselyCustomCategory addCustomCategory(Long expenseListId, XpenselyCustomCategory customCategory) {
|
||||||
ExpenseList expenseList = repository.findById(expenseListId)
|
ExpenseList expenseList = repository.findById(expenseListId)
|
||||||
.orElseThrow(() -> new RuntimeException("Expense List not found"));
|
.orElseThrow(() -> new ResourceNotFoundException("Expense List not found"));
|
||||||
customCategory.setExpenseList(expenseList);
|
customCategory.setExpenseList(expenseList);
|
||||||
|
|
||||||
return customCategoryRepository.save(customCategory);
|
return customCategoryRepository.save(customCategory);
|
||||||
@@ -200,9 +137,9 @@ public class ExpenseListService {
|
|||||||
// TODO implement API for this
|
// TODO implement API for this
|
||||||
public void deleteCustomCategory(Long expenseListId, Long categoryId) {
|
public void deleteCustomCategory(Long expenseListId, Long categoryId) {
|
||||||
XpenselyCustomCategory category = customCategoryRepository.findById(categoryId)
|
XpenselyCustomCategory category = customCategoryRepository.findById(categoryId)
|
||||||
.orElseThrow(() -> new RuntimeException("Custom Category not found"));
|
.orElseThrow(() -> new ResourceNotFoundException("Custom Category not found"));
|
||||||
if (!category.getExpenseList().getId().equals(expenseListId)) {
|
if (!category.getExpenseList().getId().equals(expenseListId)) {
|
||||||
throw new RuntimeException("Category does not belong to the specified Expense List");
|
throw new IllegalArgumentException("Category does not belong to the specified Expense List");
|
||||||
}
|
}
|
||||||
customCategoryRepository.delete(category);
|
customCategoryRepository.delete(category);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
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.Exception.ResourceNotFoundException;
|
||||||
import de.zendric.app.xpensely_server.model.Exception.UsernameAlreadyExistsException;
|
import de.zendric.app.xpensely_server.model.Exception.UsernameAlreadyExistsException;
|
||||||
import de.zendric.app.xpensely_server.repo.UserRepository;
|
import de.zendric.app.xpensely_server.repo.UserRepository;
|
||||||
|
|
||||||
@@ -29,36 +29,24 @@ public class UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,26 +1,47 @@
|
|||||||
package de.zendric.app.xpensely_Server;
|
package de.zendric.app.xpensely_Server;
|
||||||
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
|
||||||
|
|
||||||
import de.zendric.app.xpensely_server.model.ExpenseList;
|
import de.zendric.app.xpensely_server.model.ExpenseList;
|
||||||
import de.zendric.app.xpensely_server.repo.ExpenseListRepository;
|
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
|
@DataJpaTest
|
||||||
class ExpenseListRepositoryTest {
|
class ExpenseListRepositoryTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private ExpenseListRepository expenseListRepository;
|
private ExpenseListRepository expenseListRepository;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testFindExpenseListById() {
|
void saveAndFindById_returnsExpenseList() {
|
||||||
// Assuming an ExpenseList with id = 1 exists in your test DB.
|
ExpenseList list = new ExpenseList();
|
||||||
Optional<ExpenseList> optionalExpenseList = expenseListRepository.findById(1L);
|
list.setName("Groceries");
|
||||||
|
ExpenseList saved = expenseListRepository.save(list);
|
||||||
|
|
||||||
ExpenseList expenseList = optionalExpenseList.get();
|
Optional<ExpenseList> found = expenseListRepository.findById(saved.getId());
|
||||||
System.out.println("ExpenseList name: " + expenseList.getName());
|
|
||||||
}
|
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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,8 +6,11 @@ import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver;
|
|||||||
import de.zendric.app.xpensely_server.services.UserService;
|
import de.zendric.app.xpensely_server.services.UserService;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
import org.springframework.boot.security.oauth2.client.autoconfigure.OAuth2ClientAutoConfiguration;
|
||||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
import org.springframework.boot.security.oauth2.client.autoconfigure.servlet.OAuth2ClientWebSecurityAutoConfiguration;
|
||||||
|
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.http.MediaType;
|
||||||
import org.springframework.test.context.ActiveProfiles;
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||||
@@ -18,7 +21,11 @@ import static org.mockito.Mockito.when;
|
|||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||||
|
|
||||||
@WebMvcTest(AppUserController.class)
|
@WebMvcTest(value = AppUserController.class, excludeAutoConfiguration = {
|
||||||
|
OAuth2ClientAutoConfiguration.class,
|
||||||
|
OAuth2ClientWebSecurityAutoConfiguration.class,
|
||||||
|
OAuth2ResourceServerAutoConfiguration.class
|
||||||
|
})
|
||||||
@AutoConfigureMockMvc(addFilters = false)
|
@AutoConfigureMockMvc(addFilters = false)
|
||||||
@ActiveProfiles("test")
|
@ActiveProfiles("test")
|
||||||
class AppUserControllerTest {
|
class AppUserControllerTest {
|
||||||
|
|||||||
+49
-3
@@ -9,8 +9,11 @@ import de.zendric.app.xpensely_server.services.ExpenseListService;
|
|||||||
import de.zendric.app.xpensely_server.services.UserService;
|
import de.zendric.app.xpensely_server.services.UserService;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
import org.springframework.boot.security.oauth2.client.autoconfigure.OAuth2ClientAutoConfiguration;
|
||||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
import org.springframework.boot.security.oauth2.client.autoconfigure.servlet.OAuth2ClientWebSecurityAutoConfiguration;
|
||||||
|
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.http.MediaType;
|
||||||
import org.springframework.test.context.ActiveProfiles;
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||||
@@ -24,7 +27,11 @@ import static org.mockito.Mockito.when;
|
|||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||||
|
|
||||||
@WebMvcTest(ExpenseListController.class)
|
@WebMvcTest(value = ExpenseListController.class, excludeAutoConfiguration = {
|
||||||
|
OAuth2ClientAutoConfiguration.class,
|
||||||
|
OAuth2ClientWebSecurityAutoConfiguration.class,
|
||||||
|
OAuth2ResourceServerAutoConfiguration.class
|
||||||
|
})
|
||||||
@AutoConfigureMockMvc(addFilters = false)
|
@AutoConfigureMockMvc(addFilters = false)
|
||||||
@ActiveProfiles("test")
|
@ActiveProfiles("test")
|
||||||
class ExpenseListControllerTest {
|
class ExpenseListControllerTest {
|
||||||
@@ -132,4 +139,43 @@ class ExpenseListControllerTest {
|
|||||||
mockMvc.perform(get("/api/expenselist/mine"))
|
mockMvc.perform(get("/api/expenselist/mine"))
|
||||||
.andExpect(status().isOk());
|
.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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package de.zendric.app.xpensely_Server.services;
|
||||||
|
|
||||||
|
import de.zendric.app.xpensely_server.model.AppUser;
|
||||||
|
import de.zendric.app.xpensely_server.model.ExpenseList;
|
||||||
|
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 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.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
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;
|
||||||
|
|
||||||
|
@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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user