Skip to content

Commit

Permalink
Mosip 26247 fix update otp validation issue in update contact (#772)
Browse files Browse the repository at this point in the history
* Fix class cast issue

* MOSIP-26247 WIP-fix-to-double-entry-for-update-contact

* Test fixes

* Code fix

---------

Co-authored-by: Loganathan Sekar <[email protected]>
  • Loading branch information
loganathan-sekaran and Loganathan Sekar authored Feb 22, 2023
1 parent dc2847e commit adaefe4
Show file tree
Hide file tree
Showing 10 changed files with 33 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ public ResponseWrapper<Object> updateUin(
ResponseWrapper<Object> response = new ResponseWrapper<>();
audit.setAuditRequestDto(
EventEnum.getEventEnumWithValue(EventEnum.UPDATE_UIN, requestDTO.getRequest().getTransactionID()));
response.setResponse(residentService.reqUinUpdate(requestDTO.getRequest()));
response.setResponse(residentService.reqUinUpdate(requestDTO.getRequest()).getT1());
audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.UPDATE_UIN_SUCCESS,
requestDTO.getRequest().getTransactionID()));
return response;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import io.mosip.resident.dto.OtpRequestDTOV2;
import io.mosip.resident.exception.ApisResourceAccessException;
import io.mosip.resident.exception.ResidentServiceCheckedException;
import reactor.util.function.Tuple2;

import java.io.IOException;

Expand All @@ -14,4 +15,5 @@
public interface OtpManager {
public boolean sendOtp(MainRequestDTO<OtpRequestDTOV2> requestDTO, String channelType, String language) throws IOException, ResidentServiceCheckedException, ApisResourceAccessException;
public boolean validateOtp(String otp, String userId, String transactionId) throws ApisResourceAccessException, ResidentServiceCheckedException;
public Tuple2<Object, String> updateUserId(String userId, String transactionId) throws ApisResourceAccessException, ResidentServiceCheckedException;
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public ResponseDTO reqAauthTypeStatusUpdate(AuthLockOrUnLockRequestDto dto, Auth

public AuthHistoryResponseDTO reqAuthHistory(AuthHistoryRequestDTO dto) throws ResidentServiceCheckedException;

public Object reqUinUpdate(ResidentUpdateRequestDto dto) throws ResidentServiceCheckedException;
public Tuple2<Object, String> reqUinUpdate(ResidentUpdateRequestDto dto) throws ResidentServiceCheckedException;

public Tuple2<Object, String> reqUinUpdate(ResidentUpdateRequestDto dto, JSONObject demographicJsonObject) throws ResidentServiceCheckedException;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
import io.mosip.resident.service.ResidentService;
import io.mosip.resident.util.TemplateUtil;
import io.mosip.resident.validator.RequestValidator;
import reactor.util.function.Tuple2;

import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
Expand Down Expand Up @@ -180,14 +182,16 @@ private String generateOTP(MainRequestDTO<OtpRequestDTOV2> requestDTO) {
}

@Override
public boolean validateOtp(String otp, String userId, String transactionId) throws ApisResourceAccessException, ResidentServiceCheckedException {
public boolean validateOtp(String otp, String userId, String transactionId) throws ApisResourceAccessException, ResidentServiceCheckedException {
logger.info("sessionId", "idType", "id", "In validateOtp method of otpmanager service ");
String otpHash;
otpHash = digestAsPlainText(
(userId + this.environment.getProperty("mosip.kernel.data-key-splitter") + otp+transactionId).getBytes());

if (!otpRepo.existsByOtpHashAndStatusCode(otpHash, PreRegLoginConstant.ACTIVE_STATUS))
if (!otpRepo.existsByOtpHashAndStatusCode(otpHash, PreRegLoginConstant.ACTIVE_STATUS)) {
return false;
}

OtpTransactionEntity otpTxn = otpRepo.findTopByOtpHashAndStatusCode(otpHash, PreRegLoginConstant.ACTIVE_STATUS);
otpTxn.setStatusCode(PreRegLoginConstant.USED_STATUS);
otpRepo.save(otpTxn);
Expand All @@ -197,19 +201,18 @@ public boolean validateOtp(String otp, String userId, String transactionId) thro
throw new ResidentServiceException(ResidentErrorCode.EXPIRED_OTP.getErrorCode(),
ResidentErrorCode.EXPIRED_OTP.getErrorMessage());
}
updateUinData(userId, transactionId);
return true;
}

public void updateUinData(String userId, String transactionId) throws ApisResourceAccessException, ResidentServiceCheckedException {
public Tuple2<Object, String> updateUserId(String userId, String transactionId) throws ApisResourceAccessException, ResidentServiceCheckedException {
ResidentUpdateRequestDto residentUpdateRequestDto = new ResidentUpdateRequestDto();
String individualId= identityService.getResidentIndvidualId();
String individualIdType = templateUtil.getIndividualIdType();
residentUpdateRequestDto.setIndividualId(individualId);
residentUpdateRequestDto.setConsent(ACCEPTED);
residentUpdateRequestDto.setIdentityJson(getIdentityJson(individualId, transactionId, userId, individualIdType));
residentUpdateRequestDto.setIndividualIdType(individualIdType);
residentService.reqUinUpdate(residentUpdateRequestDto);
return residentService.reqUinUpdate(residentUpdateRequestDto);
}

public String getIdentityJson(String individualId, String transactionId, String userId, String individualIdType) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,60 +143,39 @@ public Tuple2<MainResponseDTO<AuthNResponse>, String> validateWithUserIdOtp(Main
String userid = null;
boolean isSuccess = false;
String eventId = ResidentConstants.NOT_AVAILABLE;
ResidentTransactionEntity residentTransactionEntity=null;

try {
residentTransactionEntity = createResidentTransactionEntity(userIdOtpRequest.getRequest().getUserId());
if (residentTransactionEntity != null) {
eventId = residentTransactionEntity.getEventId();
}
OtpRequestDTOV3 user = userIdOtpRequest.getRequest();
userid = user.getUserId();
boolean validated = otpManager.validateOtp(user.getOtp(), user.getUserId(), user.getTransactionId());
String transactionId = user.getTransactionId();
boolean validated = otpManager.validateOtp(user.getOtp(), userid, transactionId);
AuthNResponse authresponse = new AuthNResponse();
if (validated) {
Tuple2<Object, String> updateResult = otpManager.updateUserId(userid, transactionId);
eventId = updateResult.getT2();
authresponse.setMessage(PreRegLoginConstant.VALIDATION_SUCCESS);
authresponse.setStatus(PreRegLoginConstant.SUCCESS);

} else {
residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name());
residentTransactionEntity.setRequestSummary("failed");
throw new ResidentServiceException(ResidentErrorCode.OTP_VALIDATION_FAILED,
Map.of(ResidentConstants.EVENT_ID, eventId));
}
response.setResponse(authresponse);
isSuccess = true;
} catch (ResidentServiceException ex) {
residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name());
residentTransactionEntity.setRequestSummary("failed");
log.error("In calluserIdOtp method of login service- ", ex);
throw new ResidentServiceException(ResidentErrorCode.OTP_VALIDATION_FAILED, ex,
Map.of(ResidentConstants.EVENT_ID, eventId));
ex.setMetadata(Map.of(ResidentConstants.EVENT_ID, eventId));
throw ex;
} catch (RuntimeException ex) {
residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name());
residentTransactionEntity.setRequestSummary("failed");
log.error("In calluserIdOtp method of login service- ", ex);
throw new ResidentServiceException(ResidentErrorCode.OTP_VALIDATION_FAILED, ex,
Map.of(ResidentConstants.EVENT_ID, eventId));
} catch (ResidentServiceCheckedException e) {
residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name());
residentTransactionEntity.setRequestSummary("failed");
throw new ResidentServiceException(ResidentErrorCode.OTP_VALIDATION_FAILED, e,
Map.of(ResidentConstants.EVENT_ID, eventId));
} catch (ApisResourceAccessException e) {
residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name());
residentTransactionEntity.setRequestSummary("failed");
throw new ResidentServiceException(ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION, e,
Map.of(ResidentConstants.EVENT_ID, eventId));
} finally {
if(residentTransactionEntity.getStatusCode()==null) {
residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name());
}
if (residentTransactionEntity.getRequestSummary() == null) {
residentTransactionEntity.setRequestSummary("failed");
}
residentTransactionRepository.save(residentTransactionEntity);

response.setResponsetime(GenericUtil.getCurrentResponseTime());

if (isSuccess) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -818,13 +818,13 @@ private NotificationResponseDTO trySendNotification(String id, NotificationTempl
}

@Override
public Object reqUinUpdate(ResidentUpdateRequestDto dto) throws ResidentServiceCheckedException {
public Tuple2<Object, String> reqUinUpdate(ResidentUpdateRequestDto dto) throws ResidentServiceCheckedException {
byte[] decodedDemoJson = CryptoUtil.decodeURLSafeBase64(dto.getIdentityJson());
JSONObject demographicJsonObject;
try {
demographicJsonObject = JsonUtil.readValue(new String(decodedDemoJson), JSONObject.class);
JSONObject demographicIdentity = JsonUtil.getJSONObject(demographicJsonObject, IDENTITY);
return reqUinUpdate(dto, demographicIdentity).getT1();
return reqUinUpdate(dto, demographicIdentity);
} catch (IOException e) {
audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.IO_EXCEPTION, dto.getTransactionID(),
"Request for UIN update"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.web.client.RestTemplate;

import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;

import javax.crypto.SecretKey;
Expand Down Expand Up @@ -411,7 +413,7 @@ public void testRequestUINUpdate() throws Exception {
reqWrapper.setRequest(dto);
reqWrapper.setId("mosip.resident.uin");
reqWrapper.setVersion("v1");
Mockito.when(residentService.reqUinUpdate(Mockito.any())).thenReturn(new Object());
Mockito.when(residentService.reqUinUpdate(Mockito.any())).thenReturn(Tuples.of(new Object(), "123"));
String requestAsString = gson.toJson(reqWrapper);
this.mockMvc.perform(post("/req/update-uin").contentType(MediaType.APPLICATION_JSON).content(requestAsString))
.andExpect(status().isOk());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@ public void setup() throws ApisResourceAccessException, ResidentServiceCheckedEx
Mockito.when(environment.getProperty("otp.request.flooding.duration", Long.class)).thenReturn(45L);
Mockito.when(environment.getProperty("mosip.kernel.otp.expiry-time", Long.class)).thenReturn(45L);
Mockito.when(environment.getProperty("otp.request.flooding.max-count", Integer.class)).thenReturn(8);
Mockito.when(requestValidator.validateUserIdAndTransactionId(Mockito.anyString(), Mockito.anyString())).thenReturn(List.of("EMAIL"));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
import io.mosip.resident.util.TemplateUtil;
import io.mosip.resident.util.Utility;
import io.mosip.resident.validator.RequestValidator;
import reactor.util.function.Tuples;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
Expand Down Expand Up @@ -150,8 +152,6 @@ public void setup() throws ApisResourceAccessException, ResidentServiceCheckedEx
MainResponseDTO<AuthNResponse> response = new MainResponseDTO<>();
response.setResponse(authNResponse);
responseEntity = new ResponseEntity<>(HttpStatus.OK);
Mockito.when(utility.createEntity()).thenReturn(new ResidentTransactionEntity());
Mockito.when(utility.createEventId()).thenReturn("12345");
}

@Test
Expand Down Expand Up @@ -214,6 +214,7 @@ public void testValidateOtpSuccess() throws ResidentServiceCheckedException, Api
otpRequestDTOV3.setTransactionId("122222222");
requestDTO1.setRequest(otpRequestDTOV3);
Mockito.when(otpManager.validateOtp(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(true);
Mockito.when(otpManager.updateUserId(Mockito.anyString(), Mockito.anyString())).thenReturn(Tuples.of(new Object(), "12345"));
assertEquals("12345", proxyOtpService.validateWithUserIdOtp(requestDTO1).getT2());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
import io.mosip.resident.util.ResidentServiceRestClient;
import io.mosip.resident.util.Utilities;
import io.mosip.resident.util.Utility;
import reactor.util.function.Tuple2;

@RunWith(SpringRunner.class)
public class ResidentServiceResUpdateTest {
Expand Down Expand Up @@ -282,8 +283,8 @@ public void reqUinUpdateSearchMachineInMasterServiceThrowsResidentMachineService

@Test
public void reqUinUpdateGetMachineIdTest() throws BaseCheckedException, IOException {
Object residentUpdateResponseDTO = residentServiceImpl.reqUinUpdate(dto);
assertEquals(((ResidentUpdateResponseDTO) residentUpdateResponseDTO).getRegistrationId(), updateDto.getRegistrationId());
Tuple2<Object, String> residentUpdateResponseDTO = residentServiceImpl.reqUinUpdate(dto);
assertEquals(((ResidentUpdateResponseDTO) residentUpdateResponseDTO.getT1()).getRegistrationId(), updateDto.getRegistrationId());
}

@Test
Expand Down Expand Up @@ -322,15 +323,15 @@ public void reqUinUpdateGetMachineIdIsNullTest() throws BaseCheckedException, IO
Mockito.when(env.getProperty(ApiName.MACHINECREATE.name())).thenReturn("MACHINECREATE");
Mockito.when(residentServiceRestClient.postApi(eq("MACHINECREATE"), any(MediaType.class), any(HttpEntity.class),
eq(MachineCreateResponseDTO.class))).thenReturn(machineCreateResponseDTO);
Object residentUpdateResponseDTO = residentServiceImpl.reqUinUpdate(dto);
assertEquals(((ResidentUpdateResponseDTO) residentUpdateResponseDTO).getRegistrationId(), updateDto.getRegistrationId());
Tuple2<Object, String> residentUpdateResponseDTO = residentServiceImpl.reqUinUpdate(dto);
assertEquals(((ResidentUpdateResponseDTO) residentUpdateResponseDTO.getT1()).getRegistrationId(), updateDto.getRegistrationId());
verify(residentServiceRestClient, atLeast(3)).postApi(any(), any(), any(), any(Class.class));
}

@Test
public void reqUinUpdateGetMachineIdReturnsTest() throws BaseCheckedException, IOException {
Object residentUpdateResponseDTO = residentServiceImpl.reqUinUpdate(dto);
assertEquals(((ResidentUpdateResponseDTO) residentUpdateResponseDTO).getRegistrationId(), updateDto.getRegistrationId());
Tuple2<Object, String> residentUpdateResponseDTO = residentServiceImpl.reqUinUpdate(dto);
assertEquals(((ResidentUpdateResponseDTO) residentUpdateResponseDTO.getT1()).getRegistrationId(), updateDto.getRegistrationId());
verify(residentServiceRestClient, atLeast(2)).postApi(any(), any(), any(), any(Class.class));
}

Expand Down

0 comments on commit adaefe4

Please sign in to comment.