diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java index 74cf9589b0b..5292460d22d 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java @@ -1,387 +1,387 @@ -package io.mosip.registration.processor.biometric.authentication.stage; - -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.biometrics.entities.BIR; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.biometric.authentication.constants.BiometricAuthenticationConstants; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.core.constant.RegistrationType; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.AuthSystemException; -import io.mosip.registration.processor.core.exception.BioTypeException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.status.util.StatusUtil; -import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.packet.storage.utils.AuthUtil; -import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.status.code.RegistrationStatusCode; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.dto.SyncRegistrationDto; -import io.mosip.registration.processor.status.dto.SyncResponseDto; -import io.mosip.registration.processor.status.dto.SyncTypeDto; -import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.status.service.SyncRegistrationService; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.json.simple.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.util.List; -import java.util.stream.Collectors; - -@Service -public class BiometricAuthenticationStage extends MosipVerticleAPIManager { - private static Logger regProcLogger = RegProcessorLogger.getLogger(BiometricAuthenticationStage.class); - private static final String FILE_NOT_PRESENT_ERROR = "KER-PUT-007"; - - @Autowired - AuditLogRequestBuilder auditLogRequestBuilder; - - @Autowired - private Utilities utility; - - - - /** The registration status service. */ - @Autowired - RegistrationStatusService registrationStatusService; - - @Autowired - private AuthUtil authUtil; - - @Autowired - private PriorityBasedPacketManagerService packetManagerService; - - @Autowired - RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - @Value("${mosip.kernel.applicant.type.age.limit}") - private String ageLimit; - - /** server port number. */ - @Value("${server.port}") - private String port; - - /** worker pool size. */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** After this time intervel, message should be considered as expired (In seconds). */ - @Value("${mosip.regproc.biometric.authentication.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - /** The mosip event bus. */ - MosipEventBus mosipEventBus = null; - - /** Mosip router for APIs */ - @Autowired - MosipRouter router; - - @Autowired - private SyncRegistrationService syncRegistrationservice; - - public void deployVerticle() { - mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consumeAndSend(mosipEventBus, MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN, - MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_OUT, messageExpiryTimeLimit); - } - - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN, - MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_OUT)); - this.createServer(router.getRouter(), Integer.parseInt(port)); - } - - @Override - public MessageDTO process(MessageDTO object) { - TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "BiometricAuthenticationStage::BiometricAuthenticationStage::entry"); - String registrationId = object.getRid(); - object.setMessageBusAddress(MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN); - object.setIsValid(Boolean.FALSE); - object.setInternalError(Boolean.FALSE); - InternalRegistrationStatusDto registrationStatusDto=registrationStatusService - .getRegistrationStatus(registrationId); - - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.BIOMETRIC_AUTHENTICATION.toString()); - registrationStatusDto.setRegistrationStageName(this.getClass().getSimpleName()); - SyncRegistrationEntity regEntity = syncRegistrationservice.findByRegistrationId(registrationId); - String description = ""; - String code = ""; - boolean isTransactionSuccessful = false; - - try { - String process = registrationStatusDto.getRegistrationType(); - String registartionType = regEntity.getRegistrationType(); - int applicantAge = utility.getApplicantAge(registrationId, process, ProviderStageName.BIO_AUTH); - int childAgeLimit = Integer.parseInt(ageLimit); - String applicantType = BiometricAuthenticationConstants.ADULT; - if (applicantAge <= childAgeLimit && applicantAge > 0) { - applicantType = BiometricAuthenticationConstants.CHILD; - } - if (isUpdateAdultPacket(registartionType, applicantType)) { - - String biometricsLabel = packetManagerService.getFieldByMappingJsonKey( - registrationId, MappingJsonConstants.INDIVIDUAL_BIOMETRICS, registrationStatusDto.getRegistrationType(), ProviderStageName.BIO_AUTH); - if (StringUtils.isEmpty(biometricsLabel)) { - isTransactionSuccessful = checkIndividualAuthentication(registrationId, process, - registrationStatusDto); - description = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage() - : PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); - } else { - String individualBiometricsFileName = JsonUtil - .getJSONValue(JsonUtil.readValueWithUnknownProperties(biometricsLabel, JSONObject.class), - MappingJsonConstants.VALUE); - if (individualBiometricsFileName != null && !individualBiometricsFileName.isEmpty()) { - BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey( - registrationId, MappingJsonConstants.INDIVIDUAL_BIOMETRICS, process, ProviderStageName.BIO_AUTH); - if (biometricRecord == null || biometricRecord.getSegments() == null || biometricRecord.getSegments().isEmpty()) { - isTransactionSuccessful = false; - description = StatusUtil.BIOMETRIC_FILE_NOT_FOUND.getMessage(); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, description); - registrationStatusDto.setStatusComment(description); - registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_FILE_NOT_FOUND.getCode()); - } else { - isTransactionSuccessful = true; - } - } else { - isTransactionSuccessful = true; - description = PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage(); - } - } - } - - else { - object.setIsValid(true); - object.setInternalError(false); - isTransactionSuccessful = true; - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - "BiometricAuthenticationStage::success"); - if (SyncTypeDto.NEW.toString().equalsIgnoreCase(registartionType)) { - description = BiometricAuthenticationConstants.NEW_PACKET_DESCRIPTION + registrationId; - } else - description = BiometricAuthenticationConstants.CHILD_PACKET_DESCRIPTION + registrationId; - } - if (isTransactionSuccessful) { - object.setIsValid(Boolean.TRUE); - object.setInternalError(Boolean.FALSE); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getCode()); - registrationStatusDto.setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getMessage()); - } else { - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - registrationStatusDto.setStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - } - - } catch (IOException | NoSuchAlgorithmException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); - object.setIsValid(false); - object.setInternalError(true); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)); - code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_IOEXCEPTION.getCode(); - description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_IOEXCEPTION.getMessage(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, - description + e.getMessage() + ExceptionUtils.getStackTrace(e)); - } catch (JsonProcessingException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.JSON_PARSING_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)); - isTransactionSuccessful = false; - description = (PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage()); - code = (PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getCode()); - object.setIsValid(Boolean.FALSE); - object.setInternalError(Boolean.TRUE); - object.setRid(registrationStatusDto.getRegistrationId()); - e.printStackTrace(); - } catch (PacketManagerException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.PACKET_MANAGER_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_MANAGER_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - description = (PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getMessage()); - code = (PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getCode()); - object.setIsValid(Boolean.FALSE); - object.setInternalError(Boolean.TRUE); - object.setRid(registrationStatusDto.getRegistrationId()); - } catch (ApisResourceAccessException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage()+ e.getMessage())); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); - code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_API_RESOURCE_EXCEPTION.getCode(); - description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_API_RESOURCE_EXCEPTION.getMessage(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, - description + e.getMessage() + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - object.setIsValid(Boolean.FALSE); - } - catch (AuthSystemException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setSubStatusCode(StatusUtil.AUTH_SYSTEM_EXCEPTION.getCode()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.AUTH_SYSTEM_EXCEPTION.getMessage()+ e.getMessage())); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION)); - code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION.getCode(); - description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION.getMessage(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, - description + e.getMessage() + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - object.setIsValid(Boolean.FALSE); - - } - catch (Exception ex) { - registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + ex.getMessage())); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); - code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getCode(); - description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, - description + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); - object.setInternalError(Boolean.TRUE); - object.setIsValid(Boolean.FALSE); - - } finally { - - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getCode() - : code; - String moduleName = ModuleName.BIOMETRIC_AUTHENTICATION.toString(); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - description = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage() - : description; - String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); - String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description, eventId, eventName, eventType, moduleId, - moduleName, registrationId); - } - - return object; - } - - private boolean isUpdateAdultPacket(String registartionType, String applicantType) { - return (registartionType.equalsIgnoreCase(RegistrationType.UPDATE.name()) - || registartionType.equalsIgnoreCase(RegistrationType.RES_UPDATE.name())) - && applicantType.equalsIgnoreCase(BiometricAuthenticationConstants.ADULT); - } - - private boolean idaAuthenticate(List segments, String uin, InternalRegistrationStatusDto registrationStatusDto) - throws IOException, ApisResourceAccessException, BioTypeException, AuthSystemException, CertificateException, NoSuchAlgorithmException { - TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - - boolean idaAuth = false; - AuthResponseDTO authResponseDTO = authUtil.authByIdAuthentication(uin, - BiometricAuthenticationConstants.INDIVIDUAL_TYPE_UIN, segments); - if ((authResponseDTO.getErrors() == null || authResponseDTO.getErrors().isEmpty()) - && authResponseDTO.getResponse().isAuthStatus()) { - idaAuth = true; - } else { - List errors = authResponseDTO.getErrors(); - if (errors != null) { - if (errors.stream().anyMatch(error -> error.getErrorCode().equalsIgnoreCase("IDA-MLC-007"))) { - throw new AuthSystemException(PlatformErrorMessages.RPR_AUTH_SYSTEM_EXCEPTION.getMessage()); - } else { - String result = errors.stream().map(s -> s.getErrorMessage() + " ").collect(Collectors.joining()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setSubStatusCode(StatusUtil.INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED.getCode()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED.getMessage() - + result)); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), "", registrationStatusDto.getRegistrationId(), - "IDA Authentiacation failed - " + authResponseDTO.getErrors()); - idaAuth = false; - } - } - - } - return idaAuth; - } - - private boolean checkIndividualAuthentication(String registrationId, String process, - InternalRegistrationStatusDto registrationStatusDto) throws IOException, BioTypeException, - AuthSystemException, ApisResourceAccessException, PacketManagerException, JsonProcessingException, CertificateException, NoSuchAlgorithmException { - - BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey(registrationId, - MappingJsonConstants.AUTHENTICATION_BIOMETRICS, process, ProviderStageName.BIO_AUTH); - if (biometricRecord == null || CollectionUtils.isEmpty(biometricRecord.getSegments())) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto - .setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND.getCode()); - return false; - } - String uin = utility.getUIn(registrationId, process, ProviderStageName.BIO_AUTH); - - return idaAuthenticate(biometricRecord.getSegments(), uin, registrationStatusDto); - - } - -} +package io.mosip.registration.processor.biometric.authentication.stage; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.biometric.authentication.constants.BiometricAuthenticationConstants; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.ModuleName; +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.constant.RegistrationType; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.AuthSystemException; +import io.mosip.registration.processor.core.exception.BioTypeException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.status.util.StatusUtil; +import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.storage.utils.AuthUtil; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.dto.SyncRegistrationDto; +import io.mosip.registration.processor.status.dto.SyncResponseDto; +import io.mosip.registration.processor.status.dto.SyncTypeDto; +import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.status.service.SyncRegistrationService; + +@Service +public class BiometricAuthenticationStage extends MosipVerticleAPIManager { + private static Logger regProcLogger = RegProcessorLogger.getLogger(BiometricAuthenticationStage.class); + private static final String FILE_NOT_PRESENT_ERROR = "KER-PUT-007"; + + @Autowired + AuditLogRequestBuilder auditLogRequestBuilder; + + @Autowired + private Utilities utility; + + + + /** The registration status service. */ + @Autowired + RegistrationStatusService registrationStatusService; + + @Autowired + private AuthUtil authUtil; + + @Autowired + private PriorityBasedPacketManagerService packetManagerService; + + @Autowired + RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + @Value("${mosip.kernel.applicant.type.age.limit}") + private String ageLimit; + + /** server port number. */ + @Value("${server.port}") + private String port; + + /** worker pool size. */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** After this time intervel, message should be considered as expired (In seconds). */ + @Value("${mosip.regproc.biometric.authentication.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + /** The mosip event bus. */ + MosipEventBus mosipEventBus = null; + + /** Mosip router for APIs */ + @Autowired + MosipRouter router; + + @Autowired + private SyncRegistrationService syncRegistrationservice; + + public void deployVerticle() { + mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consumeAndSend(mosipEventBus, MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN, + MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_OUT, messageExpiryTimeLimit); + } + + @Override + public void start() { + router.setRoute(this.postUrl(getVertx(), MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN, + MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_OUT)); + this.createServer(router.getRouter(), Integer.parseInt(port)); + } + + @Override + public MessageDTO process(MessageDTO object) { + TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "BiometricAuthenticationStage::BiometricAuthenticationStage::entry"); + String registrationId = object.getRid(); + object.setMessageBusAddress(MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN); + object.setIsValid(Boolean.FALSE); + object.setInternalError(Boolean.FALSE); + InternalRegistrationStatusDto registrationStatusDto=registrationStatusService + .getRegistrationStatus(registrationId); + + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.BIOMETRIC_AUTHENTICATION.toString()); + registrationStatusDto.setRegistrationStageName(this.getClass().getSimpleName()); + SyncRegistrationEntity regEntity = syncRegistrationservice.findByRegistrationId(registrationId); + String description = ""; + String code = ""; + boolean isTransactionSuccessful = false; + + try { + String process = registrationStatusDto.getRegistrationType(); + String registartionType = regEntity.getRegistrationType(); + int applicantAge = utility.getApplicantAge(registrationId, process, ProviderStageName.BIO_AUTH); + int childAgeLimit = Integer.parseInt(ageLimit); + String applicantType = BiometricAuthenticationConstants.ADULT; + if (applicantAge <= childAgeLimit && applicantAge >= 0) { + applicantType = BiometricAuthenticationConstants.CHILD; + } + if (isUpdateAdultPacket(registartionType, applicantType)) { + + String biometricsLabel = packetManagerService.getFieldByMappingJsonKey( + registrationId, MappingJsonConstants.INDIVIDUAL_BIOMETRICS, registrationStatusDto.getRegistrationType(), ProviderStageName.BIO_AUTH); + if (StringUtils.isEmpty(biometricsLabel)) { + isTransactionSuccessful = checkIndividualAuthentication(registrationId, process, + registrationStatusDto); + description = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage() + : PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); + } else { + String individualBiometricsFileName = JsonUtil + .getJSONValue(JsonUtil.readValueWithUnknownProperties(biometricsLabel, JSONObject.class), + MappingJsonConstants.VALUE); + if (individualBiometricsFileName != null && !individualBiometricsFileName.isEmpty()) { + BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey( + registrationId, MappingJsonConstants.INDIVIDUAL_BIOMETRICS, process, ProviderStageName.BIO_AUTH); + if (biometricRecord == null || biometricRecord.getSegments() == null || biometricRecord.getSegments().isEmpty()) { + isTransactionSuccessful = false; + description = StatusUtil.BIOMETRIC_FILE_NOT_FOUND.getMessage(); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, description); + registrationStatusDto.setStatusComment(description); + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_FILE_NOT_FOUND.getCode()); + } else { + isTransactionSuccessful = true; + } + } else { + isTransactionSuccessful = true; + description = PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage(); + } + } + } + + else { + object.setIsValid(true); + object.setInternalError(false); + isTransactionSuccessful = true; + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + "BiometricAuthenticationStage::success"); + if (SyncTypeDto.NEW.toString().equalsIgnoreCase(registartionType)) { + description = BiometricAuthenticationConstants.NEW_PACKET_DESCRIPTION + registrationId; + } else + description = BiometricAuthenticationConstants.CHILD_PACKET_DESCRIPTION + registrationId; + } + if (isTransactionSuccessful) { + object.setIsValid(Boolean.TRUE); + object.setInternalError(Boolean.FALSE); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getCode()); + registrationStatusDto.setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getMessage()); + } else { + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + registrationStatusDto.setStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + } + + } catch (IOException | NoSuchAlgorithmException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); + object.setIsValid(false); + object.setInternalError(true); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)); + code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_IOEXCEPTION.getCode(); + description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_IOEXCEPTION.getMessage(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, + description + e.getMessage() + ExceptionUtils.getStackTrace(e)); + } catch (JsonProcessingException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.JSON_PARSING_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)); + isTransactionSuccessful = false; + description = (PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage()); + code = (PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getCode()); + object.setIsValid(Boolean.FALSE); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + e.printStackTrace(); + } catch (PacketManagerException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.PACKET_MANAGER_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_MANAGER_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + description = (PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getMessage()); + code = (PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getCode()); + object.setIsValid(Boolean.FALSE); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (ApisResourceAccessException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage()+ e.getMessage())); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); + code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_API_RESOURCE_EXCEPTION.getCode(); + description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_API_RESOURCE_EXCEPTION.getMessage(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, + description + e.getMessage() + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + object.setIsValid(Boolean.FALSE); + } + catch (AuthSystemException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setSubStatusCode(StatusUtil.AUTH_SYSTEM_EXCEPTION.getCode()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.AUTH_SYSTEM_EXCEPTION.getMessage()+ e.getMessage())); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION)); + code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION.getCode(); + description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION.getMessage(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, + description + e.getMessage() + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + object.setIsValid(Boolean.FALSE); + + } + catch (Exception ex) { + registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + ex.getMessage())); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); + code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getCode(); + description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, + description + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); + object.setInternalError(Boolean.TRUE); + object.setIsValid(Boolean.FALSE); + + } finally { + + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getCode() + : code; + String moduleName = ModuleName.BIOMETRIC_AUTHENTICATION.toString(); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + description = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage() + : description; + String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); + String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description, eventId, eventName, eventType, moduleId, + moduleName, registrationId); + } + + return object; + } + + private boolean isUpdateAdultPacket(String registartionType, String applicantType) { + return (registartionType.equalsIgnoreCase(RegistrationType.UPDATE.name()) + || registartionType.equalsIgnoreCase(RegistrationType.RES_UPDATE.name())) + && applicantType.equalsIgnoreCase(BiometricAuthenticationConstants.ADULT); + } + + private boolean idaAuthenticate(List segments, String uin, InternalRegistrationStatusDto registrationStatusDto) + throws IOException, ApisResourceAccessException, BioTypeException, AuthSystemException, CertificateException, NoSuchAlgorithmException { + TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); + + boolean idaAuth = false; + AuthResponseDTO authResponseDTO = authUtil.authByIdAuthentication(uin, + BiometricAuthenticationConstants.INDIVIDUAL_TYPE_UIN, segments); + if ((authResponseDTO.getErrors() == null || authResponseDTO.getErrors().isEmpty()) + && authResponseDTO.getResponse().isAuthStatus()) { + idaAuth = true; + } else { + List errors = authResponseDTO.getErrors(); + if (errors != null) { + if (errors.stream().anyMatch(error -> error.getErrorCode().equalsIgnoreCase("IDA-MLC-007"))) { + throw new AuthSystemException(PlatformErrorMessages.RPR_AUTH_SYSTEM_EXCEPTION.getMessage()); + } else { + String result = errors.stream().map(s -> s.getErrorMessage() + " ").collect(Collectors.joining()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setSubStatusCode(StatusUtil.INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED.getCode()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED.getMessage() + + result)); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), "", registrationStatusDto.getRegistrationId(), + "IDA Authentiacation failed - " + authResponseDTO.getErrors()); + idaAuth = false; + } + } + + } + return idaAuth; + } + + private boolean checkIndividualAuthentication(String registrationId, String process, + InternalRegistrationStatusDto registrationStatusDto) throws IOException, BioTypeException, + AuthSystemException, ApisResourceAccessException, PacketManagerException, JsonProcessingException, CertificateException, NoSuchAlgorithmException { + + BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey(registrationId, + MappingJsonConstants.AUTHENTICATION_BIOMETRICS, process, ProviderStageName.BIO_AUTH); + if (biometricRecord == null || CollectionUtils.isEmpty(biometricRecord.getSegments())) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto + .setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND.getCode()); + return false; + } + String uin = utility.getUIn(registrationId, process, ProviderStageName.BIO_AUTH); + + return idaAuthenticate(biometricRecord.getSegments(), uin, registrationStatusDto); + + } + +} diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/test/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStageTest.java b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/test/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStageTest.java index cd68bdb8265..a6eb6a5503a 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/test/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStageTest.java +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/test/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStageTest.java @@ -1,538 +1,547 @@ -package io.mosip.registration.processor.biometric.authentication.stage; - -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.read.ListAppender; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.mosip.kernel.biometrics.constant.BiometricType; -import io.mosip.kernel.biometrics.constant.QualityType; -import io.mosip.kernel.biometrics.entities.BDBInfo; -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.biometrics.entities.BIR; -import io.mosip.kernel.biometrics.entities.RegistryIDType; -import io.mosip.kernel.core.util.HMACUtils2; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; -import io.mosip.registration.processor.core.auth.dto.ErrorDTO; -import io.mosip.registration.processor.core.auth.dto.ResponseDTO; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.constant.RegistrationType; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.BioTypeException; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.packet.dto.FieldValue; -import io.mosip.registration.processor.core.packet.dto.Identity; -import io.mosip.registration.processor.core.packet.dto.masterdata.StatusResponseDto; -import io.mosip.registration.processor.core.spi.eventbus.EventHandler; -import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.util.IdentityIteratorUtil; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.packet.storage.utils.AuthUtil; -import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.rest.client.audit.dto.AuditResponseDto; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.dto.SyncRegistrationDto; -import io.mosip.registration.processor.status.dto.SyncResponseDto; -import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; -import io.mosip.registration.processor.status.repositary.RegistrationRepositary; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.status.service.SyncRegistrationService; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import org.apache.commons.io.IOUtils; -import org.json.simple.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.springframework.core.env.Environment; -import org.springframework.test.util.ReflectionTestUtils; - -import java.io.IOException; -import java.io.InputStream; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.spec.InvalidKeySpecException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.when; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ IOUtils.class, HMACUtils2.class, Utilities.class }) -@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*","javax.management.*", "javax.net.ssl.*" }) -public class BiometricAuthenticationStageTest { - - /** The input stream. */ - @Mock - private InputStream inputStream; - - - - /** The registration status service. */ - @Mock - RegistrationStatusService registrationStatusService; - - /** The packet info manager. */ - @Mock - private PacketInfoManager packetInfoManager; - - @Mock - private AuthUtil authUtil; - - @Mock - InternalRegistrationStatusDto registrationStatusDto; - - @Mock - private RegistrationProcessorRestClientService restClientService; - - @Mock - private IdentityIteratorUtil identityIteratorUtil; - - /** The dto. */ - MessageDTO dto = new MessageDTO(); - - @Mock - private PriorityBasedPacketManagerService packetManagerService; - - @Mock - private SyncRegistrationService syncRegistrationservice; - - /** The BiometricAuthenticationStage stage. */ - @InjectMocks - private BiometricAuthenticationStage biometricAuthenticationStage = new BiometricAuthenticationStage() { - @Override - public MosipEventBus getEventBus(Object verticleName, String url, int instanceNumber) { - vertx = Vertx.vertx(); - - return new MosipEventBus() { - - @Override - public Vertx getEventbus() { - return vertx; - } - - @Override - public void consume(MessageBusAddress fromAddress, - EventHandler>> eventHandler) { - - } - - @Override - public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAddress, - EventHandler>> eventHandler) { - - } - - @Override - public void send(MessageBusAddress toAddress, MessageDTO message) { - - } - }; - } - - @Override - public void consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - MessageBusAddress toAddress, long messageExpiryTimeLimit) { - } - }; - - /** The audit log request builder. */ - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - private Environment env; - - - - - /** The dto. */ - InternalRegistrationStatusDto statusDto; - /** The list. */ - List list; - - /** The list appender. */ - private ListAppender listAppender; - - @Mock - private RegistrationProcessorRestClientService registrationProcessorRestService; - - @Mock - private Utilities utility; - - @Mock - ObjectMapper mapIdentityJsonStringToObject; - - @Mock - private RegistrationRepositary registrationRepositary; - - StatusResponseDto statusResponseDto; - - @Mock - LogDescription description; - - @Mock - RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - private SyncRegistrationEntity regentity = Mockito.mock(SyncRegistrationEntity.class); - - /** - * Sets the up. - * - * @throws Exception - * the exception - */ - @Before - public void setUp() throws Exception { - ReflectionTestUtils.setField(biometricAuthenticationStage, "workerPoolSize", 10); - ReflectionTestUtils.setField(biometricAuthenticationStage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(biometricAuthenticationStage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(biometricAuthenticationStage, "ageLimit", "5"); - - - when(utility.getGetRegProcessorDemographicIdentity()).thenReturn("identity"); - - - list = new ArrayList(); - - listAppender = new ListAppender<>(); - - dto.setRid("2018701130000410092018110735"); - dto.setReg_type(RegistrationType.valueOf("UPDATE")); - - MockitoAnnotations.initMocks(this); - - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder( - "test case description", EventId.RPR_405.toString(), EventName.UPDATE.toString(), - EventType.BUSINESS.toString(), "1234testcase", ApiName.AUDIT); - - - - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("2018701130000410092018110735"); - registrationStatusDto.setStatusCode(""); - registrationStatusDto.setRegistrationType("UPDATE"); - listAppender.start(); - list.add(registrationStatusDto); - when(registrationStatusService.getByStatus(anyString())).thenReturn(list); - when(registrationStatusService.getRegistrationStatus(anyString())).thenReturn(registrationStatusDto); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); - - when(identityIteratorUtil.getFieldValue(any(), any())).thenReturn("UPDATE"); - - - Mockito.doNothing().when(description).setMessage(any()); - when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn(""); - - - statusResponseDto = new StatusResponseDto(); - statusResponseDto.setStatus("VALID"); - when(registrationProcessorRestService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(statusResponseDto); - - JSONObject jsonObject = Mockito.mock(JSONObject.class); - when(utility.getUIn(anyString(), anyString(), any())).thenReturn("12345678"); - when(utility.retrieveIdrepoJson(any())).thenReturn(jsonObject); - FieldValue fieldValue = new FieldValue(); - FieldValue fieldValue1 = new FieldValue(); - fieldValue1.setLabel("authenticationBiometricFileName"); - fieldValue1.setValue("biometricTestFileName"); - fieldValue.setLabel("registrationType"); - fieldValue.setValue("update"); - List metadata = new ArrayList<>(); - metadata.add(fieldValue); - metadata.add(fieldValue1); - - - when(utility.getDefaultSource(any(), any())).thenReturn("reg-client"); - when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(21); - - regentity.setRegistrationType("update"); - when(syncRegistrationservice.findByRegistrationId(any())).thenReturn(regentity); - - AuthResponseDTO authResponseDTO = new AuthResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - responseDTO.setAuthStatus(true); - authResponseDTO.setResponse(responseDTO); - when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); - - List birTypeList = new ArrayList<>(); - BIR birType1 = new BIR.BIRBuilder().build(); - BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); - RegistryIDType registryIDType = new RegistryIDType(); - registryIDType.setOrganization("Mosip"); - registryIDType.setType("257"); - QualityType quality = new QualityType(); - quality.setAlgorithm(registryIDType); - quality.setScore(90l); - bdbInfoType1.setQuality(quality); - BiometricType singleType1 = BiometricType.FINGER; - List singleTypeList1 = new ArrayList<>(); - singleTypeList1.add(singleType1); - List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); - bdbInfoType1.setSubtype(subtype1); - bdbInfoType1.setType(singleTypeList1); - birType1.setBdbInfo(bdbInfoType1); - birTypeList.add(birType1); - - BiometricRecord biometricRecord = new BiometricRecord(); - biometricRecord.setSegments(birTypeList); - - when(packetManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())).thenReturn(biometricRecord); - - - } - - @Test - public void biometricAuthenticationSuccessTest() throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { - when(regentity.getRegistrationType()).thenReturn("UPDATE"); - List birTypeList = new ArrayList<>(); - BIR birType1 = new BIR.BIRBuilder().build(); - BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); - RegistryIDType registryIDType = new RegistryIDType(); - registryIDType.setOrganization("Mosip"); - registryIDType.setType("257"); - QualityType quality = new QualityType(); - quality.setAlgorithm(registryIDType); - quality.setScore(90l); - bdbInfoType1.setQuality(quality); - BiometricType singleType1 = BiometricType.FINGER; - List singleTypeList1 = new ArrayList<>(); - singleTypeList1.add(singleType1); - List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); - bdbInfoType1.setSubtype(subtype1); - bdbInfoType1.setType(singleTypeList1); - birType1.setBdbInfo(bdbInfoType1); - birTypeList.add(birType1); - - BiometricRecord biometricRecord = new BiometricRecord(); - biometricRecord.setSegments(birTypeList); - - when(packetManagerService.getBiometricsByMappingJsonKey(any(), - any(), any(),any())).thenReturn(biometricRecord); - - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getIsValid()); - } - - - @Test - public void IDAuthFailureTest() throws IOException, ApisResourceAccessException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, CertificateException { - AuthResponseDTO authResponseDTO = new AuthResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - responseDTO.setAuthStatus(false); - authResponseDTO.setResponse(responseDTO); - when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); - - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertFalse(messageDto.getIsValid()); - } - - @Test - public void childPacketTest() throws ApisResourceAccessException, JsonProcessingException, io.mosip.kernel.core.exception.IOException, PacketManagerException, IOException { - when(regentity.getRegistrationType()).thenReturn("UPDATE"); - when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(2); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getIsValid()); - } - - @Test - public void inputStreamNullIndividualAuthTest() throws ApisResourceAccessException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, IOException { - - HashMap hashMap = new HashMap(); - hashMap.put("value", "testFile"); - - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - - assertFalse(messageDto.getIsValid()); - } - - @Test - public void testIOException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { - - when(utility.getApplicantAge(any(),anyString(), any())).thenThrow(new IOException("IOException")); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getInternalError()); - } - - @Test - public void testApisResourceAccessException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { - - when(utility.getApplicantAge(anyString(),anyString(), any())) - .thenThrow(new ApisResourceAccessException("ApisResourceAccessException")); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getInternalError()); - } - - @Test - public void testException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { - - when(utility.getApplicantAge(anyString(),anyString(), any())) - .thenThrow( - new ApisResourceAccessException( - "test message")); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getInternalError()); - } - - @Test - public void resupdatePacketTest() throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { - when(regentity.getRegistrationType()).thenReturn("res_update"); - List birTypeList = new ArrayList<>(); - BIR birType1 = new BIR.BIRBuilder().build(); - BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); - RegistryIDType registryIDType = new RegistryIDType(); - registryIDType.setOrganization("Mosip"); - registryIDType.setType("257"); - QualityType quality = new QualityType(); - quality.setAlgorithm(registryIDType); - quality.setScore(90l); - bdbInfoType1.setQuality(quality); - BiometricType singleType1 = BiometricType.FINGER; - List singleTypeList1 = new ArrayList<>(); - singleTypeList1.add(singleType1); - List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); - bdbInfoType1.setSubtype(subtype1); - bdbInfoType1.setType(singleTypeList1); - birType1.setBdbInfo(bdbInfoType1); - birTypeList.add(birType1); - - BiometricRecord biometricRecord = new BiometricRecord(); - biometricRecord.setSegments(birTypeList); - when(packetManagerService.getBiometricsByMappingJsonKey(any(), any(), any(),any())).thenReturn(biometricRecord); - - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - - assertTrue(messageDto.getIsValid()); - } - - @Test - public void testNewPacket() throws IOException, - ApisResourceAccessException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, CertificateException { - - AuthResponseDTO authResponseDTO = new AuthResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - responseDTO.setAuthStatus(false); - authResponseDTO.setResponse(responseDTO); - when(regentity.getRegistrationType()).thenReturn("new"); - when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - - assertTrue(messageDto.getIsValid()); - } - - @Test - public void deployVerticle() { - - biometricAuthenticationStage.deployVerticle(); - } - @Test - public void testAuthSystemException() throws ApisResourceAccessException, IOException, InvalidKeySpecException, - NoSuchAlgorithmException, BioTypeException, JsonProcessingException, PacketManagerException, CertificateException { - List birTypeList = new ArrayList<>(); - BIR birType1 = new BIR.BIRBuilder().build(); - BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); - RegistryIDType registryIDType = new RegistryIDType(); - registryIDType.setOrganization("Mosip"); - registryIDType.setType("257"); - QualityType quality = new QualityType(); - quality.setAlgorithm(registryIDType); - quality.setScore(90l); - bdbInfoType1.setQuality(quality); - BiometricType singleType1 = BiometricType.FINGER; - List singleTypeList1 = new ArrayList<>(); - singleTypeList1.add(singleType1); - List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); - bdbInfoType1.setSubtype(subtype1); - bdbInfoType1.setType(singleTypeList1); - birType1.setBdbInfo(bdbInfoType1); - birTypeList.add(birType1); - - BiometricRecord biometricRecord = new BiometricRecord(); - biometricRecord.setSegments(birTypeList); - - when(packetManagerService.getBiometricsByMappingJsonKey(any(), - any(), any(),any())).thenReturn(biometricRecord); - AuthResponseDTO authResponseDTO = new AuthResponseDTO(); - ErrorDTO error=new ErrorDTO(); - error.setErrorCode("IDA-MLC-007"); - error.setErrorMessage("system error from ida"); - - List errors=new ArrayList(); - errors.add(error); - authResponseDTO.setErrors(errors); - when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); - when(regentity.getRegistrationType()).thenReturn("UPDATE"); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getInternalError()); - } - @Test - public void testAuthFailed() throws ApisResourceAccessException, IOException, InvalidKeySpecException, - NoSuchAlgorithmException, BioTypeException, CertificateException { - AuthResponseDTO authResponseDTO = new AuthResponseDTO(); - ErrorDTO error=new ErrorDTO(); - error.setErrorCode("IDA-MLC-008"); - error.setErrorMessage("biometric didnt match"); - - List errors=new ArrayList(); - errors.add(error); - authResponseDTO.setErrors(errors); - when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); - /*File idJson = new File(classLoader.getResource("ID2.json").getFile()); - InputStream ip = new FileInputStream(idJson); - *//*String idJsonString = IOUtils.toString(ip, "UTF-8"); - Mockito.when(utility.getDemographicIdentityJSONObject(Mockito.anyString(), Mockito.anyString())) - .thenReturn(JsonUtil.getJSONObject(JsonUtil.objectMapperReadValue(idJsonString, JSONObject.class), - MappingJsonConstants.IDENTITY));*/ - when(regentity.getRegistrationType()).thenReturn("UPDATE"); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertFalse(messageDto.getIsValid()); - } - - @Test - public void testJsonProcessingException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { - - when(utility.getApplicantAge(any(),anyString(), any())).thenThrow(new JsonProcessingException("IOException")); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getInternalError()); - } - - @Test - public void testPacketManagerException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { - - when(utility.getApplicantAge(any(),anyString(), any())).thenThrow(new PacketManagerException("errorcode","IOException")); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getInternalError()); - } -} +package io.mosip.registration.processor.biometric.authentication.stage; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.io.InputStream; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.spec.InvalidKeySpecException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import org.apache.commons.io.IOUtils; +import org.json.simple.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.core.env.Environment; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import io.mosip.kernel.biometrics.constant.BiometricType; +import io.mosip.kernel.biometrics.constant.QualityType; +import io.mosip.kernel.biometrics.entities.BDBInfo; +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.biometrics.entities.RegistryIDType; +import io.mosip.kernel.core.util.HMACUtils2; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.core.abstractverticle.EventDTO; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; +import io.mosip.registration.processor.core.auth.dto.ErrorDTO; +import io.mosip.registration.processor.core.auth.dto.ResponseDTO; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.constant.RegistrationType; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.BioTypeException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.packet.dto.FieldValue; +import io.mosip.registration.processor.core.packet.dto.Identity; +import io.mosip.registration.processor.core.packet.dto.masterdata.StatusResponseDto; +import io.mosip.registration.processor.core.spi.eventbus.EventHandler; +import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.util.IdentityIteratorUtil; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.utils.AuthUtil; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.rest.client.audit.dto.AuditResponseDto; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.dto.SyncRegistrationDto; +import io.mosip.registration.processor.status.dto.SyncResponseDto; +import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; +import io.mosip.registration.processor.status.repositary.RegistrationRepositary; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.status.service.SyncRegistrationService; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ IOUtils.class, HMACUtils2.class, Utilities.class }) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*","javax.management.*", "javax.net.ssl.*" }) +public class BiometricAuthenticationStageTest { + + /** The input stream. */ + @Mock + private InputStream inputStream; + + + + /** The registration status service. */ + @Mock + RegistrationStatusService registrationStatusService; + + /** The packet info manager. */ + @Mock + private PacketInfoManager packetInfoManager; + + @Mock + private AuthUtil authUtil; + + @Mock + InternalRegistrationStatusDto registrationStatusDto; + + @Mock + private RegistrationProcessorRestClientService restClientService; + + @Mock + private IdentityIteratorUtil identityIteratorUtil; + + /** The dto. */ + MessageDTO dto = new MessageDTO(); + + @Mock + private PriorityBasedPacketManagerService packetManagerService; + + @Mock + private SyncRegistrationService syncRegistrationservice; + + /** The BiometricAuthenticationStage stage. */ + @InjectMocks + private BiometricAuthenticationStage biometricAuthenticationStage = new BiometricAuthenticationStage() { + @Override + public MosipEventBus getEventBus(Object verticleName, String url, int instanceNumber) { + vertx = Vertx.vertx(); + + return new MosipEventBus() { + + @Override + public Vertx getEventbus() { + return vertx; + } + + @Override + public void consume(MessageBusAddress fromAddress, + EventHandler>> eventHandler) { + + } + + @Override + public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAddress, + EventHandler>> eventHandler) { + + } + + @Override + public void send(MessageBusAddress toAddress, MessageDTO message) { + + } + }; + } + + @Override + public void consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + MessageBusAddress toAddress, long messageExpiryTimeLimit) { + } + }; + + /** The audit log request builder. */ + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + private Environment env; + + + + + /** The dto. */ + InternalRegistrationStatusDto statusDto; + /** The list. */ + List list; + + /** The list appender. */ + private ListAppender listAppender; + + @Mock + private RegistrationProcessorRestClientService registrationProcessorRestService; + + @Mock + private Utilities utility; + + @Mock + ObjectMapper mapIdentityJsonStringToObject; + + @Mock + private RegistrationRepositary registrationRepositary; + + StatusResponseDto statusResponseDto; + + @Mock + LogDescription description; + + @Mock + RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + private SyncRegistrationEntity regentity = Mockito.mock(SyncRegistrationEntity.class); + + /** + * Sets the up. + * + * @throws Exception + * the exception + */ + @Before + public void setUp() throws Exception { + ReflectionTestUtils.setField(biometricAuthenticationStage, "workerPoolSize", 10); + ReflectionTestUtils.setField(biometricAuthenticationStage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(biometricAuthenticationStage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(biometricAuthenticationStage, "ageLimit", "5"); + + + when(utility.getGetRegProcessorDemographicIdentity()).thenReturn("identity"); + + + list = new ArrayList(); + + listAppender = new ListAppender<>(); + + dto.setRid("2018701130000410092018110735"); + dto.setReg_type(RegistrationType.valueOf("UPDATE")); + + MockitoAnnotations.initMocks(this); + + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder( + "test case description", EventId.RPR_405.toString(), EventName.UPDATE.toString(), + EventType.BUSINESS.toString(), "1234testcase", ApiName.AUDIT); + + + + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("2018701130000410092018110735"); + registrationStatusDto.setStatusCode(""); + registrationStatusDto.setRegistrationType("UPDATE"); + listAppender.start(); + list.add(registrationStatusDto); + when(registrationStatusService.getByStatus(anyString())).thenReturn(list); + when(registrationStatusService.getRegistrationStatus(anyString())).thenReturn(registrationStatusDto); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); + + when(identityIteratorUtil.getFieldValue(any(), any())).thenReturn("UPDATE"); + + + Mockito.doNothing().when(description).setMessage(any()); + when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn(""); + + + statusResponseDto = new StatusResponseDto(); + statusResponseDto.setStatus("VALID"); + when(registrationProcessorRestService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(statusResponseDto); + + JSONObject jsonObject = Mockito.mock(JSONObject.class); + when(utility.getUIn(anyString(), anyString(), any())).thenReturn("12345678"); + when(utility.retrieveIdrepoJson(any())).thenReturn(jsonObject); + FieldValue fieldValue = new FieldValue(); + FieldValue fieldValue1 = new FieldValue(); + fieldValue1.setLabel("authenticationBiometricFileName"); + fieldValue1.setValue("biometricTestFileName"); + fieldValue.setLabel("registrationType"); + fieldValue.setValue("update"); + List metadata = new ArrayList<>(); + metadata.add(fieldValue); + metadata.add(fieldValue1); + + + when(utility.getDefaultSource(any(), any())).thenReturn("reg-client"); + when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(21); + + regentity.setRegistrationType("update"); + when(syncRegistrationservice.findByRegistrationId(any())).thenReturn(regentity); + + AuthResponseDTO authResponseDTO = new AuthResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setAuthStatus(true); + authResponseDTO.setResponse(responseDTO); + when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); + + List birTypeList = new ArrayList<>(); + BIR birType1 = new BIR.BIRBuilder().build(); + BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); + RegistryIDType registryIDType = new RegistryIDType(); + registryIDType.setOrganization("Mosip"); + registryIDType.setType("257"); + QualityType quality = new QualityType(); + quality.setAlgorithm(registryIDType); + quality.setScore(90l); + bdbInfoType1.setQuality(quality); + BiometricType singleType1 = BiometricType.FINGER; + List singleTypeList1 = new ArrayList<>(); + singleTypeList1.add(singleType1); + List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); + bdbInfoType1.setSubtype(subtype1); + bdbInfoType1.setType(singleTypeList1); + birType1.setBdbInfo(bdbInfoType1); + birTypeList.add(birType1); + + BiometricRecord biometricRecord = new BiometricRecord(); + biometricRecord.setSegments(birTypeList); + + when(packetManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())).thenReturn(biometricRecord); + + + } + + @Test + public void biometricAuthenticationSuccessTest() throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { + when(regentity.getRegistrationType()).thenReturn("UPDATE"); + List birTypeList = new ArrayList<>(); + BIR birType1 = new BIR.BIRBuilder().build(); + BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); + RegistryIDType registryIDType = new RegistryIDType(); + registryIDType.setOrganization("Mosip"); + registryIDType.setType("257"); + QualityType quality = new QualityType(); + quality.setAlgorithm(registryIDType); + quality.setScore(90l); + bdbInfoType1.setQuality(quality); + BiometricType singleType1 = BiometricType.FINGER; + List singleTypeList1 = new ArrayList<>(); + singleTypeList1.add(singleType1); + List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); + bdbInfoType1.setSubtype(subtype1); + bdbInfoType1.setType(singleTypeList1); + birType1.setBdbInfo(bdbInfoType1); + birTypeList.add(birType1); + + BiometricRecord biometricRecord = new BiometricRecord(); + biometricRecord.setSegments(birTypeList); + + when(packetManagerService.getBiometricsByMappingJsonKey(any(), + any(), any(),any())).thenReturn(biometricRecord); + + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getIsValid()); + } + + + @Test + public void IDAuthFailureTest() throws IOException, ApisResourceAccessException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, CertificateException { + AuthResponseDTO authResponseDTO = new AuthResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setAuthStatus(false); + authResponseDTO.setResponse(responseDTO); + when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); + + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertFalse(messageDto.getIsValid()); + } + + @Test + public void childPacketTest() throws ApisResourceAccessException, JsonProcessingException, io.mosip.kernel.core.exception.IOException, PacketManagerException, IOException { + when(regentity.getRegistrationType()).thenReturn("UPDATE"); + when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(2); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getIsValid()); + } + + @Test + public void inputStreamNullIndividualAuthTest() throws ApisResourceAccessException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, IOException { + + HashMap hashMap = new HashMap(); + hashMap.put("value", "testFile"); + + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + + assertFalse(messageDto.getIsValid()); + } + + @Test + public void testIOException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { + + when(utility.getApplicantAge(any(),anyString(), any())).thenThrow(new IOException("IOException")); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getInternalError()); + } + + @Test + public void testApisResourceAccessException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { + + when(utility.getApplicantAge(anyString(),anyString(), any())) + .thenThrow(new ApisResourceAccessException("ApisResourceAccessException")); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getInternalError()); + } + + @Test + public void testException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { + + when(utility.getApplicantAge(anyString(),anyString(), any())) + .thenThrow( + new ApisResourceAccessException( + "test message")); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getInternalError()); + } + + @Test + public void resupdatePacketTest() throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { + when(regentity.getRegistrationType()).thenReturn("res_update"); + List birTypeList = new ArrayList<>(); + BIR birType1 = new BIR.BIRBuilder().build(); + BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); + RegistryIDType registryIDType = new RegistryIDType(); + registryIDType.setOrganization("Mosip"); + registryIDType.setType("257"); + QualityType quality = new QualityType(); + quality.setAlgorithm(registryIDType); + quality.setScore(90l); + bdbInfoType1.setQuality(quality); + BiometricType singleType1 = BiometricType.FINGER; + List singleTypeList1 = new ArrayList<>(); + singleTypeList1.add(singleType1); + List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); + bdbInfoType1.setSubtype(subtype1); + bdbInfoType1.setType(singleTypeList1); + birType1.setBdbInfo(bdbInfoType1); + birTypeList.add(birType1); + + BiometricRecord biometricRecord = new BiometricRecord(); + biometricRecord.setSegments(birTypeList); + when(packetManagerService.getBiometricsByMappingJsonKey(any(), any(), any(),any())).thenReturn(biometricRecord); + + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + + assertTrue(messageDto.getIsValid()); + } + + @Test + public void testNewPacket() throws IOException, + ApisResourceAccessException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, CertificateException { + + AuthResponseDTO authResponseDTO = new AuthResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setAuthStatus(false); + authResponseDTO.setResponse(responseDTO); + when(regentity.getRegistrationType()).thenReturn("new"); + when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + + assertTrue(messageDto.getIsValid()); + } + + @Test + public void deployVerticle() { + + biometricAuthenticationStage.deployVerticle(); + } + @Test + public void testAuthSystemException() throws ApisResourceAccessException, IOException, InvalidKeySpecException, + NoSuchAlgorithmException, BioTypeException, JsonProcessingException, PacketManagerException, CertificateException { + List birTypeList = new ArrayList<>(); + BIR birType1 = new BIR.BIRBuilder().build(); + BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); + RegistryIDType registryIDType = new RegistryIDType(); + registryIDType.setOrganization("Mosip"); + registryIDType.setType("257"); + QualityType quality = new QualityType(); + quality.setAlgorithm(registryIDType); + quality.setScore(90l); + bdbInfoType1.setQuality(quality); + BiometricType singleType1 = BiometricType.FINGER; + List singleTypeList1 = new ArrayList<>(); + singleTypeList1.add(singleType1); + List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); + bdbInfoType1.setSubtype(subtype1); + bdbInfoType1.setType(singleTypeList1); + birType1.setBdbInfo(bdbInfoType1); + birTypeList.add(birType1); + + BiometricRecord biometricRecord = new BiometricRecord(); + biometricRecord.setSegments(birTypeList); + + when(packetManagerService.getBiometricsByMappingJsonKey(any(), + any(), any(),any())).thenReturn(biometricRecord); + AuthResponseDTO authResponseDTO = new AuthResponseDTO(); + ErrorDTO error=new ErrorDTO(); + error.setErrorCode("IDA-MLC-007"); + error.setErrorMessage("system error from ida"); + + List errors=new ArrayList(); + errors.add(error); + authResponseDTO.setErrors(errors); + when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); + when(regentity.getRegistrationType()).thenReturn("UPDATE"); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getInternalError()); + } + @Test + public void testAuthFailed() throws ApisResourceAccessException, IOException, InvalidKeySpecException, + NoSuchAlgorithmException, BioTypeException, CertificateException { + AuthResponseDTO authResponseDTO = new AuthResponseDTO(); + ErrorDTO error=new ErrorDTO(); + error.setErrorCode("IDA-MLC-008"); + error.setErrorMessage("biometric didnt match"); + + List errors=new ArrayList(); + errors.add(error); + authResponseDTO.setErrors(errors); + when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); + /*File idJson = new File(classLoader.getResource("ID2.json").getFile()); + InputStream ip = new FileInputStream(idJson); + *//*String idJsonString = IOUtils.toString(ip, "UTF-8"); + Mockito.when(utility.getDemographicIdentityJSONObject(Mockito.anyString(), Mockito.anyString())) + .thenReturn(JsonUtil.getJSONObject(JsonUtil.objectMapperReadValue(idJsonString, JSONObject.class), + MappingJsonConstants.IDENTITY));*/ + when(regentity.getRegistrationType()).thenReturn("UPDATE"); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertFalse(messageDto.getIsValid()); + } + + @Test + public void testJsonProcessingException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { + + when(utility.getApplicantAge(any(),anyString(), any())).thenThrow(new JsonProcessingException("IOException")); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getInternalError()); + } + + @Test + public void testPacketManagerException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { + + when(utility.getApplicantAge(any(),anyString(), any())).thenThrow(new PacketManagerException("errorcode","IOException")); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getInternalError()); + } + + @Test + public void testChildPacketWithLessThanOneYear() throws ApisResourceAccessException, JsonProcessingException, io.mosip.kernel.core.exception.IOException, PacketManagerException, IOException { + when(regentity.getRegistrationType()).thenReturn("UPDATE"); + when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(0); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getIsValid()); + } +}