Compare commits
10 Commits
477a5c3c70
...
9c91da9f30
| Author | SHA1 | Date | |
|---|---|---|---|
| 9c91da9f30 | |||
| 024b3880e7 | |||
| 457efab452 | |||
| 95688e5111 | |||
| bb2a4d70b2 | |||
| a948bca2fc | |||
| 3bea06fead | |||
| b7db35defe | |||
| efe84942ff | |||
| e3b8917bfc |
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,166 @@
|
|||||||
|
# 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 |
|
||||||
@@ -27,7 +27,7 @@
|
|||||||
<url/>
|
<url/>
|
||||||
</scm>
|
</scm>
|
||||||
<properties>
|
<properties>
|
||||||
<java.version>17</java.version>
|
<java.version>21</java.version>
|
||||||
</properties>
|
</properties>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
@@ -38,6 +38,15 @@
|
|||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-security</artifactId>
|
<artifactId>spring-boot-starter-security</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-validation</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.bucket4j</groupId>
|
||||||
|
<artifactId>bucket4j-core</artifactId>
|
||||||
|
<version>8.10.1</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
|
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
|
||||||
@@ -71,6 +80,11 @@
|
|||||||
<artifactId>spring-boot-starter-test</artifactId>
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.security</groupId>
|
<groupId>org.springframework.security</groupId>
|
||||||
<artifactId>spring-security-test</artifactId>
|
<artifactId>spring-security-test</artifactId>
|
||||||
|
|||||||
@@ -1,35 +1,35 @@
|
|||||||
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.Exception.UsernameAlreadyExistsException;
|
import de.zendric.app.xpensely_server.model.Exception.UsernameAlreadyExistsException;
|
||||||
|
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")
|
@GetMapping("/byName")
|
||||||
@@ -38,23 +38,17 @@ public class AppUserController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@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 {
|
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) {
|
} catch (UsernameAlreadyExistsException e) {
|
||||||
@@ -62,12 +56,18 @@ public class AppUserController {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
|
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+89
-117
@@ -1,125 +1,71 @@
|
|||||||
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.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.security.AuthenticatedUserResolver;
|
||||||
import de.zendric.app.xpensely_server.model.ExpenseChangeRequest;
|
|
||||||
import de.zendric.app.xpensely_server.model.ExpenseInput;
|
|
||||||
import de.zendric.app.xpensely_server.model.ExpenseList;
|
|
||||||
import de.zendric.app.xpensely_server.model.InviteRequest;
|
|
||||||
import de.zendric.app.xpensely_server.model.XpenselyStandardCategories;
|
|
||||||
import de.zendric.app.xpensely_server.services.CategoryService;
|
import de.zendric.app.xpensely_server.services.CategoryService;
|
||||||
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.UserService;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/expenselist")
|
@RequestMapping("/api/expenselist")
|
||||||
class ExpenseListController {
|
public class ExpenseListController {
|
||||||
|
|
||||||
private ExpenseListService expenseListService;
|
private final ExpenseListService expenseListService;
|
||||||
private UserService userService;
|
private final UserService userService;
|
||||||
private CategoryService categoryService;
|
private final CategoryService categoryService;
|
||||||
|
private final AuthenticatedUserResolver authenticatedUserResolver;
|
||||||
|
|
||||||
@Autowired
|
|
||||||
public ExpenseListController(ExpenseListService expenseListService, UserService userService,
|
public ExpenseListController(ExpenseListService expenseListService, UserService userService,
|
||||||
CategoryService categoryService) {
|
CategoryService categoryService, AuthenticatedUserResolver authenticatedUserResolver) {
|
||||||
this.expenseListService = expenseListService;
|
this.expenseListService = expenseListService;
|
||||||
this.userService = userService;
|
this.userService = userService;
|
||||||
this.categoryService = categoryService;
|
this.categoryService = categoryService;
|
||||||
|
this.authenticatedUserResolver = authenticatedUserResolver;
|
||||||
}
|
}
|
||||||
|
|
||||||
@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")
|
||||||
// TODO add handling of categories by using DTO
|
public ResponseEntity<ExpenseList> create(@RequestBody ExpenseList expenseList,
|
||||||
public ResponseEntity<ExpenseList> create(@RequestBody ExpenseList expenseList) {
|
Authentication authentication) {
|
||||||
try {
|
try {
|
||||||
if (expenseList.getOwner() != null) {
|
AppUser authenticatedUser = authenticatedUserResolver.resolveCurrentUser(authentication);
|
||||||
AppUser existingOwner = userService.getUser(expenseList.getOwner().getId());
|
expenseList.setOwner(authenticatedUser);
|
||||||
if (existingOwner == null) {
|
XpenselyStandardCategories standardCategories = categoryService.getDefaultCategories();
|
||||||
throw new IllegalArgumentException("Owner does not exist.");
|
expenseList.setXpenselyStandardCategories(standardCategories);
|
||||||
}
|
|
||||||
expenseList.setOwner(existingOwner);
|
|
||||||
XpenselyStandardCategories standardCategories = categoryService.getDefaultCategories();
|
|
||||||
expenseList.setXpenselyStandardCategories(standardCategories);
|
|
||||||
} else {
|
|
||||||
throw new IllegalArgumentException("Owner is required.");
|
|
||||||
}
|
|
||||||
|
|
||||||
expenseList.setSharedWith(null);
|
expenseList.setSharedWith(null);
|
||||||
|
|
||||||
ExpenseList savedItem = expenseListService.createList(expenseList);
|
ExpenseList savedItem = expenseListService.createList(expenseList);
|
||||||
return new ResponseEntity<>(savedItem, HttpStatus.CREATED);
|
return new ResponseEntity<>(savedItem, HttpStatus.CREATED);
|
||||||
|
} catch (ResponseStatusException e) {
|
||||||
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
return new ResponseEntity<>(null, HttpStatus.EXPECTATION_FAILED);
|
return new ResponseEntity<>(null, HttpStatus.EXPECTATION_FAILED);
|
||||||
@@ -127,7 +73,12 @@ class ExpenseListController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("{id}")
|
@DeleteMapping("{id}")
|
||||||
public ResponseEntity<HttpStatus> delete(@PathVariable("id") Long id) {
|
public ResponseEntity<HttpStatus> delete(@PathVariable("id") Long id, 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());
|
||||||
try {
|
try {
|
||||||
expenseListService.deleteById(id);
|
expenseListService.deleteById(id);
|
||||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||||
@@ -139,11 +90,16 @@ class ExpenseListController {
|
|||||||
@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,
|
||||||
|
Authentication authentication) {
|
||||||
|
AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
|
||||||
|
Optional<ExpenseList> listOpt = expenseListService.findById(expenseListId);
|
||||||
|
if (listOpt.isEmpty())
|
||||||
|
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||||
|
assertMember(user, listOpt.get());
|
||||||
try {
|
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) {
|
} catch (Exception e) {
|
||||||
@@ -154,18 +110,18 @@ class ExpenseListController {
|
|||||||
@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,
|
||||||
|
Authentication authentication) {
|
||||||
|
AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
|
||||||
|
Optional<ExpenseList> expenseListOpt = expenseListService.findById(expenseListId);
|
||||||
|
if (expenseListOpt.isEmpty())
|
||||||
|
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
|
||||||
|
assertMember(user, expenseListOpt.get());
|
||||||
try {
|
try {
|
||||||
AppUser expenseOwner = userService.getUserByName(expenseChangeRequest.getOwnerName());
|
AppUser expenseOwner = userService.getUserByName(expenseChangeRequest.getOwnerName());
|
||||||
Optional<ExpenseList> expenseList = expenseListService.findById(expenseListId);
|
Expense expense = expenseChangeRequest.convertToExpense(expenseOwner.getId(), expenseListOpt.get());
|
||||||
if (expenseList.isPresent()) {
|
Expense updatedExpense = expenseListService.updateExpense(expenseListId, expense);
|
||||||
Expense expense = expenseChangeRequest.convertToExpense(expenseOwner.getId(), expenseList.get());
|
return new ResponseEntity<>(updatedExpense, HttpStatus.OK);
|
||||||
|
|
||||||
Expense addedExpense = expenseListService.updateExpense(expenseListId, expense);
|
|
||||||
return new ResponseEntity<>(addedExpense, HttpStatus.CREATED);
|
|
||||||
}
|
|
||||||
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
|
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
|
||||||
}
|
}
|
||||||
@@ -174,7 +130,13 @@ class ExpenseListController {
|
|||||||
@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,
|
||||||
|
Authentication authentication) {
|
||||||
|
AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
|
||||||
|
Optional<ExpenseList> listOpt = expenseListService.findById(expenseListId);
|
||||||
|
if (listOpt.isEmpty())
|
||||||
|
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||||
|
assertMember(user, listOpt.get());
|
||||||
try {
|
try {
|
||||||
expenseListService.deleteExpenseFromList(expenseListId, expenseId);
|
expenseListService.deleteExpenseFromList(expenseListId, expenseId);
|
||||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||||
@@ -184,13 +146,20 @@ class ExpenseListController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@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 ||
|
||||||
@@ -200,21 +169,24 @@ 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;
|
|
||||||
try {
|
|
||||||
user = userService.getUser(inviteRequest.getUserId());
|
|
||||||
} catch (Exception e) {
|
|
||||||
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");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package de.zendric.app.xpensely_server.controller;
|
||||||
|
|
||||||
|
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 java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@RestControllerAdvice
|
||||||
|
public class GlobalExceptionHandler {
|
||||||
|
|
||||||
|
@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()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,10 @@ package de.zendric.app.xpensely_server.model;
|
|||||||
|
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.DecimalMin;
|
||||||
|
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,12 +16,25 @@ 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;
|
||||||
|
|
||||||
|
@NotNull(message = "Amount is required")
|
||||||
|
@DecimalMin(value = "0.01", message = "Amount must be greater than zero")
|
||||||
private Double amount;
|
private Double amount;
|
||||||
|
|
||||||
private Double personalUseAmount;
|
private Double personalUseAmount;
|
||||||
private Double otherPersonAmount;
|
private Double otherPersonAmount;
|
||||||
|
|
||||||
|
@NotNull(message = "Date is required")
|
||||||
private LocalDate date;
|
private LocalDate date;
|
||||||
|
|
||||||
|
@NotBlank(message = "Category is required")
|
||||||
private String category;
|
private String category;
|
||||||
|
|
||||||
public Expense convertToExpense(Long userId, ExpenseList expenseList) {
|
public Expense convertToExpense(Long userId, ExpenseList expenseList) {
|
||||||
@@ -38,4 +55,4 @@ public class ExpenseChangeRequest {
|
|||||||
|
|
||||||
return expense;
|
return expense;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,10 @@ 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.NotBlank;
|
||||||
import jakarta.persistence.Id;
|
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,19 +17,26 @@ 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.01", message = "Amount must be greater than zero")
|
||||||
private Double amount;
|
private Double amount;
|
||||||
|
|
||||||
private Double personalUseAmount;
|
private Double personalUseAmount;
|
||||||
private Double otherPersonAmount;
|
private Double otherPersonAmount;
|
||||||
|
|
||||||
|
@NotNull(message = "Date is required")
|
||||||
private LocalDate date;
|
private LocalDate date;
|
||||||
|
|
||||||
|
@NotBlank(message = "Category is required")
|
||||||
private String category;
|
private String category;
|
||||||
|
|
||||||
private ExpenseList expenseList;
|
private ExpenseList expenseList;
|
||||||
|
|||||||
@@ -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,36 @@
|
|||||||
|
package de.zendric.app.xpensely_server.security;
|
||||||
|
|
||||||
|
import de.zendric.app.xpensely_server.model.AppUser;
|
||||||
|
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 {
|
||||||
|
AppUser user = userService.getUserByGoogleId(googleId);
|
||||||
|
if (user == null) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "User not registered");
|
||||||
|
}
|
||||||
|
return user;
|
||||||
|
} catch (IllegalArgumentException 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +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.web.SecurityFilterChain;
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@@ -31,6 +32,7 @@ public class SecurityConfig {
|
|||||||
.oauth2ResourceServer(oauth2 -> oauth2
|
.oauth2ResourceServer(oauth2 -> oauth2
|
||||||
.jwt(Customizer.withDefaults()))
|
.jwt(Customizer.withDefaults()))
|
||||||
.oauth2Login(Customizer.withDefaults())
|
.oauth2Login(Customizer.withDefaults())
|
||||||
|
.addFilterAfter(new RateLimitFilter(), BearerTokenAuthenticationFilter.class)
|
||||||
.csrf().disable();
|
.csrf().disable();
|
||||||
|
|
||||||
return http.build();
|
return http.build();
|
||||||
|
|||||||
@@ -1,26 +1,47 @@
|
|||||||
package de.zendric.app.xpensely_Server;
|
package de.zendric.app.xpensely_Server;
|
||||||
|
|
||||||
import java.util.Optional;
|
import de.zendric.app.xpensely_server.model.ExpenseList;
|
||||||
|
import de.zendric.app.xpensely_server.repo.ExpenseListRepository;
|
||||||
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.orm.jpa.DataJpaTest;
|
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||||
|
|
||||||
import de.zendric.app.xpensely_server.model.ExpenseList;
|
import java.util.Optional;
|
||||||
import de.zendric.app.xpensely_server.repo.ExpenseListRepository;
|
|
||||||
|
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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
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.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||||
|
import org.springframework.boot.test.autoconfigure.web.servlet.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(AppUserController.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());
|
||||||
|
}
|
||||||
|
}
|
||||||
+135
@@ -0,0 +1,135 @@
|
|||||||
|
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.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.UserService;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||||
|
import org.springframework.boot.test.autoconfigure.web.servlet.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.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
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(ExpenseListController.class)
|
||||||
|
@AutoConfigureMockMvc(addFilters = false)
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
class ExpenseListControllerTest {
|
||||||
|
|
||||||
|
@Autowired MockMvc mockMvc;
|
||||||
|
@MockitoBean ExpenseListService expenseListService;
|
||||||
|
@MockitoBean UserService userService;
|
||||||
|
@MockitoBean CategoryService categoryService;
|
||||||
|
@MockitoBean AuthenticatedUserResolver authenticatedUserResolver;
|
||||||
|
|
||||||
|
// --- 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());
|
||||||
|
}
|
||||||
|
|
||||||
|
@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());
|
||||||
|
}
|
||||||
|
}
|
||||||
+78
@@ -0,0 +1,78 @@
|
|||||||
|
package de.zendric.app.xpensely_Server.security;
|
||||||
|
|
||||||
|
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.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")).thenReturn(null);
|
||||||
|
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user