Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/add input validation #6

Open
wants to merge 5 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,26 @@
import com.google.maps.errors.ApiError;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class ApiExceptionControllerAdvice extends ResponseEntityExceptionHandler {
Expand All @@ -28,7 +39,10 @@ public class ApiExceptionControllerAdvice extends ResponseEntityExceptionHandler
* @return a {@code ResponseEntity} instance
*/
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
ApiError error = new ApiError();
error.code = 400;
error.status = HttpStatus.BAD_REQUEST.toString();
Expand All @@ -37,22 +51,22 @@ protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotRead
}

@ExceptionHandler(InternalException.class)
protected ResponseEntity<Object> handleInternalExceptions(InternalException exp) {
protected ResponseEntity<Object> handleInternalException(InternalException exp) {
ApiError error = new ApiError();
error.code = 500;
error.status = HttpStatus.INTERNAL_SERVER_ERROR.toString();
error.message = "Uh oh! something went wrong processing your request. Please try again or advise the administrator.";
error.message = exp.getMessage();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I dont think we should show the customer intneral message. The previous approach was better. Also i added some code to log this exception since we are overriding it



return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}

@ExceptionHandler(BusinessAlreadyClaimedException.class)
protected ResponseEntity<Object> handleBusinessAlreadyClaimedExceptions(BusinessAlreadyClaimedException exp) {
protected ResponseEntity<Object> handleBusinessAlreadyClaimedException(BusinessAlreadyClaimedException exp) {
ApiError error = new ApiError();
error.code = 409;
error.status = HttpStatus.BAD_REQUEST.toString();
error.message = "Business has already been claimed. Please contact administrator for assistance.";
error.status = HttpStatus.CONFLICT.toString();
error.message = exp.getMessage();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment lets not show user internal message.


return new ResponseEntity<>(error, HttpStatus.CONFLICT);
}
Expand All @@ -68,7 +82,7 @@ protected ResponseEntity<Object> handleBusinessClaimExceptions(BusinessClaimExce
}

@ExceptionHandler(BusinessNotFoundException.class)
protected ResponseEntity<Object> handleBusinessNotFoundExceptionExceptions(BusinessNotFoundException exp) {
protected ResponseEntity<Object> handleBusinessNotFoundException(BusinessNotFoundException exp) {
ApiError error = new ApiError();
error.code = 404;
error.status = HttpStatus.NOT_FOUND.toString();
Expand All @@ -78,7 +92,7 @@ protected ResponseEntity<Object> handleBusinessNotFoundExceptionExceptions(Busin
}

@ExceptionHandler(PaymentServiceException.class)
protected ResponseEntity<Object> handlePaymentServiceExceptions(PaymentServiceException exp) {
protected ResponseEntity<Object> handlePaymentServiceException(PaymentServiceException exp) {
ApiError error = new ApiError();
error.code = 500;
error.status = HttpStatus.INTERNAL_SERVER_ERROR.toString();
Expand All @@ -88,7 +102,7 @@ protected ResponseEntity<Object> handlePaymentServiceExceptions(PaymentServiceEx
}

@ExceptionHandler(PaymentAccountNotSetupException.class)
protected ResponseEntity<Object> handlePaymentAccountNotSetupExceptionExceptions(PaymentAccountNotSetupException exp) {
protected ResponseEntity<Object> handlePaymentAccountNotSetupException(PaymentAccountNotSetupException exp) {
ApiError error = new ApiError();
error.code = 400;
error.status = HttpStatus.BAD_REQUEST.toString();
Expand All @@ -97,4 +111,50 @@ protected ResponseEntity<Object> handlePaymentAccountNotSetupExceptionExceptions
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}

}
/**
* Customize the response for MethodArgumentNotValidException.
* <p>This method delegates to {@link #handleExceptionInternal}.
*
* @param exp the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
*/
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException exp,
HttpHeaders headers, HttpStatus status, WebRequest request) {
Map<String, String> fieldErrorMap = new HashMap<>();
List<ObjectError> fieldErrors = exp.getBindingResult().getAllErrors();
fieldErrors.forEach((error) -> {
String errMessage = error.getDefaultMessage();
String fieldId = ((FieldError) error).getField();
fieldErrorMap.put(fieldId, errMessage);
});

return new ResponseEntity<>(fieldErrorMap, HttpStatus.BAD_REQUEST);
}

@ExceptionHandler(ConstraintViolationException.class)
protected ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException exp) {
Map<String, String> constraintErrors = new HashMap<>();
Set<ConstraintViolation<?>> constraintViolations = exp.getConstraintViolations();
constraintViolations.forEach((constraintViolation) -> {
String errMessage = constraintViolation.getMessage();
String constraintPath = constraintViolation.getPropertyPath().toString();
constraintErrors.put(constraintPath, errMessage);
});

return new ResponseEntity<>(constraintErrors, HttpStatus.BAD_REQUEST);
}

@ExceptionHandler(ConversionFailedException.class)
protected ResponseEntity<Object> handleConversionFailedException(ConversionFailedException exp) {
ApiError error = new ApiError();
error.code = 400;
error.status = HttpStatus.BAD_REQUEST.toString();
error.message = "Invalid value provided.";

return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public String approveBusiness(@PathVariable("id") UUID id,
return ownerService.approveClaim(paymentSystem, id);
}

// TODO (Deba) refactor the method name.
@RequestMapping(value = "business/{id}/decline", method = RequestMethod.GET)
public void approveBusiness(@PathVariable UUID id) throws
BusinessNotFoundException, InternalException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,24 @@
import com.coronacarecard.model.PagedBusinessSearchResult;
import com.coronacarecard.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("business")
@Validated
public class BusinessController {

@Autowired
private BusinessService businessService;

@GetMapping("/import")
public Business importFromGoogle(@RequestParam(value = "googleplaceid") String googlePlaceId)
public Business importFromGoogle(@NotEmpty @NotNull @RequestParam(value = "googleplaceid") String googlePlaceId)
throws BusinessNotFoundException, InternalException {
return businessService.getOrCreate(googlePlaceId);
}
Expand All @@ -32,15 +36,15 @@ public Business getBusiness(@PathVariable String externalId) throws
}

@GetMapping("/update")
public Business updateFromGoogle(@RequestParam(value = "googleplaceid") String googlePlaceId)
public Business updateFromGoogle(@NotEmpty @NotNull @RequestParam(value = "googleplaceid") String googlePlaceId)
throws BusinessNotFoundException, InternalException {
return businessService.createOrUpdate(googlePlaceId);
}

@GetMapping("/searchexternal")
public List<BusinessSearchResult> searchExternal(@RequestParam(value = "searchtext") String searchText,
@RequestParam(value = "latitude") Optional<Double> latitude,
@RequestParam(value = "longitude") Optional<Double> longitude)
public List<BusinessSearchResult> searchExternal(@NotNull @NotEmpty @RequestParam(value = "searchtext") String searchText,
@RequestParam(value = "latitude") Optional<Double> latitude,
@RequestParam(value = "longitude") Optional<Double> longitude)
throws InternalException {

return businessService.externalSearch(searchText,
Expand All @@ -49,8 +53,8 @@ public List<BusinessSearchResult> searchExternal(@RequestParam(value = "searchte
}

@GetMapping("/search")
public PagedBusinessSearchResult search(@RequestParam(value = "searchtext") String searchText,
@RequestParam(value = "page", defaultValue = "1") Integer page ,
public PagedBusinessSearchResult search(@NotNull @NotEmpty @RequestParam(value = "searchtext") String searchText,
@RequestParam(value = "page", defaultValue = "1") Integer page,
@RequestParam(value = "count", defaultValue = "10") Integer count) {
return businessService.search(searchText, page, count);
}
Expand Down
12 changes: 5 additions & 7 deletions src/main/java/com/coronacarecard/controller/OwnerController.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,17 @@
import com.coronacarecard.service.CryptoService;
import com.coronacarecard.service.OwnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@RequestMapping("owner")
@Validated
public class OwnerController {

@Autowired
Expand All @@ -24,20 +28,14 @@ public class OwnerController {
@Autowired
private CryptoService cryptoService;



@PostMapping("/claim")
public ClaimResult claim(@RequestBody BusinessRegistrationRequest businessRegistrationRequest)
public ClaimResult claim(@Valid @RequestBody BusinessRegistrationRequest businessRegistrationRequest)
throws BusinessNotFoundException, InternalException, BusinessAlreadyClaimedException {

Business claimedBusiness = ownerService.claimBusiness(businessRegistrationRequest);
return ClaimResult.builder()
.business(claimedBusiness)
.claimToken(claimedBusiness.getId().toString())
.build();

}



}
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@
import com.coronacarecard.exceptions.InternalException;
import com.coronacarecard.exceptions.PaymentAccountNotSetupException;
import com.coronacarecard.model.CheckoutResponse;
import com.coronacarecard.model.orders.OrderDetail;
import com.coronacarecard.model.PaymentSystem;
import com.coronacarecard.model.orders.OrderDetail;
import com.coronacarecard.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@RequestMapping("cart")
Expand All @@ -18,7 +23,7 @@ public class ShoppingCartController {
private ShoppingCartService shoppingCartService;

@PostMapping("/checkout")
public CheckoutResponse checkout(@RequestBody OrderDetail order) throws BusinessNotFoundException,
public CheckoutResponse checkout(@Valid @RequestBody OrderDetail order) throws BusinessNotFoundException,
PaymentAccountNotSetupException, InternalException {
return shoppingCartService.checkout(PaymentSystem.STRIPE, order);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,19 @@
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("payment/stripe")
@Validated
public class StripePaymentController {
private static Log log = LogFactory.getLog(StripePaymentController.class);

Expand Down Expand Up @@ -66,8 +70,8 @@ public String onboard(@PathVariable UUID id) throws BusinessNotFoundException, I

@GetMapping("/business/confirm")
@Transactional
public void confirm(@RequestParam(value = "code") String code,
@RequestParam(value = "state") String state,
public void confirm(@NotEmpty @NotNull @RequestParam(value = "code") String code,
@NotEmpty @NotNull @RequestParam(value = "state") String state,
HttpServletResponse httpServletResponse)
throws BusinessClaimException, BusinessNotFoundException, IOException, InternalException,
PaymentServiceException, BusinessAlreadyClaimedException {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
package com.coronacarecard.model;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

@lombok.Builder
@lombok.NoArgsConstructor
@lombok.AllArgsConstructor
@lombok.Getter
public class BusinessRegistrationRequest {
@NotNull
@NotEmpty
private String businessId;
@NotNull
@NotEmpty
@Email
private String email;
private String phone;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we validate phone number?

private String description;

}
12 changes: 12 additions & 0 deletions src/main/java/com/coronacarecard/model/orders/OrderDetail.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

import com.coronacarecard.model.Currency;

import javax.validation.constraints.Email;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;
import java.util.UUID;
Expand All @@ -13,11 +17,19 @@
@lombok.Setter
public class OrderDetail implements Serializable {
private UUID id;
@NotEmpty
@NotNull
@Email
private String customerEmail;
private String customerMobile;
@NotNull
@NotEmpty
private List<OrderLine> orderLine;
@Min(0)
private Double total;
@Min(0)
private Double contribution;
@Min(0)
private Double processingFee;
private Currency currency;
private OrderStatus status;
Expand Down
Loading