Skip to content

Commit

Permalink
Merge pull request #55 from Infosys/sachin-dev
Browse files Browse the repository at this point in the history
[ES-2012] added tests and improved code
  • Loading branch information
sacrana0 authored Jan 31, 2025
1 parent 5b21c82 commit 8922ea3
Show file tree
Hide file tree
Showing 13 changed files with 192 additions and 188 deletions.
4 changes: 4 additions & 0 deletions captcha-validation-service/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,20 @@

import java.util.ArrayList;

import io.mosip.captcha.util.CaptchaErrorCode;
import io.mosip.captcha.util.ErrorConstants;
import io.mosip.captcha.exception.CaptchaException;
import io.mosip.captcha.util.CaptchaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import io.mosip.captcha.dto.ExceptionJSONInfoDTO;
import io.mosip.captcha.dto.ResponseWrapper;
import io.mosip.captcha.exception.InvalidRequestCaptchaException;


@RestControllerAdvice
Expand All @@ -28,18 +30,17 @@ public class CaptchaExceptionHandler {
@Value("${mosip.captcha.api.version}")
private String captchaApiVersion;

@ExceptionHandler(InvalidRequestCaptchaException.class)
public ResponseWrapper<?> handleInvalidCaptchaRequest(InvalidRequestCaptchaException ex) {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ResponseWrapper<?>> handleInvalidCaptchaRequest(MethodArgumentNotValidException ex) {
ResponseWrapper<?> response = new ResponseWrapper<>();
response.setId(captchaApiId);
response.setVersion(captchaApiVersion);
response.setResponsetime(CaptchaUtils.getCurrentResponseTime());
response.setResponse(null);
ArrayList<ExceptionJSONInfoDTO> errors = new ArrayList<ExceptionJSONInfoDTO>();
ExceptionJSONInfoDTO errorDetails = new ExceptionJSONInfoDTO(ex.getErrorCode(), ex.getErrorMessage());
errors.add(errorDetails);
errors.add(new ExceptionJSONInfoDTO(ErrorConstants.INVALID_CAPTCHA_REQUEST, ErrorConstants.getErrorMessage(ErrorConstants.INVALID_CAPTCHA_REQUEST)));
response.setErrors(errors);
return response;
return new ResponseEntity<>(response, HttpStatus.OK);
}

@ExceptionHandler(CaptchaException.class)
Expand All @@ -64,7 +65,7 @@ public ResponseWrapper<?> handleException(Exception ex) {
response.setResponsetime(CaptchaUtils.getCurrentResponseTime());
response.setResponse(null);
ArrayList<ExceptionJSONInfoDTO> errors = new ArrayList<ExceptionJSONInfoDTO>();
ExceptionJSONInfoDTO errorDetails = new ExceptionJSONInfoDTO(CaptchaErrorCode.CAPTCHA_VALIDATION_FAILED.getErrorCode(), ex.getMessage());
ExceptionJSONInfoDTO errorDetails = new ExceptionJSONInfoDTO(ErrorConstants.CAPTCHA_VALIDATION_FAILED, ex.getMessage());
errors.add(errorDetails);
response.setErrors(errors);
return response;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
package io.mosip.captcha.controller;

import io.mosip.captcha.dto.*;
import io.mosip.captcha.exception.CaptchaException;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
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.RestController;

import io.mosip.captcha.dto.CaptchaRequestDTO;
import io.mosip.captcha.dto.RequestWrapper;
import io.mosip.captcha.exception.InvalidRequestCaptchaException;
import io.mosip.captcha.spi.CaptchaService;
import lombok.extern.slf4j.Slf4j;


@RestController
@Slf4j
public class CaptchaController {
Expand All @@ -25,10 +21,9 @@ public class CaptchaController {
private CaptchaService captchaService;

@PostMapping(path = "/validatecaptcha", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> validateCaptcha(@Validated @RequestBody RequestWrapper<CaptchaRequestDTO> captchaRequest,
Errors errors) throws CaptchaException, InvalidRequestCaptchaException {
log.debug("In captcha-validation-service controller to validate the recaptcha token", captchaRequest);
return new ResponseEntity<>(this.captchaService.validateCaptcha(captchaRequest.getRequest()), HttpStatus.OK);
public ResponseWrapper<CaptchaResponseDTO> validateCaptcha(@Valid @RequestBody RequestWrapper<CaptchaRequestDTO> captchaRequest) throws CaptchaException {
log.debug("In captcha-validation-service controller to validate the recaptcha token: {}", captchaRequest);
return this.captchaService.validateCaptcha(captchaRequest.getRequest());
}

}
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
package io.mosip.captcha.dto;

import java.io.Serializable;

import io.mosip.captcha.util.ErrorConstants;
import lombok.Data;
import jakarta.validation.constraints.NotBlank;

@Data
public class CaptchaRequestDTO implements Serializable{

/**
*
*/
public class CaptchaRequestDTO {

private static final long serialVersionUID = 1L;


@NotBlank(message = ErrorConstants.INVALID_CAPTCHA_REQUEST)
private String captchaToken;

private String moduleName;
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,15 @@

import com.fasterxml.jackson.annotation.JsonFormat;

import io.mosip.captcha.util.ErrorConstants;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;

/**
* This DTO class is used to define the initial request parameters.
*
Expand All @@ -25,34 +28,24 @@
*/
@Getter
@Setter
@NoArgsConstructor
@ToString
public class RequestWrapper<T> implements Serializable {

/** The Constant serialVersionUID. */
private static final long serialVersionUID = -4966448852014107698L;

/**
* Id
*/
private String id;
/**
* version
*/
private String version;
/**
* Request Date Time
*/

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
@Setter(AccessLevel.NONE)
@Getter(AccessLevel.NONE)
private Date requesttime;
/**
* Request Object
*/

@Valid
@NotNull(message = ErrorConstants.INVALID_CAPTCHA_REQUEST)
private T request;

public Date getRequesttime() {
return requesttime!=null ? new Date(requesttime.getTime()):null;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,35 +1,29 @@
package io.mosip.captcha.exception;

import io.mosip.captcha.util.ErrorConstants;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class CaptchaException extends Exception {

/**
*
*/
private static final long serialVersionUID = 1L;

public CaptchaException(String errorCode) {
this.errorCode = errorCode;
this.errorMessage = ErrorConstants.getErrorMessage(errorCode);
}

public CaptchaException(String errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;

}

private String errorCode;

private String errorMessage;

public String getErrorCode() {
return errorCode;
}

public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}

public String getErrorMessage() {
return errorMessage;
}

public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package io.mosip.captcha.service;

import java.util.HashMap;
import java.util.Map;

import io.mosip.captcha.util.CaptchaErrorCode;
import io.mosip.captcha.util.ErrorConstants;
import io.mosip.captcha.exception.CaptchaException;
import lombok.Getter;
import lombok.Setter;
Expand All @@ -11,16 +12,13 @@
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import io.mosip.captcha.dto.CaptchaRequestDTO;
import io.mosip.captcha.dto.CaptchaResponseDTO;
import io.mosip.captcha.dto.GoogleReCaptchaV2Response;
import io.mosip.captcha.dto.ResponseWrapper;
import io.mosip.captcha.exception.InvalidRequestCaptchaException;
import io.mosip.captcha.spi.CaptchaService;
import lombok.extern.slf4j.Slf4j;

Expand All @@ -34,35 +32,33 @@ public class CaptchaServiceImpl implements CaptchaService {
private Map<String, String> secret;

@Value("${mosip.captcha.verify-url}")
public String captchaVerifyUrl;
private String captchaVerifyUrl;

@Value("${mosip.captcha.default.module-name:preregistration}")
public String defaultModuleName;
private String defaultModuleName;

@Value("${mosip.captcha.api.id}")
public String captchaApiId;
private String captchaApiId;

@Value("${mosip.captcha.api.version}")
private String captchaApiVersion;

@Autowired
private RestTemplate restTemplate;

private final String CAPTCHA_SUCCESS = " Captcha successfully verified";
private final String CAPTCHA_SUCCESS = "Captcha successfully verified";

@Override
public Object validateCaptcha(Object captchaRequest) throws CaptchaException, InvalidRequestCaptchaException {
validateCaptchaRequest((CaptchaRequestDTO) captchaRequest);
String moduleName = ((CaptchaRequestDTO) captchaRequest).getModuleName();
public ResponseWrapper<CaptchaResponseDTO> validateCaptcha(CaptchaRequestDTO captchaRequest) throws CaptchaException {
String moduleName = captchaRequest.getModuleName();

MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
param.add("secret", secret.get(moduleName == null? defaultModuleName : moduleName));
param.add("response", ((CaptchaRequestDTO) captchaRequest).getCaptchaToken().trim());
Map<String, String> param = new HashMap<>();
param.put("secret", secret.get(moduleName == null? defaultModuleName : moduleName));
param.put("response", captchaRequest.getCaptchaToken().trim());

if(param.get("secret") == null) {
log.error("Failed to find secret for module {}", moduleName);
throw new CaptchaException(CaptchaErrorCode.CAPTCHA_VALIDATION_FAILED.getErrorCode(),
CaptchaErrorCode.CAPTCHA_VALIDATION_FAILED.getErrorCode());
throw new CaptchaException(ErrorConstants.CAPTCHA_VALIDATION_FAILED);
}

GoogleReCaptchaV2Response captchaResponse = null;
Expand All @@ -75,8 +71,7 @@ public Object validateCaptcha(Object captchaRequest) throws CaptchaException, In
}

if(captchaResponse == null)
throw new CaptchaException(CaptchaErrorCode.CAPTCHA_VALIDATION_FAILED.getErrorCode(),
CaptchaErrorCode.CAPTCHA_VALIDATION_FAILED.getErrorCode());
throw new CaptchaException(ErrorConstants.CAPTCHA_VALIDATION_FAILED);

if(!CollectionUtils.isEmpty(captchaResponse.getErrorCodes()))
throw new CaptchaException(captchaResponse.getErrorCodes().get(0), captchaResponse.getErrorCodes().get(0));
Expand All @@ -94,16 +89,7 @@ public Object validateCaptcha(Object captchaRequest) throws CaptchaException, In
}

//request is NOT success and error-codes is empty
throw new CaptchaException(CaptchaErrorCode.CAPTCHA_VALIDATION_FAILED.getErrorCode(),
CaptchaErrorCode.CAPTCHA_VALIDATION_FAILED.getErrorCode());
}

private void validateCaptchaRequest(CaptchaRequestDTO captchaRequest) throws InvalidRequestCaptchaException {
log.debug("{}", captchaRequest);
if (captchaRequest.getCaptchaToken() == null || captchaRequest.getCaptchaToken().trim().length() == 0) {
throw new InvalidRequestCaptchaException(CaptchaErrorCode.INVALID_CAPTCHA_REQUEST.getErrorCode(),
CaptchaErrorCode.INVALID_CAPTCHA_REQUEST.getErrorMessage());
}
throw new CaptchaException(ErrorConstants.CAPTCHA_VALIDATION_FAILED);
}

}
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package io.mosip.captcha.spi;

import io.mosip.captcha.dto.CaptchaRequestDTO;
import io.mosip.captcha.dto.CaptchaResponseDTO;
import io.mosip.captcha.dto.ResponseWrapper;
import io.mosip.captcha.exception.CaptchaException;
import io.mosip.captcha.exception.InvalidRequestCaptchaException;

public interface CaptchaService{

Object validateCaptcha(Object captchaRequest) throws CaptchaException, InvalidRequestCaptchaException;
ResponseWrapper<CaptchaResponseDTO> validateCaptcha(CaptchaRequestDTO captchaRequest) throws CaptchaException;


}
Loading

0 comments on commit 8922ea3

Please sign in to comment.