Skip to content

Commit

Permalink
MOSIP-30687 On demand template extraction changes
Browse files Browse the repository at this point in the history
Signed-off-by: Neha Farheen <[email protected]>
  • Loading branch information
Neha Farheen committed Jan 29, 2024
1 parent a72edfd commit 0f29cec
Show file tree
Hide file tree
Showing 8 changed files with 221 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,14 @@ public Tuple3<String, String, String> encryptData(byte[] data, String partnerCer
return Tuples.of(CryptoUtil.encodeBase64Url(encryptedData.getT1()), CryptoUtil.encodeBase64Url(encryptedData.getT2()), digestAsPlainText(certificateThumbprint));
}

public byte[] encryptIdData(byte[] dataToEncrypt, String partnerCertificate)
throws IdAuthenticationBusinessException {
X509Certificate x509Certificate = getX509Certificate(partnerCertificate);
PublicKey publicKey = x509Certificate.getPublicKey();
byte[] encryptedData = cryptoCore.asymmetricEncrypt(publicKey, dataToEncrypt);
return encryptedData;
}

/**
* Encrypt.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
package io.mosip.authentication.common.service.websub.impl;

import static io.mosip.authentication.core.constant.IdAuthConfigKeyConstants.ON_DEMAND_TEMPLATE_EXTRACTION_TOPIC;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import io.mosip.authentication.common.service.helper.WebSubHelper;
import io.mosip.authentication.common.service.transaction.manager.IdAuthSecurityManager;
import io.mosip.authentication.core.constant.IdAuthCommonConstants;
import io.mosip.authentication.core.exception.IdAuthenticationBusinessException;
import io.mosip.authentication.core.indauth.dto.BaseRequestDTO;
import io.mosip.authentication.core.logger.IdaLogger;
import io.mosip.authentication.core.partner.dto.PartnerDTO;
import io.mosip.idrepository.core.security.IdRepoSecurityManager;
import io.mosip.kernel.core.logger.spi.Logger;
import io.mosip.kernel.core.util.DateUtils;
import io.mosip.kernel.core.websub.model.Event;
import io.mosip.kernel.core.websub.model.EventModel;

/**
* The Class OnDemandTemplateEventPublisher.
*
* @author Neha
*/
@Component
public class OndemandTemplateEventPublisher extends BaseWebSubEventsInitializer {

private static final String REQUEST_SIGNATURE = "requestSignature";

private static final String ENTITY_NAME = "entityName";

private static final String INDIVIDUAL_ID_TYPE = "individualIdType";

private static final String AUTH_PARTNER_ID = "authPartnerId";

private static final String INDIVIDUAL_ID = "individualId";

private static final String REQUESTDATETIME = "requestdatetime";

private static final String ERROR_MESSAGE = "error_message";

private static final String ERROR_CODE = "error_Code";

/** The Constant PUBLISHER_IDA. */
private static final String PUBLISHER_IDA = "IDA";

/** The Constant logger. */
private static final Logger logger = IdaLogger.getLogger(CredentialStoreStatusEventPublisher.class);

/** The on demand template extraction topic. */
@Value("${" + ON_DEMAND_TEMPLATE_EXTRACTION_TOPIC + "}")
private String onDemadTemplateExtractionTopic;

/** The web sub event publish helper. */
@Autowired
private WebSubHelper webSubHelper;

@Autowired
private IdAuthSecurityManager securityManager;

/**
* Do subscribe.
*/
@Override
protected void doSubscribe() {
// Nothing to do here since we are just publishing event for this topic
}

/**
* Try register topic partner service events.
*/
private void tryRegisterTopicOnDemandEvent() {
try {
logger.debug(IdAuthCommonConstants.SESSION_ID, "tryRegisterOnDemandEvent", "",
"Trying to register topic: " + onDemadTemplateExtractionTopic);
webSubHelper.registerTopic(onDemadTemplateExtractionTopic);
logger.info(IdAuthCommonConstants.SESSION_ID, "tryRegisterOnDemandEvent", "",
"Registered topic: " + onDemadTemplateExtractionTopic);
} catch (Exception e) {
logger.info(IdAuthCommonConstants.SESSION_ID, "tryRegisterOnDemandEvent", e.getClass().toString(),
"Error registering topic: " + onDemadTemplateExtractionTopic + "\n" + e.getMessage());
}
}

@Override
protected void doRegister() {
logger.info(IdAuthCommonConstants.SESSION_ID, "doRegister", this.getClass().getSimpleName(),
"On demand template event topic..");
tryRegisterTopicOnDemandEvent();
}

public void publishEvent(EventModel eventModel) {
webSubHelper.publishEvent(onDemadTemplateExtractionTopic, eventModel);
}

public void notify(Object authrequestdto, String headerSignature, Optional<PartnerDTO> partner,
IdAuthenticationBusinessException e, Map<String, Object> metadata) {
try {
sendEvents(authrequestdto, headerSignature, partner, e, metadata);
} catch (Exception exception) {
logger.error(IdRepoSecurityManager.getUser(), "On demand template extraction", "notify",
exception.getMessage());
}
}

private void sendEvents(Object authrequestdto, String headerSignature, Optional<PartnerDTO> partner,
IdAuthenticationBusinessException e, Map<String, Object> metadata) {
logger.info("Inside sendEvents ondemand extraction");
Map<String, Object> eventData = new HashMap<>();
eventData.put(ERROR_CODE, e.getErrorCode());
eventData.put(ERROR_MESSAGE, e.getErrorText());
eventData.put(REQUESTDATETIME, DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime()));
eventData.put(INDIVIDUAL_ID, encryptIndividualId(((BaseRequestDTO) authrequestdto).getIndividualId(),
metadata.get(IdAuthCommonConstants.PARTNER_CERTIFICATE).toString()));
eventData.put(AUTH_PARTNER_ID, partner.get().getPartnerId());
eventData.put(INDIVIDUAL_ID_TYPE, ((BaseRequestDTO) authrequestdto).getIndividualIdType());
eventData.put(ENTITY_NAME, partner.get().getPartnerName());
eventData.put(REQUEST_SIGNATURE, headerSignature);
EventModel eventModel = createEventModel(onDemadTemplateExtractionTopic, eventData);
publishEvent(eventModel);
}

private EventModel createEventModel(String topic, Map<String, Object> eventData) {
EventModel model = new EventModel();
model.setPublisher(PUBLISHER_IDA);
String dateTime = DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime());
model.setPublishedOn(dateTime);
Event event = new Event();
event.setTimestamp(dateTime);
String eventId = UUID.randomUUID().toString();
event.setId(eventId);
event.setData(eventData);
model.setEvent(event);
model.setTopic(topic);
return model;
}

private byte[] encryptIndividualId(String id, String partnerCertificate) {
try {
return securityManager.encryptIdData(id.getBytes(), partnerCertificate);
} catch (IdAuthenticationBusinessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ private IdAuthConfigKeyConstants() {
public static final String AUTH_TRANSACTION_STATUS_TOPIC = "ida-topic-auth-transaction-status";
public static final String AUTH_ANONYMOUS_PROFILE_TOPIC = "ida-topic-auth-anonymous-profile";
public static final String AUTH_FRAUD_ANALYSIS_TOPIC = "ida-topic-fraud-analysis";
public static final String ON_DEMAND_TEMPLATE_EXTRACTION_TOPIC = "ida-topic-on-demand-template-extraction";


public static final String IDA_MAX_CREDENTIAL_PULL_WINDOW_DAYS = "ida-max-credential-pull-window-days";
public static final String IDA_MAX_WEBSUB_MSG_PULL_WINDOW_DAYS = "ida-max-websub-messages-pull-window-days";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ public enum IdAuthenticationErrorConstants {
"Please capture biometrics within %s seconds of previous biometric capture"),
INVALID_BIO_DIGITALID_TIMESTAMP("IDA-MLC-031", "DigitalId of Biometrics not captured within %s seconds of previous biometrics",
"Please capture DigitalId of biometrics within %s seconds of previous biometric capture"),

UNABLE_TO_IDENTIFY_ID("IDA-MLC-032", "Unable to identify the entered %s. Please try after few minutes"),

DEMOGRAPHIC_DATA_MISMATCH_LANG("IDA-DEA-001", "Demographic data %s in %s did not match",
"Please re-enter your %s in %s"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import io.mosip.authentication.common.service.transaction.manager.IdAuthSecurityManager;
import io.mosip.authentication.common.service.util.IdaRequestResponsConsumerUtil;
import io.mosip.authentication.common.service.validator.OTPRequestValidator;
import io.mosip.authentication.common.service.websub.impl.OndemandTemplateEventPublisher;
import io.mosip.authentication.core.constant.AuditEvents;
import io.mosip.authentication.core.constant.AuditModules;
import io.mosip.authentication.core.constant.IdAuthCommonConstants;
Expand Down Expand Up @@ -90,6 +91,9 @@ public class OTPController {

@Autowired
private IdAuthSecurityManager securityManager;

@Autowired
private OndemandTemplateEventPublisher ondemandTemplateEventPublisher;

@InitBinder
private void initBinder(WebDataBinder binder) {
Expand Down Expand Up @@ -155,6 +159,15 @@ public OtpResponseDTO generateOTP(@Valid @RequestBody OtpRequestDTO otpRequestDt
throw authTransactionHelper.createDataValidationException(authTxnBuilder, e, requestWithMetadata);
} catch (IdAuthenticationBusinessException e) {
logger.error(IdAuthCommonConstants.SESSION_ID, e.getClass().toString(), e.getErrorCode(), e.getErrorText());
if (IdAuthenticationErrorConstants.ID_NOT_AVAILABLE.getErrorCode().equals(e.getErrorCode())) {
ondemandTemplateEventPublisher.notify(otpRequestDto, request.getHeader("signature"), partner, e,
otpRequestDto.getMetadata());
throw new IdAuthenticationBusinessException(
IdAuthenticationErrorConstants.UNABLE_TO_IDENTIFY_ID.getErrorCode(),
String.format(IdAuthenticationErrorConstants.UNABLE_TO_IDENTIFY_ID.getErrorMessage(),
otpRequestDto.getIndividualIdType()),
e);
}
auditHelper.audit(AuditModules.OTP_REQUEST, AuditEvents.OTP_TRIGGER_REQUEST_RESPONSE , otpRequestDto.getTransactionID(),
IdType.getIDTypeOrDefault(otpRequestDto.getIndividualIdType()), e);
authTransactionHelper.setAuthTransactionEntityMetadata(requestWithMetadata, authTxnBuilder);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import io.mosip.authentication.common.service.util.AuthTypeUtil;
import io.mosip.authentication.common.service.util.IdaRequestResponsConsumerUtil;
import io.mosip.authentication.common.service.validator.AuthRequestValidator;
import io.mosip.authentication.common.service.websub.impl.OndemandTemplateEventPublisher;
import io.mosip.authentication.core.constant.AuditEvents;
import io.mosip.authentication.core.constant.IdAuthCommonConstants;
import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants;
Expand Down Expand Up @@ -88,6 +89,9 @@ public class AuthController {

@Autowired
private PartnerService partnerService;

@Autowired
private OndemandTemplateEventPublisher ondemandTemplateEventPublisher;


/**
Expand Down Expand Up @@ -157,7 +161,18 @@ public AuthResponseDTO authenticateIndividual(@Validated @RequestBody AuthReques
throw authTransactionHelper.createDataValidationException(authTxnBuilder, e, requestWithMetadata);
} catch (IdAuthenticationBusinessException e) {
mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(),
"authenticateApplication", e.getErrorCode() + " : " + e.getErrorText());
"authenticateApplication", e.getErrorCode() + " : " + e.getErrorText());
if (IdAuthenticationErrorConstants.ID_NOT_AVAILABLE.getErrorCode().equals(e.getErrorCode())) {
ondemandTemplateEventPublisher.notify(authrequestdto, request.getHeader("signature"), partner, e,
authrequestdto.getMetadata());
throw new IdAuthenticationBusinessException(
IdAuthenticationErrorConstants.UNABLE_TO_IDENTIFY_ID.getErrorCode(),
String.format(
IdAuthenticationErrorConstants.UNABLE_TO_IDENTIFY_ID.getErrorMessage(),
authrequestdto.getIndividualIdType()),
e);

}

auditHelper.auditExceptionForAuthRequestedModules(AuditEvents.AUTH_REQUEST_RESPONSE, authrequestdto, e);
IdaRequestResponsConsumerUtil.setIdVersionToObjectWithMetadata(requestWithMetadata, e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import io.mosip.authentication.common.service.util.AuthTypeUtil;
import io.mosip.authentication.common.service.util.IdaRequestResponsConsumerUtil;
import io.mosip.authentication.common.service.validator.AuthRequestValidator;
import io.mosip.authentication.common.service.websub.impl.OndemandTemplateEventPublisher;
import io.mosip.authentication.core.constant.AuditEvents;
import io.mosip.authentication.core.constant.IdAuthCommonConstants;
import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants;
Expand Down Expand Up @@ -98,6 +99,9 @@ public class KycAuthController {
/** The KycExchangeRequestValidator */
@Autowired
private KycExchangeRequestValidator kycExchangeValidator;

@Autowired
private OndemandTemplateEventPublisher ondemandTemplateEventPublisher;

/**
*
Expand Down Expand Up @@ -194,6 +198,15 @@ public EKycAuthResponseDTO processKyc(@Validated @RequestBody EkycAuthRequestDTO
mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "processEKyc",
e.getErrorTexts().isEmpty() ? "" : e.getErrorText());

if (IdAuthenticationErrorConstants.ID_NOT_AVAILABLE.getErrorCode().equals(e.getErrorCode())) {
ondemandTemplateEventPublisher.notify(ekycAuthRequestDTO, request.getHeader("signature"), partner,
e, ekycAuthRequestDTO.getMetadata());
throw new IdAuthenticationBusinessException(
IdAuthenticationErrorConstants.UNABLE_TO_IDENTIFY_ID.getErrorCode(),
String.format(IdAuthenticationErrorConstants.UNABLE_TO_IDENTIFY_ID.getErrorMessage(),
ekycAuthRequestDTO.getIndividualIdType()),
e);
}
auditHelper.auditExceptionForAuthRequestedModules(AuditEvents.EKYC_REQUEST_RESPONSE, ekycAuthRequestDTO, e);
IdaRequestResponsConsumerUtil.setIdVersionToObjectWithMetadata(requestWrapperWithMetadata, e);
e.putMetadata(IdAuthCommonConstants.TRANSACTION_ID, ekycAuthRequestDTO.getTransactionID());
Expand Down Expand Up @@ -272,6 +285,15 @@ public KycAuthResponseDTO processKycAuth(@Validated @RequestBody KycAuthRequestD
mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "processKycAuth",
e.getErrorTexts().isEmpty() ? "" : e.getErrorText());

if (IdAuthenticationErrorConstants.ID_NOT_AVAILABLE.getErrorCode().equals(e.getErrorCode())) {
ondemandTemplateEventPublisher.notify(authRequestDTO, request.getHeader("signature"), partner, e,
authRequestDTO.getMetadata());
throw new IdAuthenticationBusinessException(
IdAuthenticationErrorConstants.UNABLE_TO_IDENTIFY_ID.getErrorCode(),
String.format(IdAuthenticationErrorConstants.UNABLE_TO_IDENTIFY_ID.getErrorMessage(),
authRequestDTO.getIndividualIdType()),
e);
}
auditHelper.auditExceptionForAuthRequestedModules(AuditEvents.KYC_REQUEST_RESPONSE, authRequestDTO, e);
IdaRequestResponsConsumerUtil.setIdVersionToObjectWithMetadata(requestWrapperWithMetadata, e);
e.putMetadata(IdAuthCommonConstants.TRANSACTION_ID, authRequestDTO.getTransactionID());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ public void processKycFailure1() throws IdAuthenticationBusinessException, IdAut
kycAuthController.processKyc(kycAuthReqDTO, errors, "1635497344579", "1635497344579", "1635497344579", new TestHttpServletRequest());
}

@Test(expected = IdAuthenticationAppException.class)
@Test
public void processKycFailure2() throws IdAuthenticationBusinessException, IdAuthenticationAppException,
IdAuthenticationDaoException, Exception {

Expand All @@ -293,6 +293,6 @@ public void processKycFailure2() throws IdAuthenticationBusinessException, IdAut
requestWithMetadata.setMetadata(new HashMap<>());
Mockito.when(kycFacade.authenticateIndividual(kycAuthReqDTO, true, "1635497344579", "1635497344579", requestWithMetadata)).thenThrow(new IdAuthenticationBusinessException());
Mockito.when(kycFacade.processEKycAuth(kycAuthReqDTO, authResponseDTO, "1635497344579", requestWithMetadata.getMetadata())).thenReturn(kycAuthResponseDTO);
kycAuthController.processKyc(kycAuthReqDTO, errors, "1635497344579", "1635497344579", "1635497344579", requestWithMetadata);
kycAuthController.processKyc(kycAuthReqDTO, errors, "1635497344579", "1635497344579", "1635497344579", new TestHttpServletRequest());
}
}

0 comments on commit 0f29cec

Please sign in to comment.