add validation

This commit is contained in:
mirrerror
2023-11-15 09:16:27 +02:00
parent 2d981c5af8
commit fb2695e58a
23 changed files with 314 additions and 62 deletions

View File

@@ -10,9 +10,11 @@ import com.faf223.expensetrackerfaf.service.ExpenseCategoryService;
import com.faf223.expensetrackerfaf.service.ExpenseService;
import com.faf223.expensetrackerfaf.service.UserService;
import com.faf223.expensetrackerfaf.util.errors.ErrorResponse;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionDoesNotBelongToTheUserException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionNotCreatedException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionNotUpdatedException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionsNotFoundException;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -49,12 +51,12 @@ public class ExpenseController {
}
@PostMapping()
public ResponseEntity<Void> createNewExpense(@RequestBody ExpenseCreationDTO expenseDTO,
public ResponseEntity<Void> createNewExpense(@RequestBody @Valid ExpenseCreationDTO expenseDTO,
BindingResult bindingResult) {
Expense expense = expenseMapper.toExpense(expenseDTO);
if(bindingResult.hasErrors())
throw new TransactionNotCreatedException(ErrorResponse.from(bindingResult).getMessage());
throw new TransactionNotCreatedException("Could not create new expense");
Expense expense = expenseMapper.toExpense(expenseDTO);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
@@ -71,25 +73,26 @@ public class ExpenseController {
throw new TransactionNotCreatedException("Could not create new expense");
}
// TODO: check if the expense belongs to the user
@PatchMapping("/update/{id}")
public ResponseEntity<Void> updateExpense(@PathVariable long id, @RequestBody ExpenseCreationDTO expenseDTO,
public ResponseEntity<Void> updateExpense(@PathVariable long id, @RequestBody @Valid ExpenseCreationDTO expenseDTO,
BindingResult bindingResult) {
if(bindingResult.hasErrors())
throw new TransactionNotUpdatedException(ErrorResponse.from(bindingResult).getMessage());
Expense expense = expenseService.getTransactionById(id);
if(expense == null) throw new TransactionsNotFoundException("The expense has not been found");
if(expense == null)
throw new TransactionsNotFoundException("The expense has not been found");
if(!expenseService.belongsToUser(expense))
throw new TransactionDoesNotBelongToTheUserException("The transaction does not belong to you");
ExpenseCategory category = expenseCategoryService.getCategoryById(expenseDTO.getExpenseCategory());
expense.setCategory(category);
expense.setAmount(expenseDTO.getAmount());
if (!bindingResult.hasErrors()) {
expenseService.createOrUpdate(expense);
return ResponseEntity.status(HttpStatus.CREATED).build();
} else {
throw new TransactionNotUpdatedException(ErrorResponse.from(bindingResult).getMessage());
}
expenseService.createOrUpdate(expense);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
@GetMapping("/personal-expenses")
@@ -103,8 +106,8 @@ public class ExpenseController {
String email = userDetails.getUsername();
List<ExpenseDTO> expenses;
expenses = date.map(localDate -> expenseService.getTransactionsByDate(localDate).stream().map(expenseMapper::toDto).toList())
.orElseGet(() -> month.map(value -> expenseService.getTransactionsByMonth(value).stream().map(expenseMapper::toDto).toList())
expenses = date.map(localDate -> expenseService.getTransactionsByDate(localDate, email).stream().map(expenseMapper::toDto).toList())
.orElseGet(() -> month.map(value -> expenseService.getTransactionsByMonth(value, email).stream().map(expenseMapper::toDto).toList())
.orElseGet(() -> expenseService.getTransactionsByEmail(email).stream().map(expenseMapper::toDto).toList()));
if (!expenses.isEmpty()) {

View File

@@ -1,10 +1,7 @@
package com.faf223.expensetrackerfaf.controller;
import com.faf223.expensetrackerfaf.util.errors.ErrorResponse;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionDoesNotBelongToTheUserException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionNotCreatedException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionsNotFoundException;
import com.faf223.expensetrackerfaf.util.exceptions.UserNotFoundException;
import com.faf223.expensetrackerfaf.util.exceptions.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
@@ -20,7 +17,7 @@ public class GlobalExceptionHandler {
System.currentTimeMillis()
);
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
return new ResponseEntity<>(response, HttpStatus.FORBIDDEN);
}
@ExceptionHandler
@@ -30,7 +27,7 @@ public class GlobalExceptionHandler {
System.currentTimeMillis()
);
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
return new ResponseEntity<>(response, HttpStatus.NOT_MODIFIED);
}
@ExceptionHandler
@@ -53,4 +50,34 @@ public class GlobalExceptionHandler {
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
@ExceptionHandler
private ResponseEntity<ErrorResponse> handleTransactionNotUpdatedException(TransactionNotUpdatedException e) {
ErrorResponse response = new ErrorResponse(
e.getMessage(),
System.currentTimeMillis()
);
return new ResponseEntity<>(response, HttpStatus.NOT_MODIFIED);
}
@ExceptionHandler
private ResponseEntity<ErrorResponse> handleUserNotAuthenticatedException(UserNotAuthenticatedException e) {
ErrorResponse response = new ErrorResponse(
e.getMessage(),
System.currentTimeMillis()
);
return new ResponseEntity<>(response, HttpStatus.FORBIDDEN);
}
@ExceptionHandler
private ResponseEntity<ErrorResponse> handleUserNotCreatedException(UserNotCreatedException e) {
ErrorResponse response = new ErrorResponse(
e.getMessage(),
System.currentTimeMillis()
);
return new ResponseEntity<>(response, HttpStatus.NOT_MODIFIED);
}
}

View File

@@ -10,9 +10,11 @@ import com.faf223.expensetrackerfaf.service.IncomeCategoryService;
import com.faf223.expensetrackerfaf.service.IncomeService;
import com.faf223.expensetrackerfaf.service.UserService;
import com.faf223.expensetrackerfaf.util.errors.ErrorResponse;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionDoesNotBelongToTheUserException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionNotCreatedException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionNotUpdatedException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionsNotFoundException;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -49,13 +51,13 @@ public class IncomeController {
}
@PostMapping()
public ResponseEntity<Void> createNewIncome(@RequestBody IncomeCreationDTO incomeDTO,
public ResponseEntity<Void> createNewIncome(@RequestBody @Valid IncomeCreationDTO incomeDTO,
BindingResult bindingResult) {
Income income = incomeMapper.toIncome(incomeDTO);
if(bindingResult.hasErrors())
throw new TransactionNotCreatedException(ErrorResponse.from(bindingResult).getMessage());
Income income = incomeMapper.toIncome(incomeDTO);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) {
@@ -71,24 +73,26 @@ public class IncomeController {
throw new TransactionNotCreatedException("Could not create new expense");
}
// TODO: check if the income belongs to the user, extract logic into service
@PatchMapping("/update/{id}")
public ResponseEntity<Void> updateIncome(@PathVariable long id, @RequestBody IncomeCreationDTO incomeDTO,
public ResponseEntity<Void> updateIncome(@PathVariable long id, @RequestBody @Valid IncomeCreationDTO incomeDTO,
BindingResult bindingResult) {
if(bindingResult.hasErrors())
throw new TransactionNotUpdatedException(ErrorResponse.from(bindingResult).getMessage());
Income income = incomeService.getTransactionById(id);
if(income == null) throw new TransactionsNotFoundException("The income has not been found");
if(income == null)
throw new TransactionsNotFoundException("The income has not been found");
if(!incomeService.belongsToUser(income))
throw new TransactionDoesNotBelongToTheUserException("The transaction does not belong to you");
IncomeCategory category = incomeCategoryService.getCategoryById(incomeDTO.getIncomeCategory());
income.setCategory(category);
income.setAmount(incomeDTO.getAmount());
if (!bindingResult.hasErrors()) {
incomeService.createOrUpdate(income);
return ResponseEntity.status(HttpStatus.CREATED).build();
} else {
throw new TransactionNotUpdatedException(ErrorResponse.from(bindingResult).getMessage());
}
incomeService.createOrUpdate(income);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
@GetMapping("/personal-incomes")
@@ -102,8 +106,8 @@ public class IncomeController {
String email = userDetails.getUsername();
List<IncomeDTO> incomes;
incomes = date.map(localDate -> incomeService.getTransactionsByDate(localDate).stream().map(incomeMapper::toDto).toList())
.orElseGet(() -> month.map(value -> incomeService.getTransactionsByMonth(value).stream().map(incomeMapper::toDto).toList())
incomes = date.map(localDate -> incomeService.getTransactionsByDate(localDate, email).stream().map(incomeMapper::toDto).toList())
.orElseGet(() -> month.map(value -> incomeService.getTransactionsByMonth(value, email).stream().map(incomeMapper::toDto).toList())
.orElseGet(() -> incomeService.getTransactionsByEmail(email).stream().map(incomeMapper::toDto).toList()));
if (!incomes.isEmpty()) {

View File

@@ -5,7 +5,10 @@ import com.faf223.expensetrackerfaf.dto.UserDTO;
import com.faf223.expensetrackerfaf.dto.mappers.UserMapper;
import com.faf223.expensetrackerfaf.model.User;
import com.faf223.expensetrackerfaf.service.UserService;
import com.faf223.expensetrackerfaf.util.errors.ErrorResponse;
import com.faf223.expensetrackerfaf.util.exceptions.UserNotCreatedException;
import com.faf223.expensetrackerfaf.util.exceptions.UserNotFoundException;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -26,8 +29,11 @@ public class UserController {
private final UserMapper userMapper;
@PatchMapping()
public ResponseEntity<UserDTO> updateUser(@RequestBody UserCreationDTO userDTO,
public ResponseEntity<UserDTO> updateUser(@RequestBody @Valid UserCreationDTO userDTO,
BindingResult bindingResult) {
if(bindingResult.hasErrors())
throw new UserNotCreatedException(ErrorResponse.from(bindingResult).getMessage());
User user = userMapper.toUser(userDTO);
if (!bindingResult.hasErrors()) {
userService.updateUser(user);
@@ -37,7 +43,7 @@ public class UserController {
}
}
@GetMapping("/getUserData")
@GetMapping("/get-user-data")
public ResponseEntity<UserDTO> getUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

View File

@@ -13,10 +13,10 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
public class RegisterRequest {
private String firstname; // Change field name to match JSON
private String lastname; // Change field name to match JSON
private String username; // Change field name to match JSON
private String email; // Change field name to match JSON
private String firstname;
private String lastname;
private String username;
private String email;
private String password;
private Role role;
}