From cab839edb3b42a47a8e01d0868c215a3eef2ebdd Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Fri, 6 Oct 2023 15:12:26 +0530 Subject: [PATCH 01/59] feat : added new provider roles --- .../apigateway/filters/AuditValidationFilter.java | 6 +++++- .../java/org/swasth/apigateway/models/BaseRequest.java | 10 +++++++--- api-gateway/src/main/resources/application.yaml | 2 ++ api-gateway/src/main/resources/rbac.yaml | 10 ++++++++-- .../main/java/org/swasth/hcx/models/Participant.java | 10 +++++++--- hcx-apis/src/main/resources/application.yml | 2 ++ .../main/java/org/swasth/common/utils/Constants.java | 2 +- .../java/org/swasth/hcx/services/OnboardService.java | 5 ++++- hcx-onboard/src/main/resources/application.yml | 4 +++- 9 files changed, 39 insertions(+), 12 deletions(-) diff --git a/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java b/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java index 8d027cd3f..f449ee3a7 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java @@ -3,6 +3,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; import org.springframework.core.io.buffer.DataBuffer; @@ -40,6 +41,9 @@ public class AuditValidationFilter extends AbstractGatewayFilterFactory providerSpecificRoles; + public AuditValidationFilter() { super(Config.class); } @@ -60,7 +64,7 @@ public GatewayFilter apply(Config config) { ArrayList roles = (ArrayList) participant.get("roles"); String code = (String) participant.get(Constants.PARTICIPANT_CODE); Map filters = (Map) filterMap.get("filters"); - if (roles.contains("payor") || roles.contains("provider")) { + if (roles.contains("payor") || roles.contains("provider") || roles.stream().anyMatch(providerSpecificRoles::contains)) { filters.put("x-hcx-sender_code", code); filterMap.put("filters", filters); logger.debug("updated filters: {}", filterMap); diff --git a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java index e6ce365e6..9250171ba 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java @@ -4,6 +4,7 @@ import lombok.Data; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; import org.swasth.apigateway.exception.ClientException; import org.swasth.apigateway.exception.ErrorCodes; import org.swasth.apigateway.utils.DateTimeUtils; @@ -34,6 +35,9 @@ public class BaseRequest { private String hcxRoles; private String hcxCode; + @Value("${provider-specific-roles}") + private List providerSpecificRoles; + public BaseRequest() { } @@ -185,7 +189,7 @@ public void validateUsingAuditData(List allowedEntitiesForForward, List< for (Map audit : correlationAuditData) { String action = (String) audit.get(ACTION); String entity = getEntity(action); - validateCondition(!OPERATIONAL_ENTITIES.contains(entity) && action.contains("on_") && ((List) audit.get(RECIPIENT_ROLE)).contains(PROVIDER) && audit.get(STATUS).equals(COMPLETE_STATUS), ErrorCodes.ERR_INVALID_CORRELATION_ID, CLOSED_CYCLE_MSG); + validateCondition(!OPERATIONAL_ENTITIES.contains(entity) && action.contains("on_") && ((List) audit.get(RECIPIENT_ROLE)).contains(PROVIDER) && ((List) audit.get(RECIPIENT_ROLE)).stream().anyMatch(providerSpecificRoles::contains) && audit.get(STATUS).equals(COMPLETE_STATUS), ErrorCodes.ERR_INVALID_CORRELATION_ID, CLOSED_CYCLE_MSG); } String actionEntity = getEntity(jweRequest.getApiAction()); if (!OPERATIONAL_ENTITIES.contains(actionEntity)) { @@ -213,11 +217,11 @@ public void validateUsingAuditData(List allowedEntitiesForForward, List< validateCondition(getHcxRecipientCode().equals(audit.get(HCX_SENDER_CODE)), ErrorCodes.ERR_INVALID_FORWARD_REQ, FORWARD_REQ_ERR_MSG); } } - } else if (!EXCLUDE_ENTITIES.contains(getEntity(path)) && !apiAction.contains("on_") && checkParticipantRole(allowedRolesForForward, senderRoles) && recipientRoles.contains(PROVIDER)) { + } else if (!EXCLUDE_ENTITIES.contains(getEntity(path)) && !apiAction.contains("on_") && checkParticipantRole(allowedRolesForForward, senderRoles) && recipientRoles.contains(PROVIDER) && recipientRoles.stream().anyMatch(providerSpecificRoles::contains)) { throw new ClientException(ErrorCodes.ERR_ACCESS_DENIED, INVALID_API_CALL); } // validation to check if participant is forwarding the request to provider - if (isForwardReq && !apiAction.contains("on_") && recipientRoles.contains(PROVIDER)) { + if (isForwardReq && !apiAction.contains("on_") && recipientRoles.contains(PROVIDER) && recipientRoles.stream().anyMatch(providerSpecificRoles::contains)) { throw new ClientException(ErrorCodes.ERR_INVALID_FORWARD_REQ, INVALID_FORWARD_TO_PROVIDER); } } diff --git a/api-gateway/src/main/resources/application.yaml b/api-gateway/src/main/resources/application.yaml index 3c994f7ee..626a47a3b 100644 --- a/api-gateway/src/main/resources/application.yaml +++ b/api-gateway/src/main/resources/application.yaml @@ -109,6 +109,8 @@ audit: index: ${audit_index:hcx_audit} alias: ${audit_alias:hcx_audit} +provider-specific-roles: ${provider_specific_roles:provider.hospital,provider.clinic,provider.practitioner,provider.diagnostics,provider.pharmacy} + spring: main: web-application-type: reactive diff --git a/api-gateway/src/main/resources/rbac.yaml b/api-gateway/src/main/resources/rbac.yaml index c88971794..e6e27eeff 100644 --- a/api-gateway/src/main/resources/rbac.yaml +++ b/api-gateway/src/main/resources/rbac.yaml @@ -9,8 +9,14 @@ rbac: regexPaths: - /url/** - /auth/** - - role: AUTHENTICATED - - role: provider + - roles: + - AUTHENTICATED + - provider + - provider.hospital + - provider.clinic + - provider.practitioner + - provider.diagnostics + - provider.pharmacy paths: - /v0.7/coverageeligibility/check - /v0.7/predetermination/submit diff --git a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java index db7c84fbc..e4d935ff6 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java @@ -1,6 +1,7 @@ package org.swasth.hcx.models; import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; import org.swasth.common.utils.SlugUtils; import java.security.SecureRandom; @@ -13,6 +14,9 @@ public class Participant { private final Map requestBody; + @Value("${provider-specific-roles}") + private List specificProviderRoles; + public Participant(Map requestbody) { this.requestBody = requestbody; } @@ -40,10 +44,10 @@ public String generateCode(String fieldSeparator, String hcxInstanceName) { return code; } - private String getRoleAppender(){ - if (getRoles().contains(PROVIDER)){ + private String getRoleAppender() { + if (getRoles().contains(PROVIDER) || getRoles().stream().anyMatch(specificProviderRoles::contains)) { return "hosp"; - } else if (getRoles().contains(PAYOR)){ + } else if (getRoles().contains(PAYOR)) { return "payr"; } else { return getRoles().get(0); diff --git a/hcx-apis/src/main/resources/application.yml b/hcx-apis/src/main/resources/application.yml index d97196db8..3fda58212 100644 --- a/hcx-apis/src/main/resources/application.yml +++ b/hcx-apis/src/main/resources/application.yml @@ -152,3 +152,5 @@ email: pwd: ${email_pwd:} user-token-subject: ${token_generate_subject:HCX - Protocol APIs Access Token Generation credentials} user-token-message: ${user_token_message:Hi NAME,

Along with participant username and password, api access token can be generated using the following credentials.
  • user_name - USER_ID
  • secret - PASSWORD
  • participant_code - PARTICIPANT_CODE
This API Access token can be used to make protocol API requests. Please refer to the instructions provided in the link to generate access token.

If you have any queries, Please reach out HCX team.

Thanks and Regards
HCX Team.} + +provider-specific-roles: ${provider_specific_roles:provider.hospital,provider.clinic,provider.practitioner,provider.diagnostics,provider.pharmacy} \ No newline at end of file diff --git a/hcx-core/hcx-common/src/main/java/org/swasth/common/utils/Constants.java b/hcx-core/hcx-common/src/main/java/org/swasth/common/utils/Constants.java index ebc7c3e87..0177a3dca 100644 --- a/hcx-core/hcx-common/src/main/java/org/swasth/common/utils/Constants.java +++ b/hcx-core/hcx-common/src/main/java/org/swasth/common/utils/Constants.java @@ -371,7 +371,7 @@ public class Constants { public static final String OTP_REGENERATE_COUNT = "otp_regenerate_count"; public static final String LAST_REGENERATE_DATE = "last_regenerate_date"; public static final String RESPONSE_OBJ = "response_obj"; - public static final List PARTICIPANT_ROLES = Arrays.asList(PROVIDER,PAYOR,AGENCY_TPA,"agency.regulator", "research",MEMBER_ISNP, "agency.sponsor",ADMIN_ROLE); + public static final List PARTICIPANT_ROLES = Arrays.asList(PROVIDER, PAYOR, AGENCY_TPA, "agency.regulator", "research", MEMBER_ISNP, "agency.sponsor", ADMIN_ROLE, "provider.hospital", "provider.clinic", "provider.practitioner", "provider.diagnostics", "provider.pharmacy"); public static final String USER_NAME = "user_name"; public static final String CREATED_BY = "created_by"; public static final List ALLOWED_DELEGATED_TOPICS = Arrays.asList("notif-workflow-update"); diff --git a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java index d792d66b9..52daa8130 100644 --- a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java +++ b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java @@ -174,6 +174,9 @@ public class OnboardService extends BaseController { @Value("${email.failed-identity-sub}") private String failedIdentitySub; + @Value("${provider-specific-roles}") + private List specificProviderRoles; + @PostConstruct() public void init(){ keycloak = Keycloak.getInstance(keycloakURL, keycloakMasterRealm, keycloakAdminUserName, keycloakAdminPassword, keycloackClientId); @@ -245,7 +248,7 @@ private void addParticipantDetails(Map participant, OnboardReques participant.put(REGISTRY_STATUS, CREATED); if (((ArrayList) participant.get(ROLES)).contains(PAYOR)) participant.put(SCHEME_CODE, "default"); - if (((ArrayList) participant.get(ROLES)).contains(PROVIDER)) + if (((ArrayList) participant.get(ROLES)).contains(PROVIDER) || ((ArrayList) participant.get(ROLES)).stream().anyMatch(specificProviderRoles::contains)) participant.put(APPLICANT_CODE, request.getApplicantCode()); } diff --git a/hcx-onboard/src/main/resources/application.yml b/hcx-onboard/src/main/resources/application.yml index 7cc3b7ac5..f0cf66ff8 100644 --- a/hcx-onboard/src/main/resources/application.yml +++ b/hcx-onboard/src/main/resources/application.yml @@ -101,4 +101,6 @@ keycloak: participant-realm: ${keycloack_users_realm:swasth-hcx-participants} endpoint: - user-invite: ${user_invite_endpoint:/onboarding/user/invite} \ No newline at end of file + user-invite: ${user_invite_endpoint:/onboarding/user/invite} + +provider-specific-roles: ${provider_specific_roles:provider.hospital,provider.clinic,provider.practitioner,provider.diagnostics,provider.pharmacy} \ No newline at end of file From a08a54155820740343120938c1bbb82b6c6ff0cf Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 9 Oct 2023 19:14:25 +0530 Subject: [PATCH 02/59] feat : added provider roles --- .../apigateway/ApiGatewayApplication.java | 22 +++++++++++-------- .../filters/AuditValidationFilter.java | 2 +- .../swasth/apigateway/models/BaseRequest.java | 2 +- .../src/main/resources/application.yaml | 3 ++- api-gateway/src/main/resources/rbac.yaml | 10 ++------- .../controllers/v1/ParticipantController.java | 8 ++++--- .../org/swasth/hcx/models/Participant.java | 8 +++---- hcx-apis/src/main/resources/application.yml | 5 +++-- .../swasth/hcx/models/ParticipantTests.java | 16 +++++++++----- .../swasth/hcx/services/OnboardService.java | 5 +---- 10 files changed, 42 insertions(+), 39 deletions(-) diff --git a/api-gateway/src/main/java/org/swasth/apigateway/ApiGatewayApplication.java b/api-gateway/src/main/java/org/swasth/apigateway/ApiGatewayApplication.java index 490e7ab02..cbd25db57 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/ApiGatewayApplication.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/ApiGatewayApplication.java @@ -53,19 +53,23 @@ public Map aclMap(@Value("${rbac.path:classpath:rbac.yaml}") String List rbacs = (List) obj.get("rbac"); Map aclMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - for(Map rbac : rbacs){ + for (Map rbac : rbacs) { Acl acl = new Acl(); - if(rbac.get("paths") != null){ - acl.setPaths(new HashSet((List) rbac.get("paths"))); + if (rbac.get("role") != null) { + String[] roles = ((String) rbac.get("role")).split(","); + for (String role : roles) { + role = role.trim(); + if (rbac.get("paths") != null) { + acl.setPaths(new HashSet((List) rbac.get("paths"))); + } + if (rbac.get("regexPaths") != null) { + acl.setRegexPaths((List) rbac.get("regexPaths")); + } + aclMap.put(role, acl); + } } - if(rbac.get("regexPaths") != null){ - acl.setRegexPaths((List) rbac.get("regexPaths")); - } - aclMap.put((String) rbac.get("role"), acl); } - return aclMap; - } public static void main(String[] args) { diff --git a/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java b/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java index f449ee3a7..68185e1e4 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java @@ -41,7 +41,7 @@ public class AuditValidationFilter extends AbstractGatewayFilterFactory providerSpecificRoles; public AuditValidationFilter() { diff --git a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java index 9250171ba..f977428bc 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java @@ -35,7 +35,7 @@ public class BaseRequest { private String hcxRoles; private String hcxCode; - @Value("${provider-specific-roles}") + @Value("${provider-specific.roles}") private List providerSpecificRoles; public BaseRequest() { diff --git a/api-gateway/src/main/resources/application.yaml b/api-gateway/src/main/resources/application.yaml index 626a47a3b..fa8cbaa1a 100644 --- a/api-gateway/src/main/resources/application.yaml +++ b/api-gateway/src/main/resources/application.yaml @@ -109,7 +109,8 @@ audit: index: ${audit_index:hcx_audit} alias: ${audit_alias:hcx_audit} -provider-specific-roles: ${provider_specific_roles:provider.hospital,provider.clinic,provider.practitioner,provider.diagnostics,provider.pharmacy} +provider-specific: + roles: ${provider_specific_roles:provider.hospital,provider.clinic,provider.practitioner,provider.diagnostics,provider.pharmacy} spring: main: diff --git a/api-gateway/src/main/resources/rbac.yaml b/api-gateway/src/main/resources/rbac.yaml index e6e27eeff..ca0703adf 100644 --- a/api-gateway/src/main/resources/rbac.yaml +++ b/api-gateway/src/main/resources/rbac.yaml @@ -9,14 +9,8 @@ rbac: regexPaths: - /url/** - /auth/** - - roles: - - AUTHENTICATED - - provider - - provider.hospital - - provider.clinic - - provider.practitioner - - provider.diagnostics - - provider.pharmacy + - role: AUTHENTICATED + - role: provider,provider.hospital,provider.clinic,provider.practitioner,provider.diagnostics,provider.pharmacy paths: - /v0.7/coverageeligibility/check - /v0.7/predetermination/submit diff --git a/hcx-apis/src/main/java/org/swasth/hcx/controllers/v1/ParticipantController.java b/hcx-apis/src/main/java/org/swasth/hcx/controllers/v1/ParticipantController.java index 4aeddb426..c9b3da922 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/controllers/v1/ParticipantController.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/controllers/v1/ParticipantController.java @@ -45,6 +45,8 @@ public class ParticipantController extends BaseController { @Value("${postgres.onboardingOtpTable}") private String onboardOtpTable; + @Value("${provider-specific.roles}") + private List specificProviderRoles; @Autowired private ParticipantService service; @@ -52,7 +54,7 @@ public class ParticipantController extends BaseController { public ResponseEntity create(@RequestHeader HttpHeaders header, @RequestBody Map requestBody) { try { logger.info("Creating participant: {}", requestBody.get(PARTICIPANT_NAME)); - Participant participant = new Participant(requestBody); + Participant participant = new Participant(requestBody, specificProviderRoles); service.validate(requestBody, true); requestBody.put(PRIMARY_EMAIL, participant.getprimaryEmail().toLowerCase()); String code = participant.generateCode(fieldSeparator, hcxInstanceName); @@ -68,7 +70,7 @@ public ResponseEntity create(@RequestHeader HttpHeaders header, @Request public ResponseEntity update(@RequestHeader HttpHeaders header, @RequestBody Map requestBody) { try { logger.info("Updating participant: {}", requestBody.get(PARTICIPANT_CODE)); - Participant participant = new Participant(requestBody); + Participant participant = new Participant(requestBody, specificProviderRoles); String code = participant.getParticipantCode(); service.getCertificatesUrl(requestBody, code); service.validate(requestBody, false); @@ -106,7 +108,7 @@ public ResponseEntity delete(@RequestHeader HttpHeaders header, @Request logger.info("Deleting participant: {}", requestBody.get(PARTICIPANT_CODE)); if (!requestBody.containsKey(PARTICIPANT_CODE)) throw new ClientException(ErrorCodes.ERR_INVALID_PARTICIPANT_CODE, PARTICIPANT_CODE_MSG); - Participant participant = new Participant(requestBody); + Participant participant = new Participant(requestBody, specificProviderRoles); Map details = service.getParticipant(participant.getParticipantCode()); return getSuccessResponse(service.delete(details, header, participant.getParticipantCode())); } catch (Exception e) { diff --git a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java index e4d935ff6..0f1979643 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java @@ -13,12 +13,11 @@ public class Participant { private final Map requestBody; + private final List specificProviderRoles; - @Value("${provider-specific-roles}") - private List specificProviderRoles; - - public Participant(Map requestbody) { + public Participant(Map requestbody, List specificProviderRoles) { this.requestBody = requestbody; + this.specificProviderRoles = specificProviderRoles; } public String getprimaryEmail() { @@ -45,6 +44,7 @@ public String generateCode(String fieldSeparator, String hcxInstanceName) { } private String getRoleAppender() { + System.out.println(specificProviderRoles); if (getRoles().contains(PROVIDER) || getRoles().stream().anyMatch(specificProviderRoles::contains)) { return "hosp"; } else if (getRoles().contains(PAYOR)) { diff --git a/hcx-apis/src/main/resources/application.yml b/hcx-apis/src/main/resources/application.yml index 3fda58212..c7205bb6b 100644 --- a/hcx-apis/src/main/resources/application.yml +++ b/hcx-apis/src/main/resources/application.yml @@ -32,7 +32,7 @@ kafka: registry: - basePath: ${registry_basePath:http://aa5c04ed467c04ea89789cead03e4275-320353178.ap-south-1.elb.amazonaws.com:8081} + basePath: ${registry_basePath:http://dev-hcx.swasth.app/registry} hcxcode: ${registry_hcxcode:1-d2d56996-1b77-4abb-b9e9-0e6e7343c72e} organisation-api-path: ${registry_api_path:/api/v1/Organisation} user-api-path: ${registry_user_api_path:/api/v1/User} @@ -153,4 +153,5 @@ email: user-token-subject: ${token_generate_subject:HCX - Protocol APIs Access Token Generation credentials} user-token-message: ${user_token_message:Hi NAME,

Along with participant username and password, api access token can be generated using the following credentials.
  • user_name - USER_ID
  • secret - PASSWORD
  • participant_code - PARTICIPANT_CODE
This API Access token can be used to make protocol API requests. Please refer to the instructions provided in the link to generate access token.

If you have any queries, Please reach out HCX team.

Thanks and Regards
HCX Team.} -provider-specific-roles: ${provider_specific_roles:provider.hospital,provider.clinic,provider.practitioner,provider.diagnostics,provider.pharmacy} \ No newline at end of file +provider-specific: + roles: ${provider_specific_roles:provider.hospital,provider.clinic,provider.practitioner,provider.diagnostics,provider.pharmacy} \ No newline at end of file diff --git a/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java b/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java index 5ded59ffc..e7ab8f8ba 100644 --- a/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java +++ b/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java @@ -4,28 +4,32 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; +import java.util.*; @SpringBootTest(classes = { Participant.class }) public class ParticipantTests { @Test void generate_participant_code_with_payor_role() { - Participant participant = new Participant(getPayorRequestBody()); + Participant participant = new Participant(getPayorRequestBody(),getSpecificProviderRoles()); + System.out.println(participant.getParticipantName()); String code = participant.generateCode("_", "swasth-hcx"); + System.out.println(code); Assertions.assertTrue(code.contains("payr_rakshi")); } @Test void generate_participant_code_with_provider_role() { - Participant participant = new Participant(getProviderRequestBody()); + Participant participant = new Participant(getProviderRequestBody(), getSpecificProviderRoles()); String code = participant.generateCode("_", "swasth-hcx"); Assertions.assertEquals("hosp_rakshi_012345@swasth-hcx", code); } + private List getSpecificProviderRoles() { + return List.of("provider.hospital", "provider.clinic", "provider.practitioner", + "provider.diagnostics", "provider.pharmacy"); + } + private Map getPayorRequestBody() { Map obj = new HashMap<>(); obj.put("participant_name", "Rakshith Insurance"); diff --git a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java index 52daa8130..d792d66b9 100644 --- a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java +++ b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java @@ -174,9 +174,6 @@ public class OnboardService extends BaseController { @Value("${email.failed-identity-sub}") private String failedIdentitySub; - @Value("${provider-specific-roles}") - private List specificProviderRoles; - @PostConstruct() public void init(){ keycloak = Keycloak.getInstance(keycloakURL, keycloakMasterRealm, keycloakAdminUserName, keycloakAdminPassword, keycloackClientId); @@ -248,7 +245,7 @@ private void addParticipantDetails(Map participant, OnboardReques participant.put(REGISTRY_STATUS, CREATED); if (((ArrayList) participant.get(ROLES)).contains(PAYOR)) participant.put(SCHEME_CODE, "default"); - if (((ArrayList) participant.get(ROLES)).contains(PROVIDER) || ((ArrayList) participant.get(ROLES)).stream().anyMatch(specificProviderRoles::contains)) + if (((ArrayList) participant.get(ROLES)).contains(PROVIDER)) participant.put(APPLICANT_CODE, request.getApplicantCode()); } From 84c445173e628769ac4905b3ae79b6cb17d40149 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 9 Oct 2023 19:16:17 +0530 Subject: [PATCH 03/59] Update ParticipantTests.java --- .../src/test/java/org/swasth/hcx/models/ParticipantTests.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java b/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java index e7ab8f8ba..239b60fad 100644 --- a/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java +++ b/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java @@ -12,9 +12,7 @@ public class ParticipantTests { @Test void generate_participant_code_with_payor_role() { Participant participant = new Participant(getPayorRequestBody(),getSpecificProviderRoles()); - System.out.println(participant.getParticipantName()); String code = participant.generateCode("_", "swasth-hcx"); - System.out.println(code); Assertions.assertTrue(code.contains("payr_rakshi")); } From b25719e7932464c1bb0e3127f1358dc0c496581b Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 9 Oct 2023 19:24:53 +0530 Subject: [PATCH 04/59] Update Participant.java --- hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java index 0f1979643..48e040fed 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java @@ -1,7 +1,6 @@ package org.swasth.hcx.models; import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Value; import org.swasth.common.utils.SlugUtils; import java.security.SecureRandom; @@ -44,7 +43,6 @@ public String generateCode(String fieldSeparator, String hcxInstanceName) { } private String getRoleAppender() { - System.out.println(specificProviderRoles); if (getRoles().contains(PROVIDER) || getRoles().stream().anyMatch(specificProviderRoles::contains)) { return "hosp"; } else if (getRoles().contains(PAYOR)) { From 1b55ed8e0fbc54585c06b4a3182ec165f34a3aa4 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Tue, 10 Oct 2023 10:58:24 +0530 Subject: [PATCH 05/59] feat : Testcases for auditrequestTest --- .../java/org/swasth/apigateway/BaseSpec.java | 6 +++ .../apigateway/filters/AuditRequestTest.java | 39 +++++++++++++++++++ .../controllers/v1/ParticipantController.java | 8 ++-- .../org/swasth/hcx/models/Participant.java | 8 ++-- 4 files changed, 53 insertions(+), 8 deletions(-) diff --git a/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java b/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java index 7b11eb252..8c82fa9a4 100644 --- a/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java +++ b/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java @@ -202,6 +202,12 @@ protected Map getProviderDetails() throws Exception { return JSONUtils.deserialize("{ \"participant_code\":\"f7c0e759-bec3-431b-8c4f-6b294d103a74\",\"participant_name\": \"New Teja Hospital888\", \"primary_mobile\": \"9493347239\", \"primary_email\": \"dharmateja888@gmail.com\", \"roles\": [ \"provider\" ], \"address\": { \"plot\": \"5-4-199\", \"street\": \"road no 12\", \"landmark\": \"Jawaharlal Nehru Road\", \"village\": \"Nampally\", \"district\": \"Hyderabad\", \"state\": \"Telangana\", \"pincode\": \"500805\", \"osid\": \"f901ba37-e09f-4d84-a75f-5e203f8ad4da\", \"@type\": \"address\", \"locality\": \"Nampally\" }, \"phone\": [ \"040-387658992\" ], \"status\": \"Active\", \"endpoint_url\": \"https://677e6fd9-57cc-466c-80f6-ae0462762872.mock.pstmn.io\", \"payment_details\": { \"account_number\": \"4707890099809809\", \"ifsc_code\": \"ICICI\", \"osid\": \"da192c1e-5ad4-47bc-b425-de4f7bbc9bd0\" }, \"signing_cert_path\": \"urn:isbn:0-476-27557-4\", \"linked_registry_codes\": [ \"22344\" ], \"encryption_cert\": \"urn:isbn:0-4234\", \"osOwner\": [ \"f7c0e759-bec3-431b-8c4f-6b294d103a74\" ], \"osid\": \"68c5deca-8299-4feb-b441-923bb649a9a3\", \"@type\": \"Organisation\", \"payment\": { \"ifsc_code\": \"ICICI\", \"account_number\": \"4707890099809809\", \"@type\": \"payment_details\", \"osid\": \"3a3bd68a-848a-4d52-9ec2-07a92d765fb4\" } }", Map.class); } + protected Map getProviderHospitalDetails() throws Exception { + return JSONUtils.deserialize("{ \"participant_code\":\"f7c0e759-bec3-431b-8c4f-6b294d103a74\",\"participant_name\": \"New Teja Hospital888\", \"primary_mobile\": \"9493347239\", \"primary_email\": \"dharmateja888@gmail.com\", \"roles\": [ \"provider.hospital\" ], \"address\": { \"plot\": \"5-4-199\", \"street\": \"road no 12\", \"landmark\": \"Jawaharlal Nehru Road\", \"village\": \"Nampally\", \"district\": \"Hyderabad\", \"state\": \"Telangana\", \"pincode\": \"500805\", \"osid\": \"f901ba37-e09f-4d84-a75f-5e203f8ad4da\", \"@type\": \"address\", \"locality\": \"Nampally\" }, \"phone\": [ \"040-387658992\" ], \"status\": \"Active\", \"endpoint_url\": \"https://677e6fd9-57cc-466c-80f6-ae0462762872.mock.pstmn.io\", \"payment_details\": { \"account_number\": \"4707890099809809\", \"ifsc_code\": \"ICICI\", \"osid\": \"da192c1e-5ad4-47bc-b425-de4f7bbc9bd0\" }, \"signing_cert_path\": \"urn:isbn:0-476-27557-4\", \"linked_registry_codes\": [ \"22344\" ], \"encryption_cert\": \"urn:isbn:0-4234\", \"osOwner\": [ \"f7c0e759-bec3-431b-8c4f-6b294d103a74\" ], \"osid\": \"68c5deca-8299-4feb-b441-923bb649a9a3\", \"@type\": \"Organisation\", \"payment\": { \"ifsc_code\": \"ICICI\", \"account_number\": \"4707890099809809\", \"@type\": \"payment_details\", \"osid\": \"3a3bd68a-848a-4d52-9ec2-07a92d765fb4\" } }", Map.class); + } + protected Map getProviderPharmacyDetails() throws Exception { + return JSONUtils.deserialize("{ \"participant_code\":\"f7c0e759-bec3-431b-8c4f-6b294d103a74\",\"participant_name\": \"New Teja Hospital888\", \"primary_mobile\": \"9493347239\", \"primary_email\": \"dharmateja888@gmail.com\", \"roles\": [ \"provider.pharmacy\" ], \"address\": { \"plot\": \"5-4-199\", \"street\": \"road no 12\", \"landmark\": \"Jawaharlal Nehru Road\", \"village\": \"Nampally\", \"district\": \"Hyderabad\", \"state\": \"Telangana\", \"pincode\": \"500805\", \"osid\": \"f901ba37-e09f-4d84-a75f-5e203f8ad4da\", \"@type\": \"address\", \"locality\": \"Nampally\" }, \"phone\": [ \"040-387658992\" ], \"status\": \"Active\", \"endpoint_url\": \"https://677e6fd9-57cc-466c-80f6-ae0462762872.mock.pstmn.io\", \"payment_details\": { \"account_number\": \"4707890099809809\", \"ifsc_code\": \"ICICI\", \"osid\": \"da192c1e-5ad4-47bc-b425-de4f7bbc9bd0\" }, \"signing_cert_path\": \"urn:isbn:0-476-27557-4\", \"linked_registry_codes\": [ \"22344\" ], \"encryption_cert\": \"urn:isbn:0-4234\", \"osOwner\": [ \"f7c0e759-bec3-431b-8c4f-6b294d103a74\" ], \"osid\": \"68c5deca-8299-4feb-b441-923bb649a9a3\", \"@type\": \"Organisation\", \"payment\": { \"ifsc_code\": \"ICICI\", \"account_number\": \"4707890099809809\", \"@type\": \"payment_details\", \"osid\": \"3a3bd68a-848a-4d52-9ec2-07a92d765fb4\" } }", Map.class); + } protected Map getBlockedProviderDetails() throws Exception { return JSONUtils.deserialize("{ \"participant_name\": \"New Teja Hospital888\", \"primary_mobile\": \"9493347239\", \"primary_email\": \"dharmateja888@gmail.com\", \"roles\": [ \"provider\" ], \"address\": { \"plot\": \"5-4-199\", \"street\": \"road no 12\", \"landmark\": \"Jawaharlal Nehru Road\", \"village\": \"Nampally\", \"district\": \"Hyderabad\", \"state\": \"Telangana\", \"pincode\": \"500805\", \"osid\": \"f901ba37-e09f-4d84-a75f-5e203f8ad4da\", \"@type\": \"address\", \"locality\": \"Nampally\" }, \"phone\": [ \"040-387658992\" ], \"status\": \"Blocked\", \"endpoint_url\": \"https://677e6fd9-57cc-466c-80f6-ae0462762872.mock.pstmn.io\", \"payment_details\": { \"account_number\": \"4707890099809809\", \"ifsc_code\": \"ICICI\", \"osid\": \"da192c1e-5ad4-47bc-b425-de4f7bbc9bd0\" }, \"signing_cert_path\": \"urn:isbn:0-476-27557-4\", \"linked_registry_codes\": [ \"22344\" ], \"encryption_cert\": \"urn:isbn:0-4234\", \"osOwner\": [ \"f7c0e759-bec3-431b-8c4f-6b294d103a74\" ], \"osid\": \"68c5deca-8299-4feb-b441-923bb649a9a3\", \"@type\": \"Organisation\", \"payment\": { \"ifsc_code\": \"ICICI\", \"account_number\": \"4707890099809809\", \"@type\": \"payment_details\", \"osid\": \"3a3bd68a-848a-4d52-9ec2-07a92d765fb4\" } }", Map.class); } diff --git a/api-gateway/src/test/java/org/swasth/apigateway/filters/AuditRequestTest.java b/api-gateway/src/test/java/org/swasth/apigateway/filters/AuditRequestTest.java index d80c53a26..6cf9a7097 100644 --- a/api-gateway/src/test/java/org/swasth/apigateway/filters/AuditRequestTest.java +++ b/api-gateway/src/test/java/org/swasth/apigateway/filters/AuditRequestTest.java @@ -33,7 +33,46 @@ public void check_audit_request_success_scenario() throws Exception { assertEquals(result.getStatus(), HttpStatus.ACCEPTED); }); } + // Testcase for provider specific roles + @Test + public void check_audit_request_success_scenario_for_hospital_role() throws Exception { + server.enqueue(new MockResponse() + .setResponseCode(202) + .addHeader("Content-Type", "application/json")); + + Mockito.when(registryService.getDetails(anyString())) + .thenReturn(Collections.singletonList(getProviderHospitalDetails())); + + client.post().uri(versionPrefix + Constants.AUDIT_SEARCH) + .header(Constants.AUTHORIZATION, getProviderToken()) + .header("X-jwt-sub", "f7c0e759-bec3-431b-8c4f-6b294d103a74") + .bodyValue(getAuditRequestBody()) + .exchange() + .expectBody(Map.class) + .consumeWith(result -> { + assertEquals(result.getStatus(), HttpStatus.ACCEPTED); + }); + } + + @Test + public void check_audit_request_success_scenario_for_payor_role() throws Exception { + server.enqueue(new MockResponse() + .setResponseCode(202) + .addHeader("Content-Type", "application/json")); + + Mockito.when(registryService.getDetails(anyString())) + .thenReturn(Collections.singletonList(getPayorDetails())); + client.post().uri(versionPrefix + Constants.AUDIT_SEARCH) + .header(Constants.AUTHORIZATION, getPayorToken()) + .header("X-jwt-sub", "f7b916c4-e148-4cd2-aa66-472e3610d869") + .bodyValue(getAuditRequestBody()) + .exchange() + .expectBody(Map.class) + .consumeWith(result -> { + assertEquals(result.getStatus(), HttpStatus.ACCEPTED); + }); + } @Test public void check_audit_request_invalid_sender_scenario() throws Exception { Mockito.when(registryService.getDetails(anyString())) diff --git a/hcx-apis/src/main/java/org/swasth/hcx/controllers/v1/ParticipantController.java b/hcx-apis/src/main/java/org/swasth/hcx/controllers/v1/ParticipantController.java index c9b3da922..2f9c09f46 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/controllers/v1/ParticipantController.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/controllers/v1/ParticipantController.java @@ -46,7 +46,7 @@ public class ParticipantController extends BaseController { private String onboardOtpTable; @Value("${provider-specific.roles}") - private List specificProviderRoles; + private List providerSpecificRoles; @Autowired private ParticipantService service; @@ -54,7 +54,7 @@ public class ParticipantController extends BaseController { public ResponseEntity create(@RequestHeader HttpHeaders header, @RequestBody Map requestBody) { try { logger.info("Creating participant: {}", requestBody.get(PARTICIPANT_NAME)); - Participant participant = new Participant(requestBody, specificProviderRoles); + Participant participant = new Participant(requestBody, providerSpecificRoles); service.validate(requestBody, true); requestBody.put(PRIMARY_EMAIL, participant.getprimaryEmail().toLowerCase()); String code = participant.generateCode(fieldSeparator, hcxInstanceName); @@ -70,7 +70,7 @@ public ResponseEntity create(@RequestHeader HttpHeaders header, @Request public ResponseEntity update(@RequestHeader HttpHeaders header, @RequestBody Map requestBody) { try { logger.info("Updating participant: {}", requestBody.get(PARTICIPANT_CODE)); - Participant participant = new Participant(requestBody, specificProviderRoles); + Participant participant = new Participant(requestBody, providerSpecificRoles); String code = participant.getParticipantCode(); service.getCertificatesUrl(requestBody, code); service.validate(requestBody, false); @@ -108,7 +108,7 @@ public ResponseEntity delete(@RequestHeader HttpHeaders header, @Request logger.info("Deleting participant: {}", requestBody.get(PARTICIPANT_CODE)); if (!requestBody.containsKey(PARTICIPANT_CODE)) throw new ClientException(ErrorCodes.ERR_INVALID_PARTICIPANT_CODE, PARTICIPANT_CODE_MSG); - Participant participant = new Participant(requestBody, specificProviderRoles); + Participant participant = new Participant(requestBody, providerSpecificRoles); Map details = service.getParticipant(participant.getParticipantCode()); return getSuccessResponse(service.delete(details, header, participant.getParticipantCode())); } catch (Exception e) { diff --git a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java index 48e040fed..6623606ca 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java @@ -12,11 +12,11 @@ public class Participant { private final Map requestBody; - private final List specificProviderRoles; + private final List providerSpecificRoles; - public Participant(Map requestbody, List specificProviderRoles) { + public Participant(Map requestbody, List providerSpecificRoles) { this.requestBody = requestbody; - this.specificProviderRoles = specificProviderRoles; + this.providerSpecificRoles = providerSpecificRoles; } public String getprimaryEmail() { @@ -43,7 +43,7 @@ public String generateCode(String fieldSeparator, String hcxInstanceName) { } private String getRoleAppender() { - if (getRoles().contains(PROVIDER) || getRoles().stream().anyMatch(specificProviderRoles::contains)) { + if (getRoles().contains(PROVIDER) || getRoles().stream().anyMatch(providerSpecificRoles::contains)) { return "hosp"; } else if (getRoles().contains(PAYOR)) { return "payr"; From ec08ae11fb4b8186b89df2823730134aafbe23d9 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Tue, 10 Oct 2023 11:54:20 +0530 Subject: [PATCH 06/59] feat : removed code smells --- .../src/test/java/org/swasth/apigateway/BaseSpec.java | 3 --- .../org/swasth/apigateway/filters/AuditRequestTest.java | 8 ++++---- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java b/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java index 8c82fa9a4..06e6a2f03 100644 --- a/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java +++ b/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java @@ -205,9 +205,6 @@ protected Map getProviderDetails() throws Exception { protected Map getProviderHospitalDetails() throws Exception { return JSONUtils.deserialize("{ \"participant_code\":\"f7c0e759-bec3-431b-8c4f-6b294d103a74\",\"participant_name\": \"New Teja Hospital888\", \"primary_mobile\": \"9493347239\", \"primary_email\": \"dharmateja888@gmail.com\", \"roles\": [ \"provider.hospital\" ], \"address\": { \"plot\": \"5-4-199\", \"street\": \"road no 12\", \"landmark\": \"Jawaharlal Nehru Road\", \"village\": \"Nampally\", \"district\": \"Hyderabad\", \"state\": \"Telangana\", \"pincode\": \"500805\", \"osid\": \"f901ba37-e09f-4d84-a75f-5e203f8ad4da\", \"@type\": \"address\", \"locality\": \"Nampally\" }, \"phone\": [ \"040-387658992\" ], \"status\": \"Active\", \"endpoint_url\": \"https://677e6fd9-57cc-466c-80f6-ae0462762872.mock.pstmn.io\", \"payment_details\": { \"account_number\": \"4707890099809809\", \"ifsc_code\": \"ICICI\", \"osid\": \"da192c1e-5ad4-47bc-b425-de4f7bbc9bd0\" }, \"signing_cert_path\": \"urn:isbn:0-476-27557-4\", \"linked_registry_codes\": [ \"22344\" ], \"encryption_cert\": \"urn:isbn:0-4234\", \"osOwner\": [ \"f7c0e759-bec3-431b-8c4f-6b294d103a74\" ], \"osid\": \"68c5deca-8299-4feb-b441-923bb649a9a3\", \"@type\": \"Organisation\", \"payment\": { \"ifsc_code\": \"ICICI\", \"account_number\": \"4707890099809809\", \"@type\": \"payment_details\", \"osid\": \"3a3bd68a-848a-4d52-9ec2-07a92d765fb4\" } }", Map.class); } - protected Map getProviderPharmacyDetails() throws Exception { - return JSONUtils.deserialize("{ \"participant_code\":\"f7c0e759-bec3-431b-8c4f-6b294d103a74\",\"participant_name\": \"New Teja Hospital888\", \"primary_mobile\": \"9493347239\", \"primary_email\": \"dharmateja888@gmail.com\", \"roles\": [ \"provider.pharmacy\" ], \"address\": { \"plot\": \"5-4-199\", \"street\": \"road no 12\", \"landmark\": \"Jawaharlal Nehru Road\", \"village\": \"Nampally\", \"district\": \"Hyderabad\", \"state\": \"Telangana\", \"pincode\": \"500805\", \"osid\": \"f901ba37-e09f-4d84-a75f-5e203f8ad4da\", \"@type\": \"address\", \"locality\": \"Nampally\" }, \"phone\": [ \"040-387658992\" ], \"status\": \"Active\", \"endpoint_url\": \"https://677e6fd9-57cc-466c-80f6-ae0462762872.mock.pstmn.io\", \"payment_details\": { \"account_number\": \"4707890099809809\", \"ifsc_code\": \"ICICI\", \"osid\": \"da192c1e-5ad4-47bc-b425-de4f7bbc9bd0\" }, \"signing_cert_path\": \"urn:isbn:0-476-27557-4\", \"linked_registry_codes\": [ \"22344\" ], \"encryption_cert\": \"urn:isbn:0-4234\", \"osOwner\": [ \"f7c0e759-bec3-431b-8c4f-6b294d103a74\" ], \"osid\": \"68c5deca-8299-4feb-b441-923bb649a9a3\", \"@type\": \"Organisation\", \"payment\": { \"ifsc_code\": \"ICICI\", \"account_number\": \"4707890099809809\", \"@type\": \"payment_details\", \"osid\": \"3a3bd68a-848a-4d52-9ec2-07a92d765fb4\" } }", Map.class); - } protected Map getBlockedProviderDetails() throws Exception { return JSONUtils.deserialize("{ \"participant_name\": \"New Teja Hospital888\", \"primary_mobile\": \"9493347239\", \"primary_email\": \"dharmateja888@gmail.com\", \"roles\": [ \"provider\" ], \"address\": { \"plot\": \"5-4-199\", \"street\": \"road no 12\", \"landmark\": \"Jawaharlal Nehru Road\", \"village\": \"Nampally\", \"district\": \"Hyderabad\", \"state\": \"Telangana\", \"pincode\": \"500805\", \"osid\": \"f901ba37-e09f-4d84-a75f-5e203f8ad4da\", \"@type\": \"address\", \"locality\": \"Nampally\" }, \"phone\": [ \"040-387658992\" ], \"status\": \"Blocked\", \"endpoint_url\": \"https://677e6fd9-57cc-466c-80f6-ae0462762872.mock.pstmn.io\", \"payment_details\": { \"account_number\": \"4707890099809809\", \"ifsc_code\": \"ICICI\", \"osid\": \"da192c1e-5ad4-47bc-b425-de4f7bbc9bd0\" }, \"signing_cert_path\": \"urn:isbn:0-476-27557-4\", \"linked_registry_codes\": [ \"22344\" ], \"encryption_cert\": \"urn:isbn:0-4234\", \"osOwner\": [ \"f7c0e759-bec3-431b-8c4f-6b294d103a74\" ], \"osid\": \"68c5deca-8299-4feb-b441-923bb649a9a3\", \"@type\": \"Organisation\", \"payment\": { \"ifsc_code\": \"ICICI\", \"account_number\": \"4707890099809809\", \"@type\": \"payment_details\", \"osid\": \"3a3bd68a-848a-4d52-9ec2-07a92d765fb4\" } }", Map.class); } diff --git a/api-gateway/src/test/java/org/swasth/apigateway/filters/AuditRequestTest.java b/api-gateway/src/test/java/org/swasth/apigateway/filters/AuditRequestTest.java index 6cf9a7097..aa2f4c48d 100644 --- a/api-gateway/src/test/java/org/swasth/apigateway/filters/AuditRequestTest.java +++ b/api-gateway/src/test/java/org/swasth/apigateway/filters/AuditRequestTest.java @@ -35,7 +35,7 @@ public void check_audit_request_success_scenario() throws Exception { } // Testcase for provider specific roles @Test - public void check_audit_request_success_scenario_for_hospital_role() throws Exception { + void check_audit_request_success_scenario_for_hospital_role() throws Exception { server.enqueue(new MockResponse() .setResponseCode(202) .addHeader("Content-Type", "application/json")); @@ -50,12 +50,12 @@ public void check_audit_request_success_scenario_for_hospital_role() throws Exce .exchange() .expectBody(Map.class) .consumeWith(result -> { - assertEquals(result.getStatus(), HttpStatus.ACCEPTED); + assertEquals(HttpStatus.ACCEPTED, result.getStatus()); }); } @Test - public void check_audit_request_success_scenario_for_payor_role() throws Exception { + void check_audit_request_success_scenario_for_payor_role() throws Exception { server.enqueue(new MockResponse() .setResponseCode(202) .addHeader("Content-Type", "application/json")); @@ -70,7 +70,7 @@ public void check_audit_request_success_scenario_for_payor_role() throws Excepti .exchange() .expectBody(Map.class) .consumeWith(result -> { - assertEquals(result.getStatus(), HttpStatus.ACCEPTED); + assertEquals(HttpStatus.ACCEPTED, result.getStatus()); }); } @Test From ff3d7a10420100e86488c0950df8ab1176cd2302 Mon Sep 17 00:00:00 2001 From: KrutikaPhirangi Date: Tue, 10 Oct 2023 18:26:00 +0530 Subject: [PATCH 07/59] HCX-796:API access secret regenerate and expiry --- .../hcx/service/KeycloakApiAccessService.java | 12 +- hcx-apis/src/main/resources/application.yml | 7 +- .../org/swasth/common/utils/Constants.java | 1 + .../main/resources/networkNotifications.yaml | 45 ++++++++ .../hcx/controllers/v1/OnboardController.java | 12 ++ .../swasth/hcx/services/OnboardService.java | 57 +++++++--- .../src/main/resources/application.yml | 7 +- .../resources/templates/api-access-secret.ftl | 15 +++ .../job/CommonSchedulerJob.java | 9 +- .../schedulers/UserSecretScheduler.java | 105 ++++++++++++++++++ .../src/main/resources/application.yml | 6 + 11 files changed, 258 insertions(+), 18 deletions(-) create mode 100644 hcx-onboard/src/main/resources/templates/api-access-secret.ftl create mode 100644 hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java diff --git a/hcx-apis/src/main/java/org/swasth/hcx/service/KeycloakApiAccessService.java b/hcx-apis/src/main/java/org/swasth/hcx/service/KeycloakApiAccessService.java index 7c1fc04a4..fbb6ee1b3 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/service/KeycloakApiAccessService.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/service/KeycloakApiAccessService.java @@ -13,6 +13,7 @@ import org.swasth.common.exception.ClientException; import org.swasth.common.helpers.EventGenerator; import org.swasth.kafka.client.KafkaClient; +import org.swasth.postgresql.IDatabaseService; import javax.ws.rs.core.Response; import java.security.SecureRandom; @@ -35,6 +36,10 @@ public class KeycloakApiAccessService { private String keycloakAdminUserName; @Value("${keycloak.master-realm}") private String keycloakMasterRealm; + @Value("${postgres.api-access-secrets-expiry-table}") + private String apiAccessTable; + @Value("${secret.expiry-time}") + private int secretExpiry; @Value("${keycloak.protocol-access-realm}") private String keycloackProtocolAccessRealm; @Value("${keycloak.admin-client-id}") @@ -48,6 +53,8 @@ public class KeycloakApiAccessService { @Autowired private KafkaClient kafkaClient; @Autowired + private IDatabaseService postgreSQLClient; + @Autowired protected EventGenerator eventGenerator; public void addUserWithParticipant(String email, String participantCode, String name) throws ClientException { @@ -65,6 +72,9 @@ public void addUserWithParticipant(String email, String participantCode, String response = usersResource.create(user); response.close(); if (response.getStatus() == 201) { + String query = String.format("INSERT INTO %s (user_id,participant_code,secret_generation_date,secret_expiry_date,username)VALUES ('%s','%s',%d,%d,'%s');", apiAccessTable, email, + participantCode, System.currentTimeMillis(), System.currentTimeMillis() + (secretExpiry * 24 * 60 * 60 * 1000), userName); + postgreSQLClient.execute(query); String message = userEmailMessage; message = message.replace("NAME", name).replace("USER_ID", email).replace("PASSWORD", password).replace("PARTICIPANT_CODE", participantCode); kafkaClient.send(messageTopic, EMAIL, eventGenerator.getEmailMessageEvent(message, emailSub, List.of(email), new ArrayList<>(), new ArrayList<>())); @@ -95,7 +105,7 @@ private UserRepresentation createUserRequest(String userName, String name, Strin return user; } - private String generateRandomPassword(){ + private String generateRandomPassword() { String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#&*"; SecureRandom secureRandom = new SecureRandom(); StringBuilder password = new StringBuilder(16); diff --git a/hcx-apis/src/main/resources/application.yml b/hcx-apis/src/main/resources/application.yml index d97196db8..3f4bf7409 100644 --- a/hcx-apis/src/main/resources/application.yml +++ b/hcx-apis/src/main/resources/application.yml @@ -32,7 +32,7 @@ kafka: registry: - basePath: ${registry_basePath:http://aa5c04ed467c04ea89789cead03e4275-320353178.ap-south-1.elb.amazonaws.com:8081} + basePath: ${registry_basePath:http://dev-hcx.swasth.app/registry} hcxcode: ${registry_hcxcode:1-d2d56996-1b77-4abb-b9e9-0e6e7343c72e} organisation-api-path: ${registry_api_path:/api/v1/Organisation} user-api-path: ${registry_user_api_path:/api/v1/User} @@ -46,6 +46,7 @@ postgres: user: ${postgres_user:postgres} password: ${postgres_password:postgres} tablename: ${postgres_tablename:payload} + api-access-secrets-expiry-table: ${api_access_secrets_expiry_table:api_access_secrets_expiry} onboardingTable: ${onboarding_table:onboarding} onboardingOtpTable : ${onboarding_otp:onboarding_otp} subscription: @@ -55,7 +56,6 @@ postgres: subscriptionSelectQuery: ${postgres_subscription_subscriptionSelectQuery:SELECT subscription_id,subscription_request_id,subscription_status,topic_code,sender_code,recipient_code,expiry,is_delegated FROM %s WHERE subscription_id = '%s' AND sender_code = '%s' } updateSubscriptionQuery: ${postgres_subscription_updateSubscriptionQuery:UPDATE %s SET subscription_status = '%s' WHERE subscription_id = '%s' RETURNING %s } - #hcx error headers plainrequest: headers: @@ -152,3 +152,6 @@ email: pwd: ${email_pwd:} user-token-subject: ${token_generate_subject:HCX - Protocol APIs Access Token Generation credentials} user-token-message: ${user_token_message:Hi NAME,

Along with participant username and password, api access token can be generated using the following credentials.
  • user_name - USER_ID
  • secret - PASSWORD
  • participant_code - PARTICIPANT_CODE
This API Access token can be used to make protocol API requests. Please refer to the instructions provided in the link to generate access token.

If you have any queries, Please reach out HCX team.

Thanks and Regards
HCX Team.} + +secret: + expiry-time: ${secret_expiry_time:90} \ No newline at end of file diff --git a/hcx-core/hcx-common/src/main/java/org/swasth/common/utils/Constants.java b/hcx-core/hcx-common/src/main/java/org/swasth/common/utils/Constants.java index ebc7c3e87..326d73f28 100644 --- a/hcx-core/hcx-common/src/main/java/org/swasth/common/utils/Constants.java +++ b/hcx-core/hcx-common/src/main/java/org/swasth/common/utils/Constants.java @@ -219,6 +219,7 @@ public class Constants { public static final String ENCRYPTION_CERT = "encryption_cert"; public static final String ENCRYPTION_CERT_EXPIRY = "encryption_cert_expiry"; public static final String SIGNING_CERT_PATH_EXPIRY = "sigining_cert_expiry"; + public static final String API_ACCESS_SECRET_GENERATE = "/api-access/secret/generate"; public static final String PUBLIC_KEY = "public_key"; public static final String PRIVATE_KEY = "private_key"; public static final String PASSWORD = "password"; diff --git a/hcx-core/hcx-common/src/main/resources/networkNotifications.yaml b/hcx-core/hcx-common/src/main/resources/networkNotifications.yaml index b6dbb0aac..af689e702 100644 --- a/hcx-core/hcx-common/src/main/resources/networkNotifications.yaml +++ b/hcx-core/hcx-common/src/main/resources/networkNotifications.yaml @@ -348,4 +348,49 @@ ${DDMMYYYY}. Please renew your encryption key before ${DDMMYYYY} to carry on operating on HCX."} status: Active + is_delegate: false +- topic_code: notif-secret-expiry + title: Api access secret expiry + description: >- + Notification about the api access secret expiration for the participant in the + ecosystem. + allowed_senders: + - HIE/HIO.HCX + allowed_recipients: + - payor + - provider + - agency.tpa + - agency.regulator + - research + - member.isnp + - agency.sponsor + - HIE/HIO.HCX + type: Targeted + category: Network + priority: 1 + template: >- + {"message": "Api access secret will be going to expiry in + ${days} days.Please reset your api access secret."} + status: Active + is_delegate: false +- topic_code: notif-secret-expired + title: Api access secret expired + description: Notification about api access secret expired + allowed_senders: + - HIE/HIO.HCX + allowed_recipients: + - provider + - payor + - agency.tpa + - agency.regulator + - research + - member.isnp + - agency.sponsor + - HIE/HIO.HCX + type: Targeted + category: Network + priority: 1 + template: >- + {"message": "Your api access secret got expired, please update your details with secret."} + status: Active is_delegate: false \ No newline at end of file diff --git a/hcx-onboard/src/main/java/org/swasth/hcx/controllers/v1/OnboardController.java b/hcx-onboard/src/main/java/org/swasth/hcx/controllers/v1/OnboardController.java index a33acc9b9..cae631a94 100644 --- a/hcx-onboard/src/main/java/org/swasth/hcx/controllers/v1/OnboardController.java +++ b/hcx-onboard/src/main/java/org/swasth/hcx/controllers/v1/OnboardController.java @@ -5,6 +5,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.swasth.common.dto.Response; +import org.swasth.common.exception.ClientException; import org.swasth.common.utils.Constants; import org.swasth.hcx.controllers.BaseController; import org.swasth.hcx.services.OnboardService; @@ -126,4 +127,15 @@ public ResponseEntity generatePassword(@RequestBody Map return exceptionHandler("", ONBOARD_APPLICANT_PASSWORD_GENERATE, new Response(), e); } } + @PostMapping(API_ACCESS_SECRET_GENERATE) + public ResponseEntity apiAccessSecretGenerate(@RequestBody Map requestBody, @RequestHeader HttpHeaders headers) throws Exception { + try { + if(!requestBody.containsKey(USER_ID) || !requestBody.containsKey(PARTICIPANT_CODE)){ + throw new ClientException("user id or participant code is missing"); + } + return getSuccessResponse(service.generateAndSetUserSecret(requestBody)); + } catch (Exception e) { + return exceptionHandler((String) requestBody.getOrDefault(USER_ID, ""), API_ACCESS_SECRET_GENERATE, new Response(), e); + } + } } \ No newline at end of file diff --git a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java index d792d66b9..c070640a8 100644 --- a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java +++ b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java @@ -11,7 +11,9 @@ import org.keycloak.admin.client.Keycloak; import org.keycloak.admin.client.resource.RealmResource; import org.keycloak.admin.client.resource.UserResource; +import org.keycloak.admin.client.resource.UsersResource; import org.keycloak.representations.idm.CredentialRepresentation; +import org.keycloak.representations.idm.UserRepresentation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -132,7 +134,10 @@ public class OnboardService extends BaseController { private String keycloackParticipantRealm; @Value("${keycloak.client-id}") private String keycloackClientId; - + @Value("${keycloak.api-access-realm}") + private String keycloakApiAccessRealm; + @Value("${postgres.table.api-access-secrets-expiry}") + private String apiAccessTable; @Value("${endpoint.user-invite}") private String userInviteEndpoint; @Value("${email.user-invite-sub}") @@ -145,7 +150,8 @@ public class OnboardService extends BaseController { private String emailConfig; @Value("${onboard.phone}") private String phoneConfig; - + @Value("${secret.expiry-time}") + private int secretExpiry; @Autowired private IDatabaseService postgreSQLClient; @@ -894,6 +900,13 @@ private String userInviteAcceptParticipantTemplate(String participantName, Strin return freemarkerService.renderTemplate("user-invite-accepted-participant.ftl", model); } + private String apiAccessSecret(String username, String password, String participantCode) throws Exception { + Map model = new HashMap<>(); + model.put("USER_NAME", username); + model.put("PARTICIPANT_CODE", participantCode); + model.put("PASSWORD", password); + return freemarkerService.renderTemplate("api-access-secret.ftl", model); + } private String userInviteUserTemplate(String email, String name, String role, URL signedURL) throws Exception { Map model = new HashMap<>(); @@ -1093,22 +1106,24 @@ private Map updateMockDetails(Map mockParticipan mockParticipantDetails.put(PASSWORD, password); TimeUnit.SECONDS.sleep(3); // After creating participant, elasticsearch will retrieve data after one second hence added two seconds delay for search API. Map registryDetails = getParticipant(PARTICIPANT_CODE,childParticipantCode); - setKeycloakPassword(childParticipantCode, password ,registryDetails); + ArrayList osOwner = (ArrayList) registryDetails.get(OS_OWNER); + setKeycloakPassword(password, osOwner.get(0), keycloackParticipantRealm); logger.info("created Mock participant for :: parent participant code : " + parentParticipantCode + " :: child participant code : " + childParticipantCode); return mockParticipantDetails; } - private void setKeycloakPassword(String participantCode, String password , Map registryDetails) throws ClientException { + private void setKeycloakPassword(String password, String user, String realm) throws ClientException { try { - ArrayList osOwner = (ArrayList) registryDetails.get(OS_OWNER); - RealmResource realmResource = keycloak.realm(keycloackParticipantRealm); - UserResource userResource = realmResource.users().get(osOwner.get(0)); + RealmResource realmResource = keycloak.realm(realm); + UserResource userResource = realmResource.users().get(user); CredentialRepresentation passwordCred = new CredentialRepresentation(); passwordCred.setTemporary(false); passwordCred.setType(CredentialRepresentation.PASSWORD); passwordCred.setValue(password); userResource.resetPassword(passwordCred); - logger.info("The Keycloak password for the os_owner :" + osOwner.get(0) + " has been successfully updated"); + String userId = userResource.toRepresentation().getId(); + realmResource.users().get(userId).logout(); + logger.info("The Keycloak password for the user :" + user + " has been successfully updated, and their sessions have been invalidated."); } catch (Exception e) { throw new ClientException("Unable to set keycloak password : " + e.getMessage()); } @@ -1188,12 +1203,9 @@ private String generateRandomPassword(int length){ public Response generateAndSetPassword(HttpHeaders headers, String participantCode) throws Exception { String password = generateRandomPassword(24); Map registryDetails = getParticipant(PARTICIPANT_CODE, participantCode); - setKeycloakPassword(participantCode, password, registryDetails); ArrayList osOwner = (ArrayList) registryDetails.get(OS_OWNER); - RealmResource realmResource = keycloak.realm(keycloackParticipantRealm); - UserResource userResource=realmResource.users().get(osOwner.get(0)); - String username = userResource.toRepresentation().getUsername(); - kafkaClient.send(messageTopic, EMAIL, eventGenerator.getEmailMessageEvent(passwordGenerate((String) registryDetails.get(PARTICIPANT_NAME),password,username), passwordGenerateSub, Arrays.asList((String) registryDetails.get(PRIMARY_EMAIL)), getUserList(headers, participantCode), new ArrayList<>())); + setKeycloakPassword(password, osOwner.get(0), keycloackParticipantRealm); + kafkaClient.send(messageTopic, EMAIL, eventGenerator.getEmailMessageEvent(passwordGenerate((String) registryDetails.get(PARTICIPANT_NAME), password, (String) registryDetails.get(PRIMARY_EMAIL)), passwordGenerateSub, Collections.singletonList((String) registryDetails.get(PRIMARY_EMAIL)), getUserList(headers, participantCode), new ArrayList<>())); return getSuccessResponse(); } @@ -1251,4 +1263,23 @@ private List getUserList(HttpHeaders headers, String participantCode) th return new ArrayList<>(); } } + + public Response generateAndSetUserSecret(Map requestBody) throws Exception { + String password = generateRandomPassword(24); + Map participant = getParticipant(PARTICIPANT_CODE, (String) requestBody.get(PARTICIPANT_CODE)); + String userName = String.format("%s:%s", requestBody.get(PARTICIPANT_CODE), requestBody.get(USER_ID)); + String selectQuery = String.format("SELECT * FROM %s WHERE username = '%s';", apiAccessTable, userName); + ResultSet resultSet = (ResultSet) postgreSQLClient.executeQuery(selectQuery); + if (resultSet.next()) { + String query = String.format("UPDATE %s SET secret_generation_date=%d,secret_expiry_date=%d WHERE username='%s';", apiAccessTable, System.currentTimeMillis(), System.currentTimeMillis() + (secretExpiry * 24 * 60 * 60 * 1000), userName); + postgreSQLClient.execute(query); + } + RealmResource realmResource = keycloak.realm(keycloakApiAccessRealm); + UsersResource usersResource = realmResource.users(); + List existingUsers = usersResource.search(userName); + String userId = existingUsers.get(0).getId(); + setKeycloakPassword(password, userId, keycloakApiAccessRealm); + kafkaClient.send(messageTopic, EMAIL, eventGenerator.getEmailMessageEvent(apiAccessSecret(userName, password, (String) participant.get(PARTICIPANT_CODE)), passwordGenerateSub, Arrays.asList((String) participant.get(PRIMARY_EMAIL)), new ArrayList<>(), new ArrayList<>())); + return getSuccessResponse(); + } } diff --git a/hcx-onboard/src/main/resources/application.yml b/hcx-onboard/src/main/resources/application.yml index 7cc3b7ac5..0fa1f315c 100644 --- a/hcx-onboard/src/main/resources/application.yml +++ b/hcx-onboard/src/main/resources/application.yml @@ -75,6 +75,7 @@ postgres: onboard-verification: ${onboard_verification_table:onboard_verification} onboard-verifier: ${onboard_verifier_table:onboard_verifier} onboard-user-invite: ${onboard_user_invite_table:onboard_user_invite_details} + api-access-secrets-expiry: ${api_access_secrets_expiry_table:api_access_secrets_expiry} mock-service: url: ${mock_service_db_url:jdbc:postgresql://localhost:5432/mock_service} table: @@ -99,6 +100,10 @@ keycloak: master-realm: ${keycloak_master_realm:master} client-id: ${keycloack_client_id:admin-cli} participant-realm: ${keycloack_users_realm:swasth-hcx-participants} + api-access-realm: ${keycloak_api_access_realm:api-access} endpoint: - user-invite: ${user_invite_endpoint:/onboarding/user/invite} \ No newline at end of file + user-invite: ${user_invite_endpoint:/onboarding/user/invite} + +secret: + expiry-time: ${secret_expiry_time:90} \ No newline at end of file diff --git a/hcx-onboard/src/main/resources/templates/api-access-secret.ftl b/hcx-onboard/src/main/resources/templates/api-access-secret.ftl new file mode 100644 index 000000000..64762f0a3 --- /dev/null +++ b/hcx-onboard/src/main/resources/templates/api-access-secret.ftl @@ -0,0 +1,15 @@ + + + +Hello,

+Password has been generated successfully for the ${USER_NAME}.

+Use below credentials for participant token generation: +
    +
  • username : ${USER_NAME}
  • +
  • secret : ${PASSWORD}
  • +
  • participant_code : ${PARTICIPANT_CODE}
  • +
+
Thanks,
+HCX Team + + \ No newline at end of file diff --git a/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/job/CommonSchedulerJob.java b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/job/CommonSchedulerJob.java index 84fa2a60e..c2f28c995 100644 --- a/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/job/CommonSchedulerJob.java +++ b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/job/CommonSchedulerJob.java @@ -8,6 +8,7 @@ import org.springframework.scheduling.annotation.EnableScheduling; import org.swasth.commonscheduler.schedulers.ParticipantValidationScheduler; import org.swasth.commonscheduler.schedulers.RetryScheduler; +import org.swasth.commonscheduler.schedulers.UserSecretScheduler; @SpringBootApplication(scanBasePackages={"org.swasth.commonscheduler"}) public class CommonSchedulerJob implements CommandLineRunner { @@ -17,6 +18,8 @@ public class CommonSchedulerJob implements CommandLineRunner { @Autowired RetryScheduler retryScheduler; + @Autowired + UserSecretScheduler userSecretScheduler; public static void main(String[] args) { SpringApplication.run(CommonSchedulerJob.class, args); } @@ -29,7 +32,11 @@ public void run(String... args) throws Exception { } else if (args.length > 0 && StringUtils.equalsIgnoreCase("Retry", args[0])) { retryScheduler.init(); retryScheduler.process(); - } else { + } else if (args.length > 0 && StringUtils.equalsIgnoreCase("UserSecret", args[0])){ + userSecretScheduler.init(); + userSecretScheduler.processExpirySecret(); + userSecretScheduler.processExpiredSecret(); + }else { System.out.println("No input to process the scheduler."); } diff --git a/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java new file mode 100644 index 000000000..518bb6a8f --- /dev/null +++ b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java @@ -0,0 +1,105 @@ +package org.swasth.commonscheduler.schedulers; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.swasth.common.utils.Constants; +import org.swasth.common.utils.JSONUtils; +import org.swasth.common.utils.NotificationUtils; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; +import java.util.Map; + +@Component +public class UserSecretScheduler extends BaseScheduler { + @Value("${postgres.table}") + private String postgresTable; + + @Value("${secret.expiry-days}") + private List secretExpiryDays; + + @Value("${kafka.topic.notification}") + private String notifyTopic; + + @Value("${topicCode.secret-expired}") + private String secretExpired; + + @Value("${topicCode.before-secret-expiry}") + private String beforeSecretExpiry; + + @Value("${notification.expiry}") + private int notificationExpiry; + + @Value("${hcx.participantCode}") + private String hcxParticipantCode; + + @Value("${hcx.privateKey}") + private String hcxPrivateKey; + + public void processExpiredSecret() throws Exception { + System.out.println("UserSecret expired batch job is started"); + String expiryMessage = ""; + List expiredParticipantCodes = new ArrayList<>(); + try (Connection connection = postgreSQLClient.getConnection(); + Statement createStatement = connection.createStatement()) { + String secretExpiredQuery = String.format("SELECT * FROM %s WHERE secret_expiry_date <= %d ;", postgresTable, System.currentTimeMillis()); + ResultSet result = postgreSQLClient.executeQuery(secretExpiredQuery); + while (result.next()) { + String participants = result.getString("username"); + expiredParticipantCodes.add(String.valueOf(participants)); + expiryMessage = getTemplateMessage(secretExpired); + System.out.println(expiryMessage); + } + generateEvent(expiredParticipantCodes, expiryMessage, secretExpired); + createStatement.executeBatch(); + System.out.println("Job is completed"); + } catch (Exception e) { + System.out.println("Error while processing event: " + e.getMessage()); + throw e; + } + } + + public void processExpirySecret() throws Exception { + System.out.println("UserSecret expiry batch job is started"); + String beforeExpiryMessage = ""; + List aboutToExpireParticipantCodes = new ArrayList<>(); + try (Connection connection = postgreSQLClient.getConnection(); + Statement createStatement = connection.createStatement()) { + for (int beforeExpiryDay : secretExpiryDays) { + long expiryTime = System.currentTimeMillis() + (1 + beforeExpiryDay) * 24L * 60 * 60 * 1000; + long earlierDayTime = expiryTime - (24L * 60 * 60 * 1000); + String query = String.format("SELECT * FROM %s WHERE secret_expiry_date > %d AND secret_expiry_date < %d;", postgresTable, earlierDayTime, expiryTime); + ResultSet resultSet = postgreSQLClient.executeQuery(query); + while (resultSet.next()) { + String participants = resultSet.getString("username"); + aboutToExpireParticipantCodes.add(String.valueOf(participants)); + beforeExpiryMessage = getTemplateMessage(beforeSecretExpiry).replace("${days}", String.valueOf(beforeExpiryDay)); + } + generateEvent(aboutToExpireParticipantCodes, beforeExpiryMessage, beforeSecretExpiry); + aboutToExpireParticipantCodes.clear(); + } + createStatement.executeBatch(); + System.out.println("Job is completed"); + } catch (Exception e) { + System.out.println("Error while processing event: " + e.getMessage()); + throw e; + } + } + + private void generateEvent(List participantCodes, String message, String topiCode) throws Exception { + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.MILLISECOND, notificationExpiry); + String event = eventGenerator.createNotifyEvent(topiCode, hcxParticipantCode, Constants.PARTICIPANT_CODE, participantCodes, cal.getTime().toInstant().toEpochMilli(), message, hcxPrivateKey); + kafkaClient.send(notifyTopic, Constants.NOTIFICATION, event); + System.out.println("Event is pushed to kafka topic " + " :: event: " + event); + } + + private String getTemplateMessage(String topicCode) throws Exception { + return (String) JSONUtils.deserialize((String) (NotificationUtils.getNotification(topicCode).get(Constants.TEMPLATE)), Map.class).get(Constants.MESSAGE); + } +} diff --git a/hcx-scheduler-jobs/common-scheduler-job/src/main/resources/application.yml b/hcx-scheduler-jobs/common-scheduler-job/src/main/resources/application.yml index 716025b8e..18b31cfc1 100644 --- a/hcx-scheduler-jobs/common-scheduler-job/src/main/resources/application.yml +++ b/hcx-scheduler-jobs/common-scheduler-job/src/main/resources/application.yml @@ -24,6 +24,8 @@ topicCode: before-encryption-cert-expiry: ${before_encryption_cert_expiry_topic_code:notif-encryption-key-expiry} signing-cert-expired: ${signing_cert_expired_topic_code:notif-signing-cert-expired} before-signing-cert-expiry: ${before_signing_cert_expiry_topic_code:notif-signing-key-expiry} + secret-expired: ${secret_expired:notif-secret-expired} + before-secret-expiry: ${before_secret_expiry:notif-secret-expiry} #postgres config postgres: @@ -31,6 +33,7 @@ postgres: user: ${postgres_user:postgres} password: ${postgres_password:postgres} tablename: ${postgres_tablename:payload} + table: ${postgres_table:api_access_secrets_expiry} #hcx error headers plainrequest: @@ -61,3 +64,6 @@ notification: certificate: expiry-days: ${certificate_expiry_days:5,10,15} + +secret: + expiry-days: ${certificate_expiry_days:5,10,15} \ No newline at end of file From d541df4f01f3d7732dc9b81da3da07d4720a4a86 Mon Sep 17 00:00:00 2001 From: KrutikaPhirangi Date: Tue, 10 Oct 2023 18:47:30 +0530 Subject: [PATCH 08/59] Update --- .../job/CommonSchedulerJob.java | 3 +-- .../schedulers/UserSecretScheduler.java | 24 ++++++++++++------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/job/CommonSchedulerJob.java b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/job/CommonSchedulerJob.java index c2f28c995..093a66cb8 100644 --- a/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/job/CommonSchedulerJob.java +++ b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/job/CommonSchedulerJob.java @@ -34,8 +34,7 @@ public void run(String... args) throws Exception { retryScheduler.process(); } else if (args.length > 0 && StringUtils.equalsIgnoreCase("UserSecret", args[0])){ userSecretScheduler.init(); - userSecretScheduler.processExpirySecret(); - userSecretScheduler.processExpiredSecret(); + userSecretScheduler.process(); }else { System.out.println("No input to process the scheduler."); } diff --git a/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java index 518bb6a8f..5b4d31a52 100644 --- a/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java +++ b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java @@ -1,7 +1,8 @@ package org.swasth.commonscheduler.schedulers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; -import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.swasth.common.utils.Constants; import org.swasth.common.utils.JSONUtils; @@ -17,6 +18,7 @@ @Component public class UserSecretScheduler extends BaseScheduler { + private final Logger logger = LoggerFactory.getLogger(UserSecretScheduler.class); @Value("${postgres.table}") private String postgresTable; @@ -40,9 +42,14 @@ public class UserSecretScheduler extends BaseScheduler { @Value("${hcx.privateKey}") private String hcxPrivateKey; + public void process() throws Exception { + logger.info("User secret job started"); + processExpiredSecret(); + processExpirySecret(); + } public void processExpiredSecret() throws Exception { - System.out.println("UserSecret expired batch job is started"); + logger.info("User secret expired batch job started"); String expiryMessage = ""; List expiredParticipantCodes = new ArrayList<>(); try (Connection connection = postgreSQLClient.getConnection(); @@ -53,19 +60,18 @@ public void processExpiredSecret() throws Exception { String participants = result.getString("username"); expiredParticipantCodes.add(String.valueOf(participants)); expiryMessage = getTemplateMessage(secretExpired); - System.out.println(expiryMessage); } generateEvent(expiredParticipantCodes, expiryMessage, secretExpired); createStatement.executeBatch(); - System.out.println("Job is completed"); + logger.info("Job is completed"); } catch (Exception e) { - System.out.println("Error while processing event: " + e.getMessage()); + logger.info("Error while processing event: " + e.getMessage()); throw e; } } public void processExpirySecret() throws Exception { - System.out.println("UserSecret expiry batch job is started"); + logger.info("User secret expiry batch job started"); String beforeExpiryMessage = ""; List aboutToExpireParticipantCodes = new ArrayList<>(); try (Connection connection = postgreSQLClient.getConnection(); @@ -84,9 +90,9 @@ public void processExpirySecret() throws Exception { aboutToExpireParticipantCodes.clear(); } createStatement.executeBatch(); - System.out.println("Job is completed"); + logger.info("Job is completed"); } catch (Exception e) { - System.out.println("Error while processing event: " + e.getMessage()); + logger.info("Error while processing event: " + e.getMessage()); throw e; } } @@ -96,7 +102,7 @@ private void generateEvent(List participantCodes, String message, String cal.add(Calendar.MILLISECOND, notificationExpiry); String event = eventGenerator.createNotifyEvent(topiCode, hcxParticipantCode, Constants.PARTICIPANT_CODE, participantCodes, cal.getTime().toInstant().toEpochMilli(), message, hcxPrivateKey); kafkaClient.send(notifyTopic, Constants.NOTIFICATION, event); - System.out.println("Event is pushed to kafka topic " + " :: event: " + event); + logger.info("Event is pushed to kafka topic " + " :: event: " + event); } private String getTemplateMessage(String topicCode) throws Exception { From 2feae1e1f9b8728f7ca44a4bc58e0275af5468da Mon Sep 17 00:00:00 2001 From: KrutikaPhirangi Date: Tue, 10 Oct 2023 19:10:28 +0530 Subject: [PATCH 09/59] Update --- .../java/org/swasth/hcx/controllers/v1/JWTControllerTests.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hcx-apis/src/test/java/org/swasth/hcx/controllers/v1/JWTControllerTests.java b/hcx-apis/src/test/java/org/swasth/hcx/controllers/v1/JWTControllerTests.java index c636fcaad..25e1cdb6a 100644 --- a/hcx-apis/src/test/java/org/swasth/hcx/controllers/v1/JWTControllerTests.java +++ b/hcx-apis/src/test/java/org/swasth/hcx/controllers/v1/JWTControllerTests.java @@ -97,7 +97,7 @@ void api_access_token_generate_success() throws Exception { MvcResult mvcResult = mockMvc.perform(post(Constants.VERSION_PREFIX + Constants.PARTICIPANT_GENERATE_TOKEN) .header("Content-Type", "application/x-www-form-urlencoded") .param("username","hcxtest6034@yopmail.com") - .param("secret","Test@123") + .param("secret","Test@1234") .param("participant_code", "hcxtest6034.yopmail@swasth-hcx-dev")) .andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); From 6b824d8836cfd01aa49736cfea3ba2492df2cdde Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Tue, 10 Oct 2023 23:37:06 +0530 Subject: [PATCH 10/59] feat : provider specific test cases --- .../swasth/apigateway/models/BaseRequest.java | 9 ++-- .../java/org/swasth/apigateway/BaseSpec.java | 3 ++ .../apigateway/filters/HCXRequestTest.java | 21 ++++++++++ .../controllers/v1/ParticipantController.java | 9 ++-- .../org/swasth/hcx/models/Participant.java | 17 ++++---- hcx-apis/src/main/resources/application.yml | 5 +-- .../swasth/hcx/models/ParticipantTests.java | 41 ++++++++++++++++--- .../org/swasth/common/utils/Constants.java | 1 + 8 files changed, 78 insertions(+), 28 deletions(-) diff --git a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java index f977428bc..5ca1f8ea0 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java @@ -35,9 +35,6 @@ public class BaseRequest { private String hcxRoles; private String hcxCode; - @Value("${provider-specific.roles}") - private List providerSpecificRoles; - public BaseRequest() { } @@ -189,7 +186,7 @@ public void validateUsingAuditData(List allowedEntitiesForForward, List< for (Map audit : correlationAuditData) { String action = (String) audit.get(ACTION); String entity = getEntity(action); - validateCondition(!OPERATIONAL_ENTITIES.contains(entity) && action.contains("on_") && ((List) audit.get(RECIPIENT_ROLE)).contains(PROVIDER) && ((List) audit.get(RECIPIENT_ROLE)).stream().anyMatch(providerSpecificRoles::contains) && audit.get(STATUS).equals(COMPLETE_STATUS), ErrorCodes.ERR_INVALID_CORRELATION_ID, CLOSED_CYCLE_MSG); + validateCondition(!OPERATIONAL_ENTITIES.contains(entity) && action.contains("on_") && (((List) audit.get(RECIPIENT_ROLE)).contains(PROVIDER)) && ((List) audit.get(RECIPIENT_ROLE)).stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains) && audit.get(STATUS).equals(COMPLETE_STATUS), ErrorCodes.ERR_INVALID_CORRELATION_ID, CLOSED_CYCLE_MSG); } String actionEntity = getEntity(jweRequest.getApiAction()); if (!OPERATIONAL_ENTITIES.contains(actionEntity)) { @@ -217,11 +214,11 @@ public void validateUsingAuditData(List allowedEntitiesForForward, List< validateCondition(getHcxRecipientCode().equals(audit.get(HCX_SENDER_CODE)), ErrorCodes.ERR_INVALID_FORWARD_REQ, FORWARD_REQ_ERR_MSG); } } - } else if (!EXCLUDE_ENTITIES.contains(getEntity(path)) && !apiAction.contains("on_") && checkParticipantRole(allowedRolesForForward, senderRoles) && recipientRoles.contains(PROVIDER) && recipientRoles.stream().anyMatch(providerSpecificRoles::contains)) { + } else if (!EXCLUDE_ENTITIES.contains(getEntity(path)) && !apiAction.contains("on_") && checkParticipantRole(allowedRolesForForward, senderRoles) && recipientRoles.contains(PROVIDER) && recipientRoles.stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)) { throw new ClientException(ErrorCodes.ERR_ACCESS_DENIED, INVALID_API_CALL); } // validation to check if participant is forwarding the request to provider - if (isForwardReq && !apiAction.contains("on_") && recipientRoles.contains(PROVIDER) && recipientRoles.stream().anyMatch(providerSpecificRoles::contains)) { + if (isForwardReq && !apiAction.contains("on_") && recipientRoles.contains(PROVIDER) && recipientRoles.stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)) { throw new ClientException(ErrorCodes.ERR_INVALID_FORWARD_REQ, INVALID_FORWARD_TO_PROVIDER); } } diff --git a/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java b/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java index 06e6a2f03..6fa0eec26 100644 --- a/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java +++ b/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java @@ -238,6 +238,9 @@ protected List> getAuditLogs() throws Exception { return Arrays.asList(JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"request.queued\",\"recipientRole\":[\"payor\"],\"x-hcx-timestamp\":\"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5093\",\"senderRole\":[\"provider\"]}", Map.class)); } + protected List> getAuditHospitalLogs() throws Exception { + return Arrays.asList(JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"request.queued\",\"recipientRole\":[\"payor\"],\"x-hcx-timestamp\":\"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5093\",\"senderRole\":[\"provider\"]}", Map.class)); + } protected List> getCorrelationIdAuditLogs() throws Exception { Map auditMap1 = JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"request.queued\",\"recipientRole\":[\"payor\"],\"x-hcx-timestamp\": \"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"2c364696-019f-4902-83c9-2a8764559c34\",\"senderRole\":[\"provider\"]}", Map.class); Map auditMap2 = JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"response.complete\",\"recipientRole\":[\"payor\"],\"x-hcx-timestamp\": \"2023-06-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"2c364696-019f-4902-83c9-2a8764559c34\",\"senderRole\":[\"provider\"]}", Map.class); diff --git a/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java b/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java index 1e0ae4342..f3c677a89 100644 --- a/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java +++ b/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java @@ -137,6 +137,27 @@ void check_hcx_request_reuse_correlation_id_scenario_after_complete_status_and_t .expectBody(Map.class) .consumeWith(result -> assertEquals(HttpStatus.ACCEPTED, result.getStatus())); } + + @Test + void check_hcx_request_cycle_closed() throws Exception { + server.enqueue(new MockResponse() + .setResponseCode(202) + .addHeader("Content-Type", "application/json")); + Mockito.when(registryService.fetchDetails(anyString(), anyString())) + .thenReturn(getPayorDetails()) + .thenReturn(getProviderDetails()); + Mockito.when(auditService.getAuditLogs(any())) + .thenReturn(getAuditHospitalLogs()) + .thenReturn(getAuditHospitalLogs()) + .thenReturn(new ArrayList<>()); + client.post().uri(versionPrefix + Constants.COVERAGE_ELIGIBILITY_ONCHECK) + .header(Constants.AUTHORIZATION, getPayorToken()) + .header("X-jwt-sub", "20bd4228-a87f-4175-a30a-20fb28983afb") + .bodyValue(getOnRequestBody()) + .exchange() + .expectBody(Map.class) + .consumeWith(result -> assertEquals(HttpStatus.ACCEPTED, result.getStatus())); + } @Test void check_hcx_request_parse_timestamp_exception() throws Exception { diff --git a/hcx-apis/src/main/java/org/swasth/hcx/controllers/v1/ParticipantController.java b/hcx-apis/src/main/java/org/swasth/hcx/controllers/v1/ParticipantController.java index 2f9c09f46..ffd6989e7 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/controllers/v1/ParticipantController.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/controllers/v1/ParticipantController.java @@ -44,9 +44,6 @@ public class ParticipantController extends BaseController { @Value("${postgres.onboardingOtpTable}") private String onboardOtpTable; - - @Value("${provider-specific.roles}") - private List providerSpecificRoles; @Autowired private ParticipantService service; @@ -54,7 +51,7 @@ public class ParticipantController extends BaseController { public ResponseEntity create(@RequestHeader HttpHeaders header, @RequestBody Map requestBody) { try { logger.info("Creating participant: {}", requestBody.get(PARTICIPANT_NAME)); - Participant participant = new Participant(requestBody, providerSpecificRoles); + Participant participant = new Participant(requestBody); service.validate(requestBody, true); requestBody.put(PRIMARY_EMAIL, participant.getprimaryEmail().toLowerCase()); String code = participant.generateCode(fieldSeparator, hcxInstanceName); @@ -70,7 +67,7 @@ public ResponseEntity create(@RequestHeader HttpHeaders header, @Request public ResponseEntity update(@RequestHeader HttpHeaders header, @RequestBody Map requestBody) { try { logger.info("Updating participant: {}", requestBody.get(PARTICIPANT_CODE)); - Participant participant = new Participant(requestBody, providerSpecificRoles); + Participant participant = new Participant(requestBody); String code = participant.getParticipantCode(); service.getCertificatesUrl(requestBody, code); service.validate(requestBody, false); @@ -108,7 +105,7 @@ public ResponseEntity delete(@RequestHeader HttpHeaders header, @Request logger.info("Deleting participant: {}", requestBody.get(PARTICIPANT_CODE)); if (!requestBody.containsKey(PARTICIPANT_CODE)) throw new ClientException(ErrorCodes.ERR_INVALID_PARTICIPANT_CODE, PARTICIPANT_CODE_MSG); - Participant participant = new Participant(requestBody, providerSpecificRoles); + Participant participant = new Participant(requestBody); Map details = service.getParticipant(participant.getParticipantCode()); return getSuccessResponse(service.delete(details, header, participant.getParticipantCode())); } catch (Exception e) { diff --git a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java index 6623606ca..a4c0038c3 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java @@ -12,11 +12,9 @@ public class Participant { private final Map requestBody; - private final List providerSpecificRoles; - public Participant(Map requestbody, List providerSpecificRoles) { + public Participant(Map requestbody) { this.requestBody = requestbody; - this.providerSpecificRoles = providerSpecificRoles; } public String getprimaryEmail() { @@ -43,13 +41,18 @@ public String generateCode(String fieldSeparator, String hcxInstanceName) { } private String getRoleAppender() { - if (getRoles().contains(PROVIDER) || getRoles().stream().anyMatch(providerSpecificRoles::contains)) { + if (getRoles().contains("provider")) { return "hosp"; - } else if (getRoles().contains(PAYOR)) { + } else if (getRoles().stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)) { + for (String role : getRoles()) { + if (role.startsWith("provider.")) { + return role.substring(9, Math.min(role.length(), 13)); + } + } + } else if (getRoles().contains("payor")) { return "payr"; - } else { - return getRoles().get(0); } + return getRoles().isEmpty() ? "" : getRoles().get(0); } private String getRandomSeq(){ diff --git a/hcx-apis/src/main/resources/application.yml b/hcx-apis/src/main/resources/application.yml index c7205bb6b..6d978e5dc 100644 --- a/hcx-apis/src/main/resources/application.yml +++ b/hcx-apis/src/main/resources/application.yml @@ -151,7 +151,4 @@ email: id: ${email_id:} pwd: ${email_pwd:} user-token-subject: ${token_generate_subject:HCX - Protocol APIs Access Token Generation credentials} - user-token-message: ${user_token_message:Hi NAME,

Along with participant username and password, api access token can be generated using the following credentials.
  • user_name - USER_ID
  • secret - PASSWORD
  • participant_code - PARTICIPANT_CODE
This API Access token can be used to make protocol API requests. Please refer to the instructions provided in the link to generate access token.

If you have any queries, Please reach out HCX team.

Thanks and Regards
HCX Team.} - -provider-specific: - roles: ${provider_specific_roles:provider.hospital,provider.clinic,provider.practitioner,provider.diagnostics,provider.pharmacy} \ No newline at end of file + user-token-message: ${user_token_message:Hi NAME,

Along with participant username and password, api access token can be generated using the following credentials.
  • user_name - USER_ID
  • secret - PASSWORD
  • participant_code - PARTICIPANT_CODE
This API Access token can be used to make protocol API requests. Please refer to the instructions provided in the link to generate access token.

If you have any queries, Please reach out HCX team.

Thanks and Regards
HCX Team.} \ No newline at end of file diff --git a/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java b/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java index 239b60fad..e51218549 100644 --- a/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java +++ b/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java @@ -11,21 +11,23 @@ public class ParticipantTests { @Test void generate_participant_code_with_payor_role() { - Participant participant = new Participant(getPayorRequestBody(),getSpecificProviderRoles()); + Participant participant = new Participant(getPayorRequestBody()); String code = participant.generateCode("_", "swasth-hcx"); Assertions.assertTrue(code.contains("payr_rakshi")); } @Test void generate_participant_code_with_provider_role() { - Participant participant = new Participant(getProviderRequestBody(), getSpecificProviderRoles()); + Participant participant = new Participant(getProviderRequestBody()); String code = participant.generateCode("_", "swasth-hcx"); Assertions.assertEquals("hosp_rakshi_012345@swasth-hcx", code); } - private List getSpecificProviderRoles() { - return List.of("provider.hospital", "provider.clinic", "provider.practitioner", - "provider.diagnostics", "provider.pharmacy"); + @Test + void generate_specific_provider_roles(){ + Participant participant = new Participant(getProviderSpecificRequestBody()); + String code = participant.generateCode("_", "swasth-hcx"); + Assertions.assertEquals("hosp_rakshi_012345@swasth-hcx", code); } private Map getPayorRequestBody() { @@ -85,4 +87,33 @@ private Map getProviderRequestBody() { obj.put("encryption_cert", "urn:isbn:0-4234"); return obj; } + + private Map getProviderSpecificRequestBody() { + Map obj = new HashMap<>(); + obj.put("participant_name", "Rakshith Hospital"); + obj.put("primary_mobile", "9493347239"); + obj.put("primary_email", "rakshith123@gmail.com"); + obj.put("roles", new ArrayList<>(Collections.singleton("provider.hospital"))); + obj.put("applicant_code", "012345"); + obj.put("address", new HashMap<>() {{ + put("plot", "5-4-199"); + put("street", "road no 12"); + put("landmark", ""); + put("village", "Nampally"); + put("district", "Hyd"); + put("state", "Telangana"); + put("pincode", "500805"); + }}); + obj.put("phone", new ArrayList<>(Collections.singleton("040-387658992"))); + obj.put("status", "Created"); + obj.put("endpoint_url", "http://localhost:8095"); + obj.put("payment_details", new HashMap<>() {{ + put("account_number", "4707890099809809"); + put("ifsc_code", "ICICLE"); + }}); + obj.put("signing_cert_path", "urn:isbn:0-476-27557-4"); + obj.put("linked_registry_codes", new ArrayList<>(Collections.singleton("22344"))); + obj.put("encryption_cert", "urn:isbn:0-4234"); + return obj; + } } diff --git a/hcx-core/hcx-common/src/main/java/org/swasth/common/utils/Constants.java b/hcx-core/hcx-common/src/main/java/org/swasth/common/utils/Constants.java index 0177a3dca..b2a5d9f0f 100644 --- a/hcx-core/hcx-common/src/main/java/org/swasth/common/utils/Constants.java +++ b/hcx-core/hcx-common/src/main/java/org/swasth/common/utils/Constants.java @@ -148,6 +148,7 @@ public class Constants { public static final String AUDIT_TIMESTAMP = "auditTimeStamp"; public static final String UPDATED_TIME = "updatedTimestamp"; public static final String REQUEST_TIME = "requestTimeStamp"; + public static final List PROVIDER_SPECIFIC_ROLES = Arrays.asList("provider.hospital", "provider.clinic", "provider.practitioner", "provider.diagnostics", "provider.pharmacy"); public static final String OBJECT = "object"; public static final String CDATA = "cdata"; public static final String EDATA = "edata"; From bdc17e373ca7067fdd5a2bcfb6f87b93bc1bf8f1 Mon Sep 17 00:00:00 2001 From: KrutikaPhirangi Date: Wed, 11 Oct 2023 10:39:39 +0530 Subject: [PATCH 11/59] Update --- .../java/org/swasth/hcx/controllers/v1/JWTControllerTests.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hcx-apis/src/test/java/org/swasth/hcx/controllers/v1/JWTControllerTests.java b/hcx-apis/src/test/java/org/swasth/hcx/controllers/v1/JWTControllerTests.java index 25e1cdb6a..c636fcaad 100644 --- a/hcx-apis/src/test/java/org/swasth/hcx/controllers/v1/JWTControllerTests.java +++ b/hcx-apis/src/test/java/org/swasth/hcx/controllers/v1/JWTControllerTests.java @@ -97,7 +97,7 @@ void api_access_token_generate_success() throws Exception { MvcResult mvcResult = mockMvc.perform(post(Constants.VERSION_PREFIX + Constants.PARTICIPANT_GENERATE_TOKEN) .header("Content-Type", "application/x-www-form-urlencoded") .param("username","hcxtest6034@yopmail.com") - .param("secret","Test@1234") + .param("secret","Test@123") .param("participant_code", "hcxtest6034.yopmail@swasth-hcx-dev")) .andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); From 8ed9273b3c5c9edbc46cb9249133b3743098a807 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Wed, 11 Oct 2023 10:40:19 +0530 Subject: [PATCH 12/59] feat : testcase --- .../swasth/hcx/models/ParticipantTests.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java b/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java index e51218549..07ab0b6f5 100644 --- a/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java +++ b/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java @@ -29,6 +29,12 @@ void generate_specific_provider_roles(){ String code = participant.generateCode("_", "swasth-hcx"); Assertions.assertEquals("hosp_rakshi_012345@swasth-hcx", code); } + @Test + void generate_hcx_admin_code(){ + Participant participant = new Participant(getHCXAdminRequestBody()); + String code = participant.generateCode("_", "swasth-hcx"); + Assertions.assertEquals("hie/hio.hcx_rakshi_012345@swasth-hcx",code); + } private Map getPayorRequestBody() { Map obj = new HashMap<>(); @@ -116,4 +122,33 @@ private Map getProviderSpecificRequestBody() { obj.put("encryption_cert", "urn:isbn:0-4234"); return obj; } + + private Map getHCXAdminRequestBody() { + Map obj = new HashMap<>(); + obj.put("participant_name", "Rakshith Hospital"); + obj.put("primary_mobile", "9493347239"); + obj.put("primary_email", "rakshith123@gmail.com"); + obj.put("roles", new ArrayList<>(Collections.singleton("HIE/HIO.HCX"))); + obj.put("applicant_code", "012345"); + obj.put("address", new HashMap<>() {{ + put("plot", "5-4-199"); + put("street", "road no 12"); + put("landmark", ""); + put("village", "Nampally"); + put("district", "Hyd"); + put("state", "Telangana"); + put("pincode", "500805"); + }}); + obj.put("phone", new ArrayList<>(Collections.singleton("040-387658992"))); + obj.put("status", "Created"); + obj.put("endpoint_url", "http://localhost:8095"); + obj.put("payment_details", new HashMap<>() {{ + put("account_number", "4707890099809809"); + put("ifsc_code", "ICICLE"); + }}); + obj.put("signing_cert_path", "urn:isbn:0-476-27557-4"); + obj.put("linked_registry_codes", new ArrayList<>(Collections.singleton("22344"))); + obj.put("encryption_cert", "urn:isbn:0-4234"); + return obj; + } } From 08fec3426a63215efaec711230b3213739772969 Mon Sep 17 00:00:00 2001 From: KrutikaPhirangi Date: Wed, 11 Oct 2023 13:31:30 +0530 Subject: [PATCH 13/59] TestCases --- .../schedulers/UserSecretScheduler.java | 3 -- .../schedulers/CommonSchedulerTest.java | 36 ++++++++++++++++++- 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java index 5b4d31a52..9fbfdbbe4 100644 --- a/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java +++ b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java @@ -65,7 +65,6 @@ public void processExpiredSecret() throws Exception { createStatement.executeBatch(); logger.info("Job is completed"); } catch (Exception e) { - logger.info("Error while processing event: " + e.getMessage()); throw e; } } @@ -92,7 +91,6 @@ public void processExpirySecret() throws Exception { createStatement.executeBatch(); logger.info("Job is completed"); } catch (Exception e) { - logger.info("Error while processing event: " + e.getMessage()); throw e; } } @@ -102,7 +100,6 @@ private void generateEvent(List participantCodes, String message, String cal.add(Calendar.MILLISECOND, notificationExpiry); String event = eventGenerator.createNotifyEvent(topiCode, hcxParticipantCode, Constants.PARTICIPANT_CODE, participantCodes, cal.getTime().toInstant().toEpochMilli(), message, hcxPrivateKey); kafkaClient.send(notifyTopic, Constants.NOTIFICATION, event); - logger.info("Event is pushed to kafka topic " + " :: event: " + event); } private String getTemplateMessage(String topicCode) throws Exception { diff --git a/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java b/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java index 998a80067..d607272e8 100644 --- a/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java +++ b/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java @@ -3,6 +3,7 @@ import io.zonky.test.db.postgres.embedded.EmbeddedPostgres; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; +import org.junit.Assert; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -12,11 +13,13 @@ import org.mockito.MockitoAnnotations; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.kafka.test.context.EmbeddedKafka; import org.springframework.test.context.ActiveProfiles; +import org.swasth.common.exception.ClientException; import org.swasth.common.helpers.EventGenerator; import org.swasth.common.service.RegistryService; import org.swasth.common.utils.Constants; @@ -36,7 +39,7 @@ import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) -@SpringBootTest(classes ={ ParticipantValidationScheduler.class, CommonSchedulerJob.class, BaseScheduler.class}) +@SpringBootTest(classes ={ ParticipantValidationScheduler.class, CommonSchedulerJob.class, BaseScheduler.class, UserSecretScheduler.class}) @Import(GenericConfiguration.class) @ActiveProfiles("test") @EmbeddedKafka( @@ -55,6 +58,8 @@ public class CommonSchedulerTest { private EventGenerator eventGenerator; @Mock private RetryScheduler retryScheduler; + @Mock + private UserSecretScheduler userSecretScheduler; @MockBean private RegistryService registryService; @MockBean @@ -73,6 +78,9 @@ void setup() throws Exception { retryScheduler.postgreSQLClient = postgreSQLClient; retryScheduler.eventGenerator = eventGenerator; retryScheduler.kafkaClient = kafkaClient; + userSecretScheduler.postgreSQLClient = postgreSQLClient; + userSecretScheduler.eventGenerator = eventGenerator; + userSecretScheduler.kafkaClient = kafkaClient; } @AfterEach void teardown() throws IOException, InterruptedException { @@ -135,5 +143,31 @@ public void testRetryRequestsScheduler() throws Exception { } else throw new Exception("The test case failed."); } + @Test + public void testUserSecretExpired() throws Exception { + postgreSQLClient.execute("CREATE TABLE api_access_secrets_expiry(user_id character varying, participant_code character varying, secret_generation_date bigint, secret_expiry_date bigint, username character varying NOT NULL)"); + postgreSQLClient.execute("INSERT INTO api_access_secrets_expiry(user_id, participant_code, secret_generation_date, secret_expiry_date, username) VALUES('mock15@gmail.com', 'hcxtest1051.yopmail@swasth-hcx-dev', '1696839989628', '1696833349003', 'hcxtest1051.yopmail@swasth-hcx-dev:mock15@gmail.com');"); + when(eventGenerator.generateMetadataEvent(any())).thenReturn("mockedEvent"); + lenient().doNothing().when(kafkaClient).send(anyString(), anyString(), anyString()); + String[] args = {"UserSecret"}; + commonSchedulerJob.run(args); + userSecretScheduler.processExpiredSecret(); + String query = String.format("SELECT * FROM api_access_secrets_expiry WHERE secret_expiry_date <= %d ;",System.currentTimeMillis()); + ResultSet result = postgreSQLClient.executeQuery(query); + while (result.next()) { + String participant = result.getString("username"); + Assert.assertEquals("hcxtest1051.yopmail@swasth-hcx-dev:mock15@gmail.com", participant); + } + } + + @Test + public void testUserSecretAboutTpExpire() throws Exception { + postgreSQLClient.execute("CREATE TABLE api_access_secrets_expiry(user_id character varying, participant_code character varying, secret_generation_date bigint, secret_expiry_date bigint, username character varying NOT NULL)"); + postgreSQLClient.execute("INSERT INTO api_access_secrets_expiry(user_id, participant_code, secret_generation_date, secret_expiry_date, username) VALUES('mock18@gmail.com', 'hcxtest6.yopmail@swasth-hcx', '1696839989628', '1697528269086', 'hcxtest6.yopmail@swasth-hcx:mock18@gmail.com');"); + when(eventGenerator.generateMetadataEvent(any())).thenReturn("mockedEvent"); + lenient().doNothing().when(kafkaClient).send(anyString(), anyString(), anyString()); + String[] args = {"UserSecret"}; + commonSchedulerJob.run(args); + } } From 5b353286df7aacfb059f92d6f1b6f66dd580011b Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Wed, 11 Oct 2023 15:18:36 +0530 Subject: [PATCH 14/59] feat : testcases in api-gateway --- .../java/org/swasth/apigateway/models/BaseRequest.java | 2 +- .../src/test/java/org/swasth/apigateway/BaseSpec.java | 8 ++++++-- .../org/swasth/apigateway/filters/HCXRequestTest.java | 8 ++++---- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java index 5ca1f8ea0..67bf3f7ac 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java @@ -186,7 +186,7 @@ public void validateUsingAuditData(List allowedEntitiesForForward, List< for (Map audit : correlationAuditData) { String action = (String) audit.get(ACTION); String entity = getEntity(action); - validateCondition(!OPERATIONAL_ENTITIES.contains(entity) && action.contains("on_") && (((List) audit.get(RECIPIENT_ROLE)).contains(PROVIDER)) && ((List) audit.get(RECIPIENT_ROLE)).stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains) && audit.get(STATUS).equals(COMPLETE_STATUS), ErrorCodes.ERR_INVALID_CORRELATION_ID, CLOSED_CYCLE_MSG); + validateCondition(!OPERATIONAL_ENTITIES.contains(entity) && action.contains("on_") && (((List) audit.get(RECIPIENT_ROLE)).contains(PROVIDER)) || ((List) audit.get(RECIPIENT_ROLE)).stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains) && audit.get(STATUS).equals(COMPLETE_STATUS), ErrorCodes.ERR_INVALID_CORRELATION_ID, CLOSED_CYCLE_MSG); } String actionEntity = getEntity(jweRequest.getApiAction()); if (!OPERATIONAL_ENTITIES.contains(actionEntity)) { diff --git a/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java b/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java index 6fa0eec26..e39eb4d4b 100644 --- a/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java +++ b/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java @@ -238,8 +238,12 @@ protected List> getAuditLogs() throws Exception { return Arrays.asList(JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"request.queued\",\"recipientRole\":[\"payor\"],\"x-hcx-timestamp\":\"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5093\",\"senderRole\":[\"provider\"]}", Map.class)); } - protected List> getAuditHospitalLogs() throws Exception { - return Arrays.asList(JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"request.queued\",\"recipientRole\":[\"payor\"],\"x-hcx-timestamp\":\"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5093\",\"senderRole\":[\"provider\"]}", Map.class)); + protected List> getAuditProviderLogs() throws Exception { + return Arrays.asList(JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"request.complete\",\"recipientRole\":[\"provider\"],\"x-hcx-timestamp\":\"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/on_check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5093\",\"senderRole\":[\"provider\"]}", Map.class)); + } + + protected List> getAuditProviderSpecificRolesLogs() throws Exception { + return Arrays.asList(JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"request.complete\",\"recipientRole\":[\"provider.hospital\"],\"x-hcx-timestamp\":\"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/on_check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5093\",\"senderRole\":[\"provider\"]}", Map.class)); } protected List> getCorrelationIdAuditLogs() throws Exception { Map auditMap1 = JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"request.queued\",\"recipientRole\":[\"payor\"],\"x-hcx-timestamp\": \"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"2c364696-019f-4902-83c9-2a8764559c34\",\"senderRole\":[\"provider\"]}", Map.class); diff --git a/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java b/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java index f3c677a89..7fcda3cea 100644 --- a/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java +++ b/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java @@ -139,7 +139,7 @@ void check_hcx_request_reuse_correlation_id_scenario_after_complete_status_and_t } @Test - void check_hcx_request_cycle_closed() throws Exception { + void check_hcx_request_cycle_closed_for_provider_role() throws Exception { server.enqueue(new MockResponse() .setResponseCode(202) .addHeader("Content-Type", "application/json")); @@ -147,8 +147,8 @@ void check_hcx_request_cycle_closed() throws Exception { .thenReturn(getPayorDetails()) .thenReturn(getProviderDetails()); Mockito.when(auditService.getAuditLogs(any())) - .thenReturn(getAuditHospitalLogs()) - .thenReturn(getAuditHospitalLogs()) + .thenReturn(getAuditProviderLogs()) + .thenReturn(getAuditProviderLogs()) .thenReturn(new ArrayList<>()); client.post().uri(versionPrefix + Constants.COVERAGE_ELIGIBILITY_ONCHECK) .header(Constants.AUTHORIZATION, getPayorToken()) @@ -156,7 +156,7 @@ void check_hcx_request_cycle_closed() throws Exception { .bodyValue(getOnRequestBody()) .exchange() .expectBody(Map.class) - .consumeWith(result -> assertEquals(HttpStatus.ACCEPTED, result.getStatus())); + .consumeWith(result -> assertEquals(HttpStatus.BAD_REQUEST, result.getStatus())); } @Test From 4bde8d51a975d430d8231e736a5ba434b63cecb9 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Wed, 11 Oct 2023 16:38:55 +0530 Subject: [PATCH 15/59] feat : added testcases --- .../swasth/apigateway/models/BaseRequest.java | 4 ++-- .../java/org/swasth/apigateway/BaseSpec.java | 8 +++++++ .../apigateway/filters/HCXRequestTest.java | 21 ++++++++++++++++++- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java index 67bf3f7ac..f023fc702 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java @@ -214,11 +214,11 @@ public void validateUsingAuditData(List allowedEntitiesForForward, List< validateCondition(getHcxRecipientCode().equals(audit.get(HCX_SENDER_CODE)), ErrorCodes.ERR_INVALID_FORWARD_REQ, FORWARD_REQ_ERR_MSG); } } - } else if (!EXCLUDE_ENTITIES.contains(getEntity(path)) && !apiAction.contains("on_") && checkParticipantRole(allowedRolesForForward, senderRoles) && recipientRoles.contains(PROVIDER) && recipientRoles.stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)) { + } else if (!EXCLUDE_ENTITIES.contains(getEntity(path)) && !apiAction.contains("on_") && checkParticipantRole(allowedRolesForForward, senderRoles) && ((recipientRoles.contains(PROVIDER)) || (recipientRoles.stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)))) { throw new ClientException(ErrorCodes.ERR_ACCESS_DENIED, INVALID_API_CALL); } // validation to check if participant is forwarding the request to provider - if (isForwardReq && !apiAction.contains("on_") && recipientRoles.contains(PROVIDER) && recipientRoles.stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)) { + if (isForwardReq && !apiAction.contains("on_") && ((recipientRoles.contains(PROVIDER)) || (recipientRoles.stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)))) { throw new ClientException(ErrorCodes.ERR_INVALID_FORWARD_REQ, INVALID_FORWARD_TO_PROVIDER); } } diff --git a/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java b/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java index e39eb4d4b..7a906d169 100644 --- a/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java +++ b/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java @@ -217,6 +217,10 @@ protected Map getPayor2Details() throws Exception { return JSONUtils.deserialize("{ \"participant_name\": \"New payor 2\", \"primary_mobile\": \"9493347002\", \"primary_email\": \"newpayor002@gmail.com\", \"roles\": [ \"payor\" ], \"scheme_code\": \"Default\", \"address\": { \"plot\": \"5-4-199\", \"street\": \"road no 12\", \"landmark\": \"Jawaharlal Nehru Road\", \"village\": \"Nampally\", \"district\": \"Hyderabad\", \"state\": \"Telangana\", \"pincode\": \"500805\", \"osid\": \"513aa2ef-c4d4-4202-9926-816a6d22ab8f\" }, \"phone\": [ \"040-387658992\" ], \"status\": \"Active\", \"endpoint_url\": \"http://a07c089412c1b46f2b49946c59267d03-2070772031.ap-south-1.elb.amazonaws.com:8080\", \"payment_details\": { \"account_number\": \"4707890099809809\", \"ifsc_code\": \"ICICI\", \"osid\": \"2b9fd445-053e-4f44-8ceb-bb51e3f48a86\" }, \"signing_cert_path\": \"urn:isbn:0-476-27557-4\", \"linked_registry_codes\": [ \"22344\" ], \"encryption_cert\": \"urn:isbn:0-4234\", \"osOwner\": [ \"a97ae3c3-bf32-438f-a63e-5b896393163f\" ], \"osid\": \"8584ba69-6c50-4535-8ad5-c02b8c3180a6\" }", Map.class); } + protected Map getInvalidPayorDetails() throws Exception { + return JSONUtils.deserialize("{ \"participant_name\": \"New payor 2\", \"primary_mobile\": \"9493347002\", \"primary_email\": \"newpayor002@gmail.com\", \"roles\": [ \"provider.hospital\" ], \"scheme_code\": \"Default\", \"address\": { \"plot\": \"5-4-199\", \"street\": \"road no 12\", \"landmark\": \"Jawaharlal Nehru Road\", \"village\": \"Nampally\", \"district\": \"Hyderabad\", \"state\": \"Telangana\", \"pincode\": \"500805\", \"osid\": \"513aa2ef-c4d4-4202-9926-816a6d22ab8f\" }, \"phone\": [ \"040-387658992\" ], \"status\": \"Active\", \"endpoint_url\": \"http://a07c089412c1b46f2b49946c59267d03-2070772031.ap-south-1.elb.amazonaws.com:8080\", \"payment_details\": { \"account_number\": \"4707890099809809\", \"ifsc_code\": \"ICICI\", \"osid\": \"2b9fd445-053e-4f44-8ceb-bb51e3f48a86\" }, \"signing_cert_path\": \"urn:isbn:0-476-27557-4\", \"linked_registry_codes\": [ \"22344\" ], \"encryption_cert\": \"urn:isbn:0-4234\", \"osOwner\": [ \"a97ae3c3-bf32-438f-a63e-5b896393163f\" ], \"osid\": \"8584ba69-6c50-4535-8ad5-c02b8c3180a6\" }", Map.class); + } + protected Map getBlockedPayorDetails() throws Exception { return JSONUtils.deserialize("{ \"participant_name\": \"New payor 3\", \"primary_mobile\": \"9493347003\", \"primary_email\": \"newpayor003@gmail.com\", \"roles\": [ \"payor\" ], \"scheme_code\": \"Default\", \"address\": { \"plot\": \"5-4-199\", \"street\": \"road no 12\", \"landmark\": \"Jawaharlal Nehru Road\", \"village\": \"Nampally\", \"district\": \"Hyderabad\", \"state\": \"Telangana\", \"pincode\": \"500805\", \"osid\": \"929d9a60-1fe3-49a5-bae7-4b49970cebbb\" }, \"phone\": [ \"040-387658992\" ], \"status\": \"Blocked\", \"endpoint_url\": \"http://a07c089412c1b46f2b49946c59267d03-2070772031.ap-south-1.elb.amazonaws.com:8080\", \"payment_details\": { \"account_number\": \"4707890099809809\", \"ifsc_code\": \"ICICI\", \"osid\": \"68a27687-b8c8-4271-97a1-0af3f53c3f3c\" }, \"signing_cert_path\": \"urn:isbn:0-476-27557-4\", \"linked_registry_codes\": [ \"22344\" ], \"encryption_cert\": \"urn:isbn:0-4234\", \"osOwner\": [ \"20bd4228-a87f-4175-a30a-20fb28983afb\" ], \"osid\": \"ce23ccdc-e645-4e35-97b8-0bd8fef43ecd\" }", Map.class); } @@ -238,6 +242,10 @@ protected List> getAuditLogs() throws Exception { return Arrays.asList(JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"request.queued\",\"recipientRole\":[\"payor\"],\"x-hcx-timestamp\":\"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5093\",\"senderRole\":[\"provider\"]}", Map.class)); } + protected List> getAuditRolesLogs() throws Exception { + return Arrays.asList(JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"request.queued\",\"recipientRole\":[\"provider\"],\"x-hcx-timestamp\":\"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5093\",\"senderRole\":[\"provider\"]}", Map.class)); + } + protected List> getAuditProviderLogs() throws Exception { return Arrays.asList(JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"request.complete\",\"recipientRole\":[\"provider\"],\"x-hcx-timestamp\":\"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/on_check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5093\",\"senderRole\":[\"provider\"]}", Map.class)); } diff --git a/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java b/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java index 7fcda3cea..de33dc311 100644 --- a/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java +++ b/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java @@ -158,7 +158,6 @@ void check_hcx_request_cycle_closed_for_provider_role() throws Exception { .expectBody(Map.class) .consumeWith(result -> assertEquals(HttpStatus.BAD_REQUEST, result.getStatus())); } - @Test void check_hcx_request_parse_timestamp_exception() throws Exception { server.enqueue(new MockResponse() @@ -663,6 +662,26 @@ void check_hcx_forward_request_success_scenario() throws Exception { .expectBody(Map.class) .consumeWith(result -> assertEquals(HttpStatus.ACCEPTED, result.getStatus())); } + @Test + void check_hcx_forward_request_invalid_roles_scenario() throws Exception { + server.enqueue(new MockResponse() + .setResponseCode(202) + .addHeader("Content-Type", "application/json")); + Mockito.when(registryService.fetchDetails(anyString(), anyString())) + .thenReturn(getPayorDetails()) + .thenReturn(getInvalidPayorDetails()); + Mockito.when(auditService.getAuditLogs(any())) + .thenReturn(getAuditRolesLogs()) + .thenReturn(getAuditRolesLogs()) + .thenReturn(new ArrayList<>()); + client.post().uri(versionPrefix + Constants.COVERAGE_ELIGIBILITY_CHECK) + .header(Constants.AUTHORIZATION, getPayorToken()) + .header("X-jwt-sub", "20bd4228-a87f-4175-a30a-20fb28983afb") + .bodyValue(Collections.singletonMap("payload", "eyJlbmMiOiJBMjU2R0NNIiwKImFsZyI6IlJTQS1PQUVQIiwKIngtaGN4LXNlbmRlcl9jb2RlIjoiMS1jZTIzY2NkYy1lNjQ1LTRlMzUtOTdiOC0wYmQ4ZmVmNDNlY2QiLAoieC1oY3gtcmVjaXBpZW50X2NvZGUiOiIxLTg1ODRiYTY5LTZjNTAtNDUzNS04YWQ1LWMwMmI4YzMxODBhNiIsCiJ4LWhjeC1hcGlfY2FsbF9pZCI6IjI2YjEwNjBjLTFlODMtNDYwMC05NjEyLWVhMzFlMGNhNTA5NCIsCiJ4LWhjeC1jb3JyZWxhdGlvbl9pZCI6IjVlOTM0ZjkwLTExMWQtNGYwYi1iMDE2LWMyMmQ4MjA2NzRlMSIsCiJ4LWhjeC10aW1lc3RhbXAiOiIyMDIxLTEwLTI3VDIwOjM1OjUyLjYzNiswNTMwIiwKIngtaGN4LXdvcmtmbG93X2lkIjoiMjZiMTA2MGMtMWU4My00NjAwLTk2MTItZWEzMWUwY2E1MDk0Igp9.6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY.Mz-VPPyU4RlcuYv1IwIvzw")) + .exchange() + .expectBody(Map.class) + .consumeWith(result -> assertEquals(HttpStatus.BAD_REQUEST, result.getStatus())); + } @Test void check_hcx_forward_request_invalid_correlation_id_scenario() throws Exception { From 52167648c258447f6ccbf24a0b7328e52455381b Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Wed, 11 Oct 2023 16:55:45 +0530 Subject: [PATCH 16/59] Update Participant.java --- hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java index a4c0038c3..efd1ccd17 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java @@ -46,13 +46,13 @@ private String getRoleAppender() { } else if (getRoles().stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)) { for (String role : getRoles()) { if (role.startsWith("provider.")) { - return role.substring(9, Math.min(role.length(), 13)); + return role.substring(9, 13); } } } else if (getRoles().contains("payor")) { return "payr"; } - return getRoles().isEmpty() ? "" : getRoles().get(0); + return getRoles().get(0); } private String getRandomSeq(){ From 99df176f092db7cb24b424b92a67a5bd48f76a4d Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Wed, 11 Oct 2023 17:12:49 +0530 Subject: [PATCH 17/59] Update BaseRequest.java --- .../src/main/java/org/swasth/apigateway/models/BaseRequest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java index f023fc702..fdef8c46b 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java @@ -218,7 +218,7 @@ public void validateUsingAuditData(List allowedEntitiesForForward, List< throw new ClientException(ErrorCodes.ERR_ACCESS_DENIED, INVALID_API_CALL); } // validation to check if participant is forwarding the request to provider - if (isForwardReq && !apiAction.contains("on_") && ((recipientRoles.contains(PROVIDER)) || (recipientRoles.stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)))) { + if (isForwardReq && !apiAction.contains("on_") && recipientRoles.contains(PROVIDER)) { throw new ClientException(ErrorCodes.ERR_INVALID_FORWARD_REQ, INVALID_FORWARD_TO_PROVIDER); } } From 19fd2e4f9f878abc51620598a28422ddc800bd2c Mon Sep 17 00:00:00 2001 From: KrutikaPhirangi Date: Wed, 11 Oct 2023 17:20:21 +0530 Subject: [PATCH 18/59] Update ParticipantService.java --- .../main/java/org/swasth/hcx/service/ParticipantService.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/hcx-apis/src/main/java/org/swasth/hcx/service/ParticipantService.java b/hcx-apis/src/main/java/org/swasth/hcx/service/ParticipantService.java index 172357a72..c53867b9f 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/service/ParticipantService.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/service/ParticipantService.java @@ -55,8 +55,6 @@ public class ParticipantService extends BaseRegistryService { private RedisCache redisCache; @Autowired private Environment env; - @Autowired - private UserService userService; public RegistryResponse create(Map requestBody, HttpHeaders header, String code) throws Exception { From 32d055c98ff4b3530ad13bd8199eeda2a51dd5c4 Mon Sep 17 00:00:00 2001 From: KrutikaPhirangi Date: Wed, 11 Oct 2023 17:33:56 +0530 Subject: [PATCH 19/59] Update test cases --- .../job/CommonSchedulerJob.java | 8 +- .../schedulers/UserSecretScheduler.java | 11 ++- .../schedulers/CommonSchedulerTest.java | 73 +++++++++++-------- 3 files changed, 53 insertions(+), 39 deletions(-) diff --git a/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/job/CommonSchedulerJob.java b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/job/CommonSchedulerJob.java index 093a66cb8..929801ab8 100644 --- a/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/job/CommonSchedulerJob.java +++ b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/job/CommonSchedulerJob.java @@ -10,7 +10,7 @@ import org.swasth.commonscheduler.schedulers.RetryScheduler; import org.swasth.commonscheduler.schedulers.UserSecretScheduler; -@SpringBootApplication(scanBasePackages={"org.swasth.commonscheduler"}) +@SpringBootApplication(scanBasePackages = {"org.swasth.commonscheduler"}) public class CommonSchedulerJob implements CommandLineRunner { @Autowired @@ -20,6 +20,7 @@ public class CommonSchedulerJob implements CommandLineRunner { RetryScheduler retryScheduler; @Autowired UserSecretScheduler userSecretScheduler; + public static void main(String[] args) { SpringApplication.run(CommonSchedulerJob.class, args); } @@ -32,12 +33,11 @@ public void run(String... args) throws Exception { } else if (args.length > 0 && StringUtils.equalsIgnoreCase("Retry", args[0])) { retryScheduler.init(); retryScheduler.process(); - } else if (args.length > 0 && StringUtils.equalsIgnoreCase("UserSecret", args[0])){ + } else if (args.length > 0 && StringUtils.equalsIgnoreCase("UserSecret", args[0])) { userSecretScheduler.init(); userSecretScheduler.process(); - }else { + } else { System.out.println("No input to process the scheduler."); } - } } \ No newline at end of file diff --git a/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java index 9fbfdbbe4..87ae335a7 100644 --- a/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java +++ b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java @@ -1,9 +1,11 @@ package org.swasth.commonscheduler.schedulers; +import com.fasterxml.jackson.core.JsonProcessingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; +import org.swasth.common.exception.ClientException; import org.swasth.common.utils.Constants; import org.swasth.common.utils.JSONUtils; import org.swasth.common.utils.NotificationUtils; @@ -42,6 +44,7 @@ public class UserSecretScheduler extends BaseScheduler { @Value("${hcx.privateKey}") private String hcxPrivateKey; + public void process() throws Exception { logger.info("User secret job started"); processExpiredSecret(); @@ -65,7 +68,7 @@ public void processExpiredSecret() throws Exception { createStatement.executeBatch(); logger.info("Job is completed"); } catch (Exception e) { - throw e; + throw new ClientException(e.getMessage()); } } @@ -91,7 +94,7 @@ public void processExpirySecret() throws Exception { createStatement.executeBatch(); logger.info("Job is completed"); } catch (Exception e) { - throw e; + throw new ClientException(e.getMessage()); } } @@ -102,7 +105,7 @@ private void generateEvent(List participantCodes, String message, String kafkaClient.send(notifyTopic, Constants.NOTIFICATION, event); } - private String getTemplateMessage(String topicCode) throws Exception { - return (String) JSONUtils.deserialize((String) (NotificationUtils.getNotification(topicCode).get(Constants.TEMPLATE)), Map.class).get(Constants.MESSAGE); + private String getTemplateMessage(String topicCode) throws JsonProcessingException { + return (String) JSONUtils.deserialize((String) (NotificationUtils.getNotification(topicCode).get(Constants.TEMPLATE)), Map.class).get(Constants.MESSAGE); } } diff --git a/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java b/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java index d607272e8..e6917b8d1 100644 --- a/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java +++ b/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java @@ -13,7 +13,6 @@ import org.mockito.MockitoAnnotations; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; @@ -39,7 +38,7 @@ import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) -@SpringBootTest(classes ={ ParticipantValidationScheduler.class, CommonSchedulerJob.class, BaseScheduler.class, UserSecretScheduler.class}) +@SpringBootTest(classes = {ParticipantValidationScheduler.class, CommonSchedulerJob.class, BaseScheduler.class, UserSecretScheduler.class}) @Import(GenericConfiguration.class) @ActiveProfiles("test") @EmbeddedKafka( @@ -67,12 +66,12 @@ public class CommonSchedulerTest { @MockBean private PostgreSQLClient postgreSQLClient; private EmbeddedPostgres embeddedPostgres; - private MockWebServer registryServer = new MockWebServer(); + private MockWebServer registryServer = new MockWebServer(); @BeforeEach void setup() throws Exception { MockitoAnnotations.initMocks(this); - registryServer.start(InetAddress.getByName("localhost"),8082); + registryServer.start(InetAddress.getByName("localhost"), 8082); embeddedPostgres = EmbeddedPostgres.builder().setPort(5432).start(); postgreSQLClient = new PostgreSQLClient("jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres"); retryScheduler.postgreSQLClient = postgreSQLClient; @@ -82,6 +81,7 @@ void setup() throws Exception { userSecretScheduler.eventGenerator = eventGenerator; userSecretScheduler.kafkaClient = kafkaClient; } + @AfterEach void teardown() throws IOException, InterruptedException { registryServer.shutdown(); @@ -95,15 +95,16 @@ void testParticipantValidationScheduler() throws Exception { .setResponseCode(200) .addHeader("Content-Type", "application/json")); Mockito.when(registryService.getDetails(anyString())).thenReturn(getProviderDetailsLessThanCurrentDay()); - Mockito.when(eventGenerator.createNotifyEvent(anyString(),anyString(),anyString(),anyList(),anyLong(),anyString(),anyString())) + Mockito.when(eventGenerator.createNotifyEvent(anyString(), anyString(), anyString(), anyList(), anyLong(), anyString(), anyString())) .thenReturn("mockedEvent"); - lenient().doNothing().when(kafkaClient).send(anyString(),anyString(),anyString()); - String[] args = { "ParticipantValidation" }; + lenient().doNothing().when(kafkaClient).send(anyString(), anyString(), anyString()); + String[] args = {"ParticipantValidation"}; commonSchedulerJob.run(args); verify(kafkaClient, times(0)).send(anyString(), anyString(), anyString()); - assertEquals("mockedEvent", eventGenerator.createNotifyEvent(anyString(),anyString(),anyString(),anyList(),anyLong(),anyString(),anyString())); + assertEquals("mockedEvent", eventGenerator.createNotifyEvent(anyString(), anyString(), anyString(), anyList(), anyLong(), anyString(), anyString())); } - private List> getProviderDetailsLessThanCurrentDay() throws Exception { + + private List> getProviderDetailsLessThanCurrentDay() throws Exception { return JSONUtils.deserialize("[{ \"participant_name\": \"HCX Gateway\", \"primary_mobile\": \"\", \"primary_email\": \"hcxgateway@gmail.com\", \"roles\": [ \"HIE/HIO.HCX\" ], \"status\": \"Created\", \"endpoint_url\": \"http://a54c5bc648f1a41b8871b77ac01060ed-1840123973.ap-south-1.elb.amazonaws.com:8080\", \"encryption_cert\": \"urn:isbn:0-4234\", \"encryption_cert_expiry\": 1693301576009,\n" + "\"sigining_cert_expiry\": 1693301576009,\"signing_cert_path\": \"https://dev-hcx-certificates.s3.ap-south-1.amazonaws.com/test-user-52.gmail%40swasth-hcx/signing_cert_path.pem\",\"osOwner\": [ \"f698b521-7409-432d-a5db-d13e51f029a9\" ], \"participant_code\": \"d2d56996-1b77-4abb-b9e9-0e6e7343c72e\" }]", ArrayList.class); } @@ -114,54 +115,54 @@ void testParticipantValidationSchedulers() throws Exception { .setResponseCode(200) .addHeader("Content-Type", "application/json")); Mockito.when(registryService.getDetails(anyString())).thenReturn(getProviderDetailsMoreThanFiveDays()); - Mockito.when(eventGenerator.createNotifyEvent(anyString(),anyString(),anyString(),anyList(),anyLong(),anyString(),anyString())) + Mockito.when(eventGenerator.createNotifyEvent(anyString(), anyString(), anyString(), anyList(), anyLong(), anyString(), anyString())) .thenReturn("mockedEvent"); - lenient().doNothing().when(kafkaClient).send(anyString(),anyString(),anyString()); - String[] args = { "ParticipantValidation" }; + lenient().doNothing().when(kafkaClient).send(anyString(), anyString(), anyString()); + String[] args = {"ParticipantValidation"}; commonSchedulerJob.run(args); verify(kafkaClient, times(0)).send(anyString(), anyString(), anyString()); - assertEquals("mockedEvent", eventGenerator.createNotifyEvent(anyString(),anyString(),anyString(),anyList(),anyLong(),anyString(),anyString())); + assertEquals("mockedEvent", eventGenerator.createNotifyEvent(anyString(), anyString(), anyString(), anyList(), anyLong(), anyString(), anyString())); } - private List> getProviderDetailsMoreThanFiveDays() throws Exception { + + private List> getProviderDetailsMoreThanFiveDays() throws Exception { return JSONUtils.deserialize("[{ \"participant_name\": \"HCX Gateway\", \"primary_mobile\": \"\", \"primary_email\": \"hcxgateway@gmail.com\", \"roles\": [ \"HIE/HIO.HCX\" ], \"status\": \"Created\", \"endpoint_url\": \"http://a54c5bc648f1a41b8871b77ac01060ed-1840123973.ap-south-1.elb.amazonaws.com:8080\", \"encryption_cert\": \"urn:isbn:0-4234\", \"encryption_cert_expiry\": 1695569991000,\n" + "\"sigining_cert_expiry\": 1695569991000,\"signing_cert_path\": \"https://dev-hcx-certificates.s3.ap-south-1.amazonaws.com/test-user-52.gmail%40swasth-hcx/signing_cert_path.pem\",\"osOwner\": [ \"f698b521-7409-432d-a5db-d13e51f029a9\" ], \"participant_code\": \"d2d56996-1b77-4abb-b9e9-0e6e7343c72e\" }]", ArrayList.class); } @Test public void testRetryRequestsScheduler() throws Exception { - postgreSQLClient.execute("CREATE TABLE payload(mid character varying PRIMARY KEY, data character varying NOT NULL, action character varying, status character varying, retrycount integer, lastupdatedon bigint)"); - postgreSQLClient.execute("INSERT INTO payload(mid, data, action, status, retrycount, lastupdatedon) VALUES('e49e067d-60ff-40ee-b3df-08abb6c2fda1', '{}', '/coverageeligibility/check', 'request.retry',1,'1676218371439');"); - when(eventGenerator.generateMetadataEvent(any())).thenReturn("mockedEvent"); - lenient().doNothing().when(kafkaClient).send(anyString(), anyString(), anyString()); - String[] args = {"Retry"}; - commonSchedulerJob.run(args); - verify(kafkaClient, times(0)).send(anyString(), anyString(), anyString()); - ResultSet result = postgreSQLClient.executeQuery("SELECT * FROM payload where mid='e49e067d-60ff-40ee-b3df-08abb6c2fda1';"); - if(result.next()) { - int retryCount = result.getInt(Constants.RETRY_COUNT); - assertEquals(2, retryCount); - } else throw new Exception("The test case failed."); + postgreSQLClient.execute("CREATE TABLE payload(mid character varying PRIMARY KEY, data character varying NOT NULL, action character varying, status character varying, retrycount integer, lastupdatedon bigint)"); + postgreSQLClient.execute("INSERT INTO payload(mid, data, action, status, retrycount, lastupdatedon) VALUES('e49e067d-60ff-40ee-b3df-08abb6c2fda1', '{}', '/coverageeligibility/check', 'request.retry',1,'1676218371439');"); + when(eventGenerator.generateMetadataEvent(any())).thenReturn("mockedEvent"); + lenient().doNothing().when(kafkaClient).send(anyString(), anyString(), anyString()); + String[] args = {"Retry"}; + commonSchedulerJob.run(args); + verify(kafkaClient, times(0)).send(anyString(), anyString(), anyString()); + ResultSet result = postgreSQLClient.executeQuery("SELECT * FROM payload where mid='e49e067d-60ff-40ee-b3df-08abb6c2fda1';"); + if (result.next()) { + int retryCount = result.getInt(Constants.RETRY_COUNT); + assertEquals(2, retryCount); + } else throw new Exception("The test case failed."); } @Test - public void testUserSecretExpired() throws Exception { + void testUserSecretExpired() throws Exception { postgreSQLClient.execute("CREATE TABLE api_access_secrets_expiry(user_id character varying, participant_code character varying, secret_generation_date bigint, secret_expiry_date bigint, username character varying NOT NULL)"); postgreSQLClient.execute("INSERT INTO api_access_secrets_expiry(user_id, participant_code, secret_generation_date, secret_expiry_date, username) VALUES('mock15@gmail.com', 'hcxtest1051.yopmail@swasth-hcx-dev', '1696839989628', '1696833349003', 'hcxtest1051.yopmail@swasth-hcx-dev:mock15@gmail.com');"); when(eventGenerator.generateMetadataEvent(any())).thenReturn("mockedEvent"); lenient().doNothing().when(kafkaClient).send(anyString(), anyString(), anyString()); String[] args = {"UserSecret"}; commonSchedulerJob.run(args); - userSecretScheduler.processExpiredSecret(); - String query = String.format("SELECT * FROM api_access_secrets_expiry WHERE secret_expiry_date <= %d ;",System.currentTimeMillis()); + String query = String.format("SELECT * FROM api_access_secrets_expiry WHERE secret_expiry_date <= %d ;", System.currentTimeMillis()); ResultSet result = postgreSQLClient.executeQuery(query); while (result.next()) { - String participant = result.getString("username"); + String participant = result.getString("username"); Assert.assertEquals("hcxtest1051.yopmail@swasth-hcx-dev:mock15@gmail.com", participant); } } @Test - public void testUserSecretAboutTpExpire() throws Exception { + void testUserSecretAboutTpExpire() throws Exception { postgreSQLClient.execute("CREATE TABLE api_access_secrets_expiry(user_id character varying, participant_code character varying, secret_generation_date bigint, secret_expiry_date bigint, username character varying NOT NULL)"); postgreSQLClient.execute("INSERT INTO api_access_secrets_expiry(user_id, participant_code, secret_generation_date, secret_expiry_date, username) VALUES('mock18@gmail.com', 'hcxtest6.yopmail@swasth-hcx', '1696839989628', '1697528269086', 'hcxtest6.yopmail@swasth-hcx:mock18@gmail.com');"); when(eventGenerator.generateMetadataEvent(any())).thenReturn("mockedEvent"); @@ -169,5 +170,15 @@ public void testUserSecretAboutTpExpire() throws Exception { String[] args = {"UserSecret"}; commonSchedulerJob.run(args); } + @Test + void testUserSecretAExpiredException() { + try { + String[] args = {"UserSecret"}; + commonSchedulerJob.run(args); + } catch (Exception e) { + String message = e.getMessage(); + assertEquals(true , message.contains("Error while performing database operation: ERROR: relation \"api_access_secrets_expiry\" does not exist\n")); + } + } } From f4c0f7219be9388ba79c8dd4b0df05f8195909cd Mon Sep 17 00:00:00 2001 From: KrutikaPhirangi Date: Wed, 11 Oct 2023 17:49:57 +0530 Subject: [PATCH 20/59] Update CommonSchedulerTest.java --- .../swasth/commonscheduler/schedulers/CommonSchedulerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java b/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java index e6917b8d1..d160858bc 100644 --- a/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java +++ b/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java @@ -18,7 +18,6 @@ import org.springframework.context.annotation.Import; import org.springframework.kafka.test.context.EmbeddedKafka; import org.springframework.test.context.ActiveProfiles; -import org.swasth.common.exception.ClientException; import org.swasth.common.helpers.EventGenerator; import org.swasth.common.service.RegistryService; import org.swasth.common.utils.Constants; @@ -169,6 +168,7 @@ void testUserSecretAboutTpExpire() throws Exception { lenient().doNothing().when(kafkaClient).send(anyString(), anyString(), anyString()); String[] args = {"UserSecret"}; commonSchedulerJob.run(args); + verify(kafkaClient, times(0)).send(anyString(), anyString(), anyString()); } @Test void testUserSecretAExpiredException() { From 2c307fc72ac2c8d9869602dcade579fdad7b1d04 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Wed, 11 Oct 2023 18:09:57 +0530 Subject: [PATCH 21/59] feat : added test cases --- .../java/org/swasth/apigateway/BaseSpec.java | 4 ++-- .../apigateway/filters/HCXRequestTest.java | 21 +++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java b/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java index 7a906d169..3a7094a76 100644 --- a/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java +++ b/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java @@ -247,11 +247,11 @@ protected List> getAuditRolesLogs() throws Exception { } protected List> getAuditProviderLogs() throws Exception { - return Arrays.asList(JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"request.complete\",\"recipientRole\":[\"provider\"],\"x-hcx-timestamp\":\"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/on_check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5093\",\"senderRole\":[\"provider\"]}", Map.class)); + return Arrays.asList(JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"response.complete\",\"recipientRole\":[\"provider\"],\"x-hcx-timestamp\":\"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/on_check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5093\",\"senderRole\":[\"provider\"]}", Map.class)); } protected List> getAuditProviderSpecificRolesLogs() throws Exception { - return Arrays.asList(JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"request.complete\",\"recipientRole\":[\"provider.hospital\"],\"x-hcx-timestamp\":\"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/on_check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5093\",\"senderRole\":[\"provider\"]}", Map.class)); + return Arrays.asList(JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"response.complete\",\"recipientRole\":[\"provider.hospital\"],\"x-hcx-timestamp\":\"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/on_check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5093\",\"senderRole\":[\"provider\"]}", Map.class)); } protected List> getCorrelationIdAuditLogs() throws Exception { Map auditMap1 = JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"request.queued\",\"recipientRole\":[\"payor\"],\"x-hcx-timestamp\": \"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"2c364696-019f-4902-83c9-2a8764559c34\",\"senderRole\":[\"provider\"]}", Map.class); diff --git a/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java b/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java index de33dc311..ff4231d3c 100644 --- a/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java +++ b/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java @@ -158,6 +158,27 @@ void check_hcx_request_cycle_closed_for_provider_role() throws Exception { .expectBody(Map.class) .consumeWith(result -> assertEquals(HttpStatus.BAD_REQUEST, result.getStatus())); } + + @Test + void check_hcx_request_cycle_closed_for_provider_specific_roles() throws Exception { + server.enqueue(new MockResponse() + .setResponseCode(202) + .addHeader("Content-Type", "application/json")); + Mockito.when(registryService.fetchDetails(anyString(), anyString())) + .thenReturn(getPayorDetails()) + .thenReturn(getProviderDetails()); + Mockito.when(auditService.getAuditLogs(any())) + .thenReturn(getAuditProviderSpecificRolesLogs()) + .thenReturn(getAuditProviderSpecificRolesLogs()) + .thenReturn(new ArrayList<>()); + client.post().uri(versionPrefix + Constants.COVERAGE_ELIGIBILITY_ONCHECK) + .header(Constants.AUTHORIZATION, getPayorToken()) + .header("X-jwt-sub", "20bd4228-a87f-4175-a30a-20fb28983afb") + .bodyValue(getOnRequestBody()) + .exchange() + .expectBody(Map.class) + .consumeWith(result -> assertEquals(HttpStatus.BAD_REQUEST, result.getStatus())); + } @Test void check_hcx_request_parse_timestamp_exception() throws Exception { server.enqueue(new MockResponse() From 073072b394d27608c45365f21d1d0ca14adc8763 Mon Sep 17 00:00:00 2001 From: KrutikaPhirangi Date: Wed, 11 Oct 2023 18:50:49 +0530 Subject: [PATCH 22/59] Update --- .../main/java/org/swasth/hcx/services/OnboardService.java | 8 ++++---- .../src/main/resources/templates/api-access-secret.ftl | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java index c070640a8..39cd8503c 100644 --- a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java +++ b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java @@ -900,9 +900,9 @@ private String userInviteAcceptParticipantTemplate(String participantName, Strin return freemarkerService.renderTemplate("user-invite-accepted-participant.ftl", model); } - private String apiAccessSecret(String username, String password, String participantCode) throws Exception { + private String apiAccessSecretTemplate(String user, String password, String participantCode) throws Exception { Map model = new HashMap<>(); - model.put("USER_NAME", username); + model.put("USER_ID", user); model.put("PARTICIPANT_CODE", participantCode); model.put("PASSWORD", password); return freemarkerService.renderTemplate("api-access-secret.ftl", model); @@ -1123,7 +1123,7 @@ private void setKeycloakPassword(String password, String user, String realm) thr userResource.resetPassword(passwordCred); String userId = userResource.toRepresentation().getId(); realmResource.users().get(userId).logout(); - logger.info("The Keycloak password for the user :" + user + " has been successfully updated, and their sessions have been invalidated."); + logger.info("The Keycloak password for the osOwner :" + user + " has been successfully updated, and their sessions have been invalidated."); } catch (Exception e) { throw new ClientException("Unable to set keycloak password : " + e.getMessage()); } @@ -1279,7 +1279,7 @@ public Response generateAndSetUserSecret(Map requestBody) throw List existingUsers = usersResource.search(userName); String userId = existingUsers.get(0).getId(); setKeycloakPassword(password, userId, keycloakApiAccessRealm); - kafkaClient.send(messageTopic, EMAIL, eventGenerator.getEmailMessageEvent(apiAccessSecret(userName, password, (String) participant.get(PARTICIPANT_CODE)), passwordGenerateSub, Arrays.asList((String) participant.get(PRIMARY_EMAIL)), new ArrayList<>(), new ArrayList<>())); + kafkaClient.send(messageTopic, EMAIL, eventGenerator.getEmailMessageEvent(apiAccessSecretTemplate((String) requestBody.get(USER_ID), password, (String) participant.get(PARTICIPANT_CODE)), passwordGenerateSub, Arrays.asList((String) requestBody.get(USER_ID)), new ArrayList<>(), new ArrayList<>())); return getSuccessResponse(); } } diff --git a/hcx-onboard/src/main/resources/templates/api-access-secret.ftl b/hcx-onboard/src/main/resources/templates/api-access-secret.ftl index 64762f0a3..0d8f9cdad 100644 --- a/hcx-onboard/src/main/resources/templates/api-access-secret.ftl +++ b/hcx-onboard/src/main/resources/templates/api-access-secret.ftl @@ -1,11 +1,11 @@ -Hello,

-Password has been generated successfully for the ${USER_NAME}.

-Use below credentials for participant token generation: +Hello ${USER_ID},

+Secret has been generated successfully for the user_id : ${USER_ID}.

+Use below credentials for token generation:
    -
  • username : ${USER_NAME}
  • +
  • username : ${USER_ID}
  • secret : ${PASSWORD}
  • participant_code : ${PARTICIPANT_CODE}
From fd4caa100393393c674941cdb35ac4f8f8a1d709 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Thu, 12 Oct 2023 10:37:23 +0530 Subject: [PATCH 23/59] Update HCXRequestTest.java --- .../test/java/org/swasth/apigateway/filters/HCXRequestTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java b/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java index ff4231d3c..2355f3b1b 100644 --- a/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java +++ b/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java @@ -138,6 +138,7 @@ void check_hcx_request_reuse_correlation_id_scenario_after_complete_status_and_t .consumeWith(result -> assertEquals(HttpStatus.ACCEPTED, result.getStatus())); } + // The status is "response.complete," indicating that the cycle should be closed. and below testcase is failing @Test void check_hcx_request_cycle_closed_for_provider_role() throws Exception { server.enqueue(new MockResponse() From 8e82fec88f3e970bd59a7dad67765dc07fe3fb17 Mon Sep 17 00:00:00 2001 From: KrutikaPhirangi Date: Thu, 12 Oct 2023 11:57:24 +0530 Subject: [PATCH 24/59] Update --- .../org/swasth/hcx/service/KeycloakApiAccessService.java | 6 +++--- hcx-apis/src/main/resources/application.yml | 4 ++-- .../hcx-common/src/main/resources/networkNotifications.yaml | 4 ++-- .../main/java/org/swasth/hcx/services/OnboardService.java | 6 +++--- hcx-onboard/src/main/resources/application.yml | 4 ++-- .../src/main/resources/templates/api-access-secret.ftl | 2 +- .../commonscheduler/schedulers/UserSecretScheduler.java | 2 +- .../common-scheduler-job/src/main/resources/application.yml | 2 +- 8 files changed, 15 insertions(+), 15 deletions(-) diff --git a/hcx-apis/src/main/java/org/swasth/hcx/service/KeycloakApiAccessService.java b/hcx-apis/src/main/java/org/swasth/hcx/service/KeycloakApiAccessService.java index fbb6ee1b3..304df29bb 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/service/KeycloakApiAccessService.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/service/KeycloakApiAccessService.java @@ -38,8 +38,8 @@ public class KeycloakApiAccessService { private String keycloakMasterRealm; @Value("${postgres.api-access-secrets-expiry-table}") private String apiAccessTable; - @Value("${secret.expiry-time}") - private int secretExpiry; + @Value("${api-access-secret.expiry-days}") + private int secretExpiryDays; @Value("${keycloak.protocol-access-realm}") private String keycloackProtocolAccessRealm; @Value("${keycloak.admin-client-id}") @@ -73,7 +73,7 @@ public void addUserWithParticipant(String email, String participantCode, String response.close(); if (response.getStatus() == 201) { String query = String.format("INSERT INTO %s (user_id,participant_code,secret_generation_date,secret_expiry_date,username)VALUES ('%s','%s',%d,%d,'%s');", apiAccessTable, email, - participantCode, System.currentTimeMillis(), System.currentTimeMillis() + (secretExpiry * 24 * 60 * 60 * 1000), userName); + participantCode, System.currentTimeMillis(), System.currentTimeMillis() + (secretExpiryDays * 24 * 60 * 60 * 1000), userName); postgreSQLClient.execute(query); String message = userEmailMessage; message = message.replace("NAME", name).replace("USER_ID", email).replace("PASSWORD", password).replace("PARTICIPANT_CODE", participantCode); diff --git a/hcx-apis/src/main/resources/application.yml b/hcx-apis/src/main/resources/application.yml index 3f4bf7409..019b71b90 100644 --- a/hcx-apis/src/main/resources/application.yml +++ b/hcx-apis/src/main/resources/application.yml @@ -153,5 +153,5 @@ email: user-token-subject: ${token_generate_subject:HCX - Protocol APIs Access Token Generation credentials} user-token-message: ${user_token_message:Hi NAME,

Along with participant username and password, api access token can be generated using the following credentials.
  • user_name - USER_ID
  • secret - PASSWORD
  • participant_code - PARTICIPANT_CODE
This API Access token can be used to make protocol API requests. Please refer to the instructions provided in the link to generate access token.

If you have any queries, Please reach out HCX team.

Thanks and Regards
HCX Team.} -secret: - expiry-time: ${secret_expiry_time:90} \ No newline at end of file +api-access-secret: + expiry-days: ${secret_expiry_days:90} \ No newline at end of file diff --git a/hcx-core/hcx-common/src/main/resources/networkNotifications.yaml b/hcx-core/hcx-common/src/main/resources/networkNotifications.yaml index af689e702..53708b366 100644 --- a/hcx-core/hcx-common/src/main/resources/networkNotifications.yaml +++ b/hcx-core/hcx-common/src/main/resources/networkNotifications.yaml @@ -349,7 +349,7 @@ operating on HCX."} status: Active is_delegate: false -- topic_code: notif-secret-expiry +- topic_code: notif-api-access-secret-expiry title: Api access secret expiry description: >- Notification about the api access secret expiration for the participant in the @@ -373,7 +373,7 @@ ${days} days.Please reset your api access secret."} status: Active is_delegate: false -- topic_code: notif-secret-expired +- topic_code: notif-api-access-secret-expired title: Api access secret expired description: Notification about api access secret expired allowed_senders: diff --git a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java index 39cd8503c..4610307fe 100644 --- a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java +++ b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java @@ -150,8 +150,8 @@ public class OnboardService extends BaseController { private String emailConfig; @Value("${onboard.phone}") private String phoneConfig; - @Value("${secret.expiry-time}") - private int secretExpiry; + @Value("${api-access-secret.expiry-days}") + private int secretExpiryDays; @Autowired private IDatabaseService postgreSQLClient; @@ -1271,7 +1271,7 @@ public Response generateAndSetUserSecret(Map requestBody) throw String selectQuery = String.format("SELECT * FROM %s WHERE username = '%s';", apiAccessTable, userName); ResultSet resultSet = (ResultSet) postgreSQLClient.executeQuery(selectQuery); if (resultSet.next()) { - String query = String.format("UPDATE %s SET secret_generation_date=%d,secret_expiry_date=%d WHERE username='%s';", apiAccessTable, System.currentTimeMillis(), System.currentTimeMillis() + (secretExpiry * 24 * 60 * 60 * 1000), userName); + String query = String.format("UPDATE %s SET secret_generation_date=%d,secret_expiry_date=%d WHERE username='%s';", apiAccessTable, System.currentTimeMillis(), System.currentTimeMillis() + (secretExpiryDays * 24 * 60 * 60 * 1000), userName); postgreSQLClient.execute(query); } RealmResource realmResource = keycloak.realm(keycloakApiAccessRealm); diff --git a/hcx-onboard/src/main/resources/application.yml b/hcx-onboard/src/main/resources/application.yml index 0fa1f315c..bc7a97e3f 100644 --- a/hcx-onboard/src/main/resources/application.yml +++ b/hcx-onboard/src/main/resources/application.yml @@ -105,5 +105,5 @@ keycloak: endpoint: user-invite: ${user_invite_endpoint:/onboarding/user/invite} -secret: - expiry-time: ${secret_expiry_time:90} \ No newline at end of file +api-access-secret: + expiry-days: ${secret_expiry_days:90} \ No newline at end of file diff --git a/hcx-onboard/src/main/resources/templates/api-access-secret.ftl b/hcx-onboard/src/main/resources/templates/api-access-secret.ftl index 0d8f9cdad..c70966269 100644 --- a/hcx-onboard/src/main/resources/templates/api-access-secret.ftl +++ b/hcx-onboard/src/main/resources/templates/api-access-secret.ftl @@ -2,7 +2,7 @@ Hello ${USER_ID},

-Secret has been generated successfully for the user_id : ${USER_ID}.

+API Access secret has been generated successfully for the user_id : ${USER_ID}.

Use below credentials for token generation:
  • username : ${USER_ID}
  • diff --git a/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java index 87ae335a7..905b14248 100644 --- a/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java +++ b/hcx-scheduler-jobs/common-scheduler-job/src/main/java/org/swasth/commonscheduler/schedulers/UserSecretScheduler.java @@ -24,7 +24,7 @@ public class UserSecretScheduler extends BaseScheduler { @Value("${postgres.table}") private String postgresTable; - @Value("${secret.expiry-days}") + @Value("${api-access-secret.expiry-days}") private List secretExpiryDays; @Value("${kafka.topic.notification}") diff --git a/hcx-scheduler-jobs/common-scheduler-job/src/main/resources/application.yml b/hcx-scheduler-jobs/common-scheduler-job/src/main/resources/application.yml index 18b31cfc1..fa56d48aa 100644 --- a/hcx-scheduler-jobs/common-scheduler-job/src/main/resources/application.yml +++ b/hcx-scheduler-jobs/common-scheduler-job/src/main/resources/application.yml @@ -65,5 +65,5 @@ notification: certificate: expiry-days: ${certificate_expiry_days:5,10,15} -secret: +api-access-secret: expiry-days: ${certificate_expiry_days:5,10,15} \ No newline at end of file From f5f4674b667b0d3ff976258cb54f4695de639cf1 Mon Sep 17 00:00:00 2001 From: KrutikaPhirangi Date: Thu, 12 Oct 2023 13:07:53 +0530 Subject: [PATCH 25/59] Update application.yml --- .../common-scheduler-job/src/main/resources/application.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hcx-scheduler-jobs/common-scheduler-job/src/main/resources/application.yml b/hcx-scheduler-jobs/common-scheduler-job/src/main/resources/application.yml index fa56d48aa..f52de6d42 100644 --- a/hcx-scheduler-jobs/common-scheduler-job/src/main/resources/application.yml +++ b/hcx-scheduler-jobs/common-scheduler-job/src/main/resources/application.yml @@ -24,8 +24,8 @@ topicCode: before-encryption-cert-expiry: ${before_encryption_cert_expiry_topic_code:notif-encryption-key-expiry} signing-cert-expired: ${signing_cert_expired_topic_code:notif-signing-cert-expired} before-signing-cert-expiry: ${before_signing_cert_expiry_topic_code:notif-signing-key-expiry} - secret-expired: ${secret_expired:notif-secret-expired} - before-secret-expiry: ${before_secret_expiry:notif-secret-expiry} + secret-expired: ${secret_expired:notif-api-access-secret-expired} + before-secret-expiry: ${before_secret_expiry:notif-api-access-secret-expiry} #postgres config postgres: From 75b9966cac6ded04943d2247f7e54af0002b429d Mon Sep 17 00:00:00 2001 From: KrutikaPhirangi Date: Thu, 12 Oct 2023 13:29:43 +0530 Subject: [PATCH 26/59] Update CommonSchedulerTest.java --- .../swasth/commonscheduler/schedulers/CommonSchedulerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java b/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java index d160858bc..0f570d3cb 100644 --- a/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java +++ b/hcx-scheduler-jobs/common-scheduler-job/src/test/java/org/swasth/commonscheduler/schedulers/CommonSchedulerTest.java @@ -163,7 +163,7 @@ void testUserSecretExpired() throws Exception { @Test void testUserSecretAboutTpExpire() throws Exception { postgreSQLClient.execute("CREATE TABLE api_access_secrets_expiry(user_id character varying, participant_code character varying, secret_generation_date bigint, secret_expiry_date bigint, username character varying NOT NULL)"); - postgreSQLClient.execute("INSERT INTO api_access_secrets_expiry(user_id, participant_code, secret_generation_date, secret_expiry_date, username) VALUES('mock18@gmail.com', 'hcxtest6.yopmail@swasth-hcx', '1696839989628', '1697528269086', 'hcxtest6.yopmail@swasth-hcx:mock18@gmail.com');"); + postgreSQLClient.execute("INSERT INTO api_access_secrets_expiry(user_id, participant_code, secret_generation_date, secret_expiry_date, username) VALUES('mock18@gmail.com', 'hcxtest6.yopmail@swasth-hcx', '1696839989628', '1698479822560', 'hcxtest6.yopmail@swasth-hcx:mock18@gmail.com');"); when(eventGenerator.generateMetadataEvent(any())).thenReturn("mockedEvent"); lenient().doNothing().when(kafkaClient).send(anyString(), anyString(), anyString()); String[] args = {"UserSecret"}; From 384889fcdeb6a92e046c2745de242786ff0bb7cf Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Thu, 12 Oct 2023 19:18:11 +0530 Subject: [PATCH 27/59] feat : handled exception --- .../java/org/swasth/hcx/services/OnboardService.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java index d792d66b9..5d7a8acbc 100644 --- a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java +++ b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java @@ -294,7 +294,7 @@ private Map getApplicantBody(OnboardRequest request) { body.put(MOBILE, request.getPrimaryMobile()); body.put(APPLICANT_NAME, request.getParticipantName()); body.put(ADDITIONALVERIFICATION, request.getAdditionalVerification()); - body.put(ROLE, PROVIDER); + body.put(ROLE, request.getRoles().get(0)); return body; } @@ -765,8 +765,13 @@ public Response userInviteAccept(HttpHeaders headers, Map body) private void addUser(HttpHeaders headers, String requestBody) throws Exception { HttpResponse response = HttpUtils.post(hcxAPIBasePath + VERSION_PREFIX + PARTICIPANT_USER_ADD, requestBody, getHeadersMap(headers)); if (response.getStatus() != 200) { - Response resp = new Response(JSONUtils.deserialize(response.getBody(), Map.class)); - throw new ClientException(resp.getError().getCode(), resp.getError().getMessage()); + Map result = JSONUtils.deserialize(response.getBody(), Map.class); + List> errList = JSONUtils.convert(result.get("result"), ArrayList.class); + Map errorMap = new HashMap<>(); + for (Map error : errList) { + errorMap = (Map) error.get("error"); + } + throw new ClientException((String) errorMap.get("message")); } } From 9ae4bcef3fc2cbd78c6577997ac759a8e29f8d16 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Sat, 14 Oct 2023 22:41:51 +0530 Subject: [PATCH 28/59] Update ParticipantService.java --- .../main/java/org/swasth/hcx/service/ParticipantService.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/hcx-apis/src/main/java/org/swasth/hcx/service/ParticipantService.java b/hcx-apis/src/main/java/org/swasth/hcx/service/ParticipantService.java index 172357a72..c53867b9f 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/service/ParticipantService.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/service/ParticipantService.java @@ -55,8 +55,6 @@ public class ParticipantService extends BaseRegistryService { private RedisCache redisCache; @Autowired private Environment env; - @Autowired - private UserService userService; public RegistryResponse create(Map requestBody, HttpHeaders header, String code) throws Exception { From 7d151eaa750c1c5eccb7c9d99a03a2c7cb2beb98 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 16 Oct 2023 10:29:14 +0530 Subject: [PATCH 29/59] feat : removed roles in yaml file --- .../org/swasth/apigateway/filters/AuditValidationFilter.java | 5 +---- api-gateway/src/main/resources/application.yaml | 3 --- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java b/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java index 68185e1e4..7e91896ca 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java @@ -41,9 +41,6 @@ public class AuditValidationFilter extends AbstractGatewayFilterFactory providerSpecificRoles; - public AuditValidationFilter() { super(Config.class); } @@ -64,7 +61,7 @@ public GatewayFilter apply(Config config) { ArrayList roles = (ArrayList) participant.get("roles"); String code = (String) participant.get(Constants.PARTICIPANT_CODE); Map filters = (Map) filterMap.get("filters"); - if (roles.contains("payor") || roles.contains("provider") || roles.stream().anyMatch(providerSpecificRoles::contains)) { + if (roles.contains("payor") || roles.contains("provider") || roles.stream().anyMatch(Constants.PROVIDER_SPECIFIC_ROLES::contains)) { filters.put("x-hcx-sender_code", code); filterMap.put("filters", filters); logger.debug("updated filters: {}", filterMap); diff --git a/api-gateway/src/main/resources/application.yaml b/api-gateway/src/main/resources/application.yaml index fa8cbaa1a..3c994f7ee 100644 --- a/api-gateway/src/main/resources/application.yaml +++ b/api-gateway/src/main/resources/application.yaml @@ -109,9 +109,6 @@ audit: index: ${audit_index:hcx_audit} alias: ${audit_alias:hcx_audit} -provider-specific: - roles: ${provider_specific_roles:provider.hospital,provider.clinic,provider.practitioner,provider.diagnostics,provider.pharmacy} - spring: main: web-application-type: reactive From 02e0a8012a711ba119eb04ba13933e04d75860c0 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 16 Oct 2023 10:33:05 +0530 Subject: [PATCH 30/59] feat : removed roles in rbac file --- hcx-onboard/src/main/resources/application.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/hcx-onboard/src/main/resources/application.yml b/hcx-onboard/src/main/resources/application.yml index f0cf66ff8..7cc3b7ac5 100644 --- a/hcx-onboard/src/main/resources/application.yml +++ b/hcx-onboard/src/main/resources/application.yml @@ -101,6 +101,4 @@ keycloak: participant-realm: ${keycloack_users_realm:swasth-hcx-participants} endpoint: - user-invite: ${user_invite_endpoint:/onboarding/user/invite} - -provider-specific-roles: ${provider_specific_roles:provider.hospital,provider.clinic,provider.practitioner,provider.diagnostics,provider.pharmacy} \ No newline at end of file + user-invite: ${user_invite_endpoint:/onboarding/user/invite} \ No newline at end of file From c43c5586d1efcaab3e8f25b3d668dac7b9eb4259 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 16 Oct 2023 11:09:37 +0530 Subject: [PATCH 31/59] feat : added applicant code --- .../main/java/org/swasth/hcx/services/OnboardService.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java index 5d7a8acbc..d9bb6e6ea 100644 --- a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java +++ b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java @@ -239,13 +239,14 @@ private String createEntity(String api, String participant, Map return (String) JSONUtils.deserialize(createResponse.getBody(), Map.class).get(id); } - private void addParticipantDetails(Map participant, OnboardRequest request) { + private void addParticipantDetails(Map participant, OnboardRequest request) { participant.put(ENDPOINT_URL, "http://testurl/v0.7"); participant.put(ENCRYPTION_CERT, "https://raw.githubusercontent.com/Swasth-Digital-Health-Foundation/hcx-platform/main/hcx-apis/src/test/resources/examples/test-keys/public-key.pem"); participant.put(REGISTRY_STATUS, CREATED); - if (((ArrayList) participant.get(ROLES)).contains(PAYOR)) + ArrayList roles = (ArrayList) participant.get(ROLES); + if (roles.contains(PAYOR)) participant.put(SCHEME_CODE, "default"); - if (((ArrayList) participant.get(ROLES)).contains(PROVIDER)) + if (roles.contains(PROVIDER) || roles.stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)) participant.put(APPLICANT_CODE, request.getApplicantCode()); } From c64bb3f9a10238a58448f69e87d7a48c5a4a5b76 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 16 Oct 2023 12:03:43 +0530 Subject: [PATCH 32/59] Update Participant.java --- .../src/main/java/org/swasth/hcx/models/Participant.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java index efd1ccd17..d66285398 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java @@ -41,9 +41,7 @@ public String generateCode(String fieldSeparator, String hcxInstanceName) { } private String getRoleAppender() { - if (getRoles().contains("provider")) { - return "hosp"; - } else if (getRoles().stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)) { + if (getRoles().stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)) { for (String role : getRoles()) { if (role.startsWith("provider.")) { return role.substring(9, 13); @@ -51,6 +49,8 @@ private String getRoleAppender() { } } else if (getRoles().contains("payor")) { return "payr"; + } else if(getRoles().contains("bsp")){ + return "bsp"; } return getRoles().get(0); } From cd46eb73d90e65ebc8009f1530a4ded36210d97b Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Thu, 19 Oct 2023 11:19:15 +0530 Subject: [PATCH 33/59] Update OnboardService.java --- .../src/main/java/org/swasth/hcx/services/OnboardService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java index 775ea338b..a8def479d 100644 --- a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java +++ b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java @@ -296,7 +296,7 @@ private Map getApplicantBody(OnboardRequest request) { body.put(MOBILE, request.getPrimaryMobile()); body.put(APPLICANT_NAME, request.getParticipantName()); body.put(ADDITIONALVERIFICATION, request.getAdditionalVerification()); - body.put(ROLE, request.getRoles().get(0)); + body.put(ROLE, request.getRoles()); return body; } From 42183542aec733c578204833a506482851b3290e Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Fri, 20 Oct 2023 13:01:02 +0530 Subject: [PATCH 34/59] feat : time stamp issue --- .../swasth/apigateway/models/BaseRequest.java | 8 ++-- .../java/org/swasth/apigateway/BaseSpec.java | 4 +- .../apigateway/filters/HCXRequestTest.java | 42 +++++++++---------- .../swasth/hcx/models/ParticipantTests.java | 2 +- 4 files changed, 27 insertions(+), 29 deletions(-) diff --git a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java index fdef8c46b..7d1e61fc1 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java @@ -366,18 +366,16 @@ private List> filteredList(List> correla .filter(map -> COMPLETE_STATUS.equals(map.get(STATUS))) .filter(map -> { try { - return isWithinLastDays((String) map.get(TIMESTAMP), days); + return isWithinLastDays((Long) map.get(UPDATED_TIME), days); } catch (ParseException e) { throw new RuntimeException(e); } }).collect(Collectors.toList()); } - private boolean isWithinLastDays(String timestamp,int days) throws ParseException { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + private boolean isWithinLastDays(long timestamp ,int days) throws ParseException { Date currentDate = new Date(); - Date date = sdf.parse(timestamp); - long differenceInMillis = currentDate.getTime() - date.getTime(); + long differenceInMillis = currentDate.getTime() - timestamp; long daysDifference = TimeUnit.DAYS.convert(differenceInMillis, TimeUnit.MILLISECONDS); return daysDifference > days; } diff --git a/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java b/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java index 3a7094a76..8c45b5aed 100644 --- a/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java +++ b/api-gateway/src/test/java/org/swasth/apigateway/BaseSpec.java @@ -254,8 +254,8 @@ protected List> getAuditProviderSpecificRolesLogs() throws Ex return Arrays.asList(JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"response.complete\",\"recipientRole\":[\"provider.hospital\"],\"x-hcx-timestamp\":\"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/on_check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5093\",\"senderRole\":[\"provider\"]}", Map.class)); } protected List> getCorrelationIdAuditLogs() throws Exception { - Map auditMap1 = JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"request.queued\",\"recipientRole\":[\"payor\"],\"x-hcx-timestamp\": \"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"2c364696-019f-4902-83c9-2a8764559c34\",\"senderRole\":[\"provider\"]}", Map.class); - Map auditMap2 = JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1646736375686,\"x-hcx-status\":\"response.complete\",\"recipientRole\":[\"payor\"],\"x-hcx-timestamp\": \"2023-06-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"2c364696-019f-4902-83c9-2a8764559c34\",\"senderRole\":[\"provider\"]}", Map.class); + Map auditMap1 = JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1687850562000,\"x-hcx-status\":\"request.queued\",\"recipientRole\":[\"payor\"],\"x-hcx-timestamp\": \"2021-10-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"2c364696-019f-4902-83c9-2a8764559c34\",\"senderRole\":[\"provider\"]}", Map.class); + Map auditMap2 = JSONUtils.deserialize("{\"eid\":\"AUDIT\",\"x-hcx-error_details\":{},\"x-hcx-recipient_code\":\"1-2ff1f493-c4d4-4fc7-8d41-aaabb997af23\",\"x-hcx-debug_details\":{},\"auditTimeStamp\":1646736378272,\"mid\":\"54af42a9-3905-4f15-8c9d-94079594b6a6\",\"x-hcx-correlation_id\":\"5e934f90-111d-4f0b-b016-c22d820674e1\",\"updatedTimestamp\":1687850562000,\"x-hcx-status\":\"response.complete\",\"recipientRole\":[\"payor\"],\"x-hcx-timestamp\": \"2023-06-27T20:35:52.636+0530\",\"requestTimeStamp\":1646735834459,\"x-hcx-sender_code\":\"1-3a3bd68a-848a-4d52-9ec2-07a92d765fb4\",\"action\":\"/v1/coverageeligibility/check\",\"x-hcx-workflow_id\":\"26b1060c-1e83-4600-9612-ea31e0ca5094\",\"x-hcx-api_call_id\":\"2c364696-019f-4902-83c9-2a8764559c34\",\"senderRole\":[\"provider\"]}", Map.class); return new ArrayList<>(Arrays.asList(auditMap1,auditMap2)); } diff --git a/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java b/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java index 2355f3b1b..bd63d80ff 100644 --- a/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java +++ b/api-gateway/src/test/java/org/swasth/apigateway/filters/HCXRequestTest.java @@ -180,27 +180,27 @@ void check_hcx_request_cycle_closed_for_provider_specific_roles() throws Excepti .expectBody(Map.class) .consumeWith(result -> assertEquals(HttpStatus.BAD_REQUEST, result.getStatus())); } - @Test - void check_hcx_request_parse_timestamp_exception() throws Exception { - server.enqueue(new MockResponse() - .setResponseCode(202) - .addHeader("Content-Type", "application/json")); - Mockito.when(registryService.fetchDetails(anyString(), anyString())) - .thenReturn(getProviderDetails()) - .thenReturn(getPayorDetails()); - Mockito.when(auditService.getAuditLogs(any())) - .thenReturn(new ArrayList<>()) - .thenReturn(getAuditLogs()) - .thenReturn(new ArrayList<>()) - .thenReturn(getInvalidTimestampAuditLogs()); - client.post().uri(versionPrefix + Constants.COVERAGE_ELIGIBILITY_CHECK) - .header(Constants.AUTHORIZATION, getProviderToken()) - .header("X-jwt-sub", "f7c0e759-bec3-431b-8c4f-6b294d103a74") - .bodyValue(getCorrelationIDRequestBody()) - .exchange() - .expectBody(Map.class) - .consumeWith(result -> assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatus())); - } +// @Test +// void check_hcx_request_parse_timestamp_exception() throws Exception { +// server.enqueue(new MockResponse() +// .setResponseCode(202) +// .addHeader("Content-Type", "application/json")); +// Mockito.when(registryService.fetchDetails(anyString(), anyString())) +// .thenReturn(getProviderDetails()) +// .thenReturn(getPayorDetails()); +// Mockito.when(auditService.getAuditLogs(any())) +// .thenReturn(new ArrayList<>()) +// .thenReturn(getAuditLogs()) +// .thenReturn(new ArrayList<>()) +// .thenReturn(getInvalidTimestampAuditLogs()); +// client.post().uri(versionPrefix + Constants.COVERAGE_ELIGIBILITY_CHECK) +// .header(Constants.AUTHORIZATION, getProviderToken()) +// .header("X-jwt-sub", "f7c0e759-bec3-431b-8c4f-6b294d103a74") +// .bodyValue(getCorrelationIDRequestBody()) +// .exchange() +// .expectBody(Map.class) +// .consumeWith(result -> assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatus())); +// } @Test void check_hcx_request_filter_list_empty() throws Exception { diff --git a/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java b/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java index 07ab0b6f5..bb31566e4 100644 --- a/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java +++ b/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java @@ -20,7 +20,7 @@ void generate_participant_code_with_payor_role() { void generate_participant_code_with_provider_role() { Participant participant = new Participant(getProviderRequestBody()); String code = participant.generateCode("_", "swasth-hcx"); - Assertions.assertEquals("hosp_rakshi_012345@swasth-hcx", code); + Assertions.assertEquals("provider_rakshi_012345@swasth-hcx", code); } @Test From 008c87c3d5b4eee4ebc99ee3aa6626a528116e63 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Fri, 27 Oct 2023 10:15:06 +0530 Subject: [PATCH 35/59] feat : pipeline job --- .../src/main/scala/org/swasth/dp/core/util/Constants.scala | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/Constants.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/Constants.scala index 83c6f4187..ada1672de 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/Constants.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/Constants.scala @@ -134,7 +134,8 @@ object Constants { val PARTICIPANT_ROLE = "participant_role" val RECIPIENTS = "recipients" val CORRELATIONID = "correlation_id" - val ALLOWED_STATUS_UPDATE = List(QUEUED_STATUS, DISPATCH_STATUS, ERROR_STATUS) + val COMPLETE_RESPONSE = "response.complete" + val ALLOWED_STATUS_UPDATE = List(QUEUED_STATUS, DISPATCH_STATUS, ERROR_STATUS,COMPLETE_RESPONSE) // Notification topic codes val PARTICIPANT_ONBOARD = "notif-participant-onboarded" @@ -150,7 +151,6 @@ object Constants { val SEARCH_COUNT = "count" val SEARCH_ENTITY_COUNT = "entity_counts" val PARTIAL_RESPONSE = "response.partial" - val COMPLETE_RESPONSE = "response.complete" val REQUEST_INITIATED = "request.initiated" From 5d28b28c4a2319c20df7b6ca32e749686200e7d4 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Fri, 27 Oct 2023 15:12:08 +0530 Subject: [PATCH 36/59] Update DispatcherUtil.scala --- .../src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala | 2 ++ 1 file changed, 2 insertions(+) diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala index e1f1f1d2c..fc85d0f23 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala @@ -33,7 +33,9 @@ class DispatcherUtil(config: BaseJobConfig) extends Serializable { Console.println("HCX Token: " + token) httpPost.setHeader("Authorization", "Bearer "+ token) response = httpClient.execute(httpPost); + Console.println("------------------response ---------------" + response) val statusCode = response.getStatusLine().getStatusCode(); + Console.println("--------------status code -------------" + statusCode); val responseBody = EntityUtils.toString(response.getEntity, StandardCharsets.UTF_8) Console.println("Status code: " + statusCode + " :: Response body: " + responseBody); if (config.successCodes.contains(statusCode)) { From 7ee1d1f33b3cc21491ae1601b595cb435e0150a6 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Fri, 27 Oct 2023 15:25:52 +0530 Subject: [PATCH 37/59] Update DispatcherUtil.scala --- .../src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala | 2 -- 1 file changed, 2 deletions(-) diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala index fc85d0f23..e1f1f1d2c 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala @@ -33,9 +33,7 @@ class DispatcherUtil(config: BaseJobConfig) extends Serializable { Console.println("HCX Token: " + token) httpPost.setHeader("Authorization", "Bearer "+ token) response = httpClient.execute(httpPost); - Console.println("------------------response ---------------" + response) val statusCode = response.getStatusLine().getStatusCode(); - Console.println("--------------status code -------------" + statusCode); val responseBody = EntityUtils.toString(response.getEntity, StandardCharsets.UTF_8) Console.println("Status code: " + statusCode + " :: Response body: " + responseBody); if (config.successCodes.contains(statusCode)) { From 413b70d52790e80b03ba710e5d6a05513932833b Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Fri, 27 Oct 2023 16:39:06 +0530 Subject: [PATCH 38/59] feat : removed status --- .../org/swasth/apigateway/filters/AuditValidationFilter.java | 1 - .../src/main/java/org/swasth/apigateway/models/BaseRequest.java | 2 -- .../core/src/main/scala/org/swasth/dp/core/util/Constants.scala | 2 +- 3 files changed, 1 insertion(+), 4 deletions(-) diff --git a/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java b/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java index 7e91896ca..d60fef352 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/filters/AuditValidationFilter.java @@ -3,7 +3,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; import org.springframework.core.io.buffer.DataBuffer; diff --git a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java index 7d1e61fc1..db71fd22d 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java @@ -4,7 +4,6 @@ import lombok.Data; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Value; import org.swasth.apigateway.exception.ClientException; import org.swasth.apigateway.exception.ErrorCodes; import org.swasth.apigateway.utils.DateTimeUtils; @@ -13,7 +12,6 @@ import java.text.MessageFormat; import java.text.ParseException; -import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/Constants.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/Constants.scala index ada1672de..c81d54085 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/Constants.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/Constants.scala @@ -135,7 +135,7 @@ object Constants { val RECIPIENTS = "recipients" val CORRELATIONID = "correlation_id" val COMPLETE_RESPONSE = "response.complete" - val ALLOWED_STATUS_UPDATE = List(QUEUED_STATUS, DISPATCH_STATUS, ERROR_STATUS,COMPLETE_RESPONSE) + val ALLOWED_STATUS_UPDATE = List(QUEUED_STATUS, DISPATCH_STATUS, ERROR_STATUS) // Notification topic codes val PARTICIPANT_ONBOARD = "notif-participant-onboarded" From 63650b0e487aae2bc9c3f6d94845f86430df3a23 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 12:01:06 +0530 Subject: [PATCH 39/59] feat : added logic for error scenario --- .../scala/org/swasth/dp/core/job/BaseProcessFunction.scala | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala index 8e52fdea9..083417890 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala @@ -76,8 +76,11 @@ abstract class BaseProcessFunction[T, R](config: BaseJobConfig) extends ProcessF } def setStatus(event: util.Map[String, AnyRef], status: String): Unit = { - if(Constants.ALLOWED_STATUS_UPDATE.contains(event.get(Constants.HEADERS).asInstanceOf[util.Map[String, AnyRef]].get(Constants.PROTOCOL).asInstanceOf[util.Map[String, AnyRef]].getOrDefault(Constants.HCX_STATUS, ""))) + if (Constants.ALLOWED_STATUS_UPDATE.contains(event.get(Constants.HEADERS).asInstanceOf[util.Map[String, AnyRef]].get(Constants.PROTOCOL).asInstanceOf[util.Map[String, AnyRef]].getOrDefault(Constants.HCX_STATUS, ""))) event.get(Constants.HEADERS).asInstanceOf[util.Map[String, AnyRef]].get(Constants.PROTOCOL).asInstanceOf[util.Map[String, AnyRef]].put(Constants.HCX_STATUS, status) + else { + event.get(Constants.HEADERS).asInstanceOf[util.Map[String, AnyRef]].get(Constants.PROTOCOL).asInstanceOf[util.Map[String, AnyRef]].put(Constants.HCX_STATUS, event.get(Constants.HEADERS).asInstanceOf[util.Map[String, AnyRef]].get(Constants.PROTOCOL).asInstanceOf[util.Map[String, AnyRef]].getOrDefault(Constants.HCX_STATUS, "")) + } } def setErrorDetails(event: util.Map[String, AnyRef], errorDetails: util.Map[String, AnyRef]): Unit ={ From c934be0f3f490371fe7967be2599b96f26bfc441 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 14:53:39 +0530 Subject: [PATCH 40/59] Update BaseRequest.java --- .../src/main/java/org/swasth/apigateway/models/BaseRequest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java index db71fd22d..a4cb44611 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java @@ -188,7 +188,7 @@ public void validateUsingAuditData(List allowedEntitiesForForward, List< } String actionEntity = getEntity(jweRequest.getApiAction()); if (!OPERATIONAL_ENTITIES.contains(actionEntity)) { - if (!correlationFilteredData.isEmpty()) { + if (!correlationFilteredData.isEmpty() && !OPERATIONAL_ENTITIES.contains(getEntity((String) correlationFilteredData.get(0).get(ACTION)))) { List> filteredList = filteredList(correlationFilteredData, correlationDataCloseDays); // validating correlation id at sender context if (filteredList.isEmpty() && correlationFilteredData.get(0).get(HCX_SENDER_CODE).toString().equals(jweRequest.getHcxSenderCode()) && correlationAuditData.get(0).get(CORRELATION_ID).toString().contains(jweRequest.getCorrelationId())) { From 88718d77bf9e794678911abe9a4919329eda526a Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 16:02:08 +0530 Subject: [PATCH 41/59] feat : enhanced search API for identity verification --- hcx-apis/src/main/resources/application.yml | 2 +- .../java/org/swasth/hcx/services/OnboardService.java | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/hcx-apis/src/main/resources/application.yml b/hcx-apis/src/main/resources/application.yml index d97196db8..0ec6dfe31 100644 --- a/hcx-apis/src/main/resources/application.yml +++ b/hcx-apis/src/main/resources/application.yml @@ -32,7 +32,7 @@ kafka: registry: - basePath: ${registry_basePath:http://aa5c04ed467c04ea89789cead03e4275-320353178.ap-south-1.elb.amazonaws.com:8081} + basePath: ${registry_basePath:https://dev-hcx.swasth.app/registry} hcxcode: ${registry_hcxcode:1-d2d56996-1b77-4abb-b9e9-0e6e7343c72e} organisation-api-path: ${registry_api_path:/api/v1/Organisation} user-api-path: ${registry_user_api_path:/api/v1/User} diff --git a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java index 7f18d3eb7..0b1d28e33 100644 --- a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java +++ b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java @@ -701,6 +701,8 @@ public ResponseEntity applicantSearch(Map requestBody, S getMockParticipant(participantList, headers); if (fields != null && fields.toLowerCase().contains(ONBOARD_VALIDATION_PROPERTIES)) getOnboardValidations(participantList); + if (fields != null && fields.toLowerCase().contains(IDENTITY_VERIFICATION)) + addIdentityVerification(participantList); return new ResponseEntity<>(new RegistryResponse(participantList, ORGANISATION), HttpStatus.OK); } @@ -984,6 +986,16 @@ private void addSponsors(List> participantsList) throws Exce filterSponsors(sponsorMap, participantsList); } + private void addIdentityVerification(List> participantsList) throws Exception { + String selectQuery = String.format("SELECT * FROM %S WHERE participant_code IN (%s)", onboardingVerifierTable, getParticipantCodeList(participantsList, PARTICIPANT_CODE)); + ResultSet resultSet = (ResultSet) postgreSQLClient.executeQuery(selectQuery); + Map identityVerification = new HashMap<>(); + while (resultSet.next()) { + identityVerification.put(resultSet.getString(PARTICIPANT_CODE), resultSet.getString("status")); + } + filterDetails(identityVerification, participantsList, IDENTITY_VERIFICATION); + } + private void addCommunicationStatus(List> participantsList) throws Exception { String selectQuery = String.format("SELECT * FROM %s WHERE participant_code IN (%s)", onboardVerificationTable, getParticipantCodeList(participantsList, PARTICIPANT_CODE)); ResultSet resultSet = (ResultSet) postgreSQLClient.executeQuery(selectQuery); From 917b4f68f9ed5959c4b6a6db9590358dfc90c0cb Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 16:43:11 +0530 Subject: [PATCH 42/59] feta : added testcases --- .../org/swasth/hcx/models/Participant.java | 8 ++-- .../swasth/hcx/models/ParticipantTests.java | 39 ++++++++++++++++++- 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java index d66285398..ab2a833c6 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java @@ -43,14 +43,14 @@ public String generateCode(String fieldSeparator, String hcxInstanceName) { private String getRoleAppender() { if (getRoles().stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)) { for (String role : getRoles()) { - if (role.startsWith("provider.")) { - return role.substring(9, 13); - } + return role.substring(9, 13); } } else if (getRoles().contains("payor")) { return "payr"; - } else if(getRoles().contains("bsp")){ + } else if (getRoles().contains("bsp")) { return "bsp"; + } else if (getRoles().contains("provider")){ + return "hosp"; } return getRoles().get(0); } diff --git a/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java b/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java index bb31566e4..43e3abd57 100644 --- a/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java +++ b/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java @@ -20,7 +20,7 @@ void generate_participant_code_with_payor_role() { void generate_participant_code_with_provider_role() { Participant participant = new Participant(getProviderRequestBody()); String code = participant.generateCode("_", "swasth-hcx"); - Assertions.assertEquals("provider_rakshi_012345@swasth-hcx", code); + Assertions.assertEquals("hosp_rakshi_012345@swasth-hcx", code); } @Test @@ -35,7 +35,13 @@ void generate_hcx_admin_code(){ String code = participant.generateCode("_", "swasth-hcx"); Assertions.assertEquals("hie/hio.hcx_rakshi_012345@swasth-hcx",code); } - + @Test + void generate_bsp_role_user(){ + Participant participant = new Participant(getBSPRequestBody()); + String code = participant.generateCode("_", "swasth-hcx"); + System.out.println(code); + Assertions.assertEquals("bsp_rakshi_012345@swasth-hcx",code); + } private Map getPayorRequestBody() { Map obj = new HashMap<>(); obj.put("participant_name", "Rakshith Insurance"); @@ -151,4 +157,33 @@ private Map getHCXAdminRequestBody() { obj.put("encryption_cert", "urn:isbn:0-4234"); return obj; } + + private Map getBSPRequestBody() { + Map obj = new HashMap<>(); + obj.put("participant_name", "Rakshith Hospital"); + obj.put("primary_mobile", "9493347239"); + obj.put("primary_email", "rakshith123@gmail.com"); + obj.put("roles", new ArrayList<>(Collections.singleton("bsp"))); + obj.put("applicant_code", "012345"); + obj.put("address", new HashMap<>() {{ + put("plot", "5-4-199"); + put("street", "road no 12"); + put("landmark", ""); + put("village", "Nampally"); + put("district", "Hyd"); + put("state", "Telangana"); + put("pincode", "500805"); + }}); + obj.put("phone", new ArrayList<>(Collections.singleton("040-387658992"))); + obj.put("status", "Created"); + obj.put("endpoint_url", "http://localhost:8095"); + obj.put("payment_details", new HashMap<>() {{ + put("account_number", "4707890099809809"); + put("ifsc_code", "ICICLE"); + }}); + obj.put("signing_cert_path", "urn:isbn:0-476-27557-4"); + obj.put("linked_registry_codes", new ArrayList<>(Collections.singleton("22344"))); + obj.put("encryption_cert", "urn:isbn:0-4234"); + return obj; + } } From ab3aeefb3f076289733997fe6b514f44673ce116 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 16:47:59 +0530 Subject: [PATCH 43/59] Update BaseRequest.java --- .../src/main/java/org/swasth/apigateway/models/BaseRequest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java index a4cb44611..db71fd22d 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java @@ -188,7 +188,7 @@ public void validateUsingAuditData(List allowedEntitiesForForward, List< } String actionEntity = getEntity(jweRequest.getApiAction()); if (!OPERATIONAL_ENTITIES.contains(actionEntity)) { - if (!correlationFilteredData.isEmpty() && !OPERATIONAL_ENTITIES.contains(getEntity((String) correlationFilteredData.get(0).get(ACTION)))) { + if (!correlationFilteredData.isEmpty()) { List> filteredList = filteredList(correlationFilteredData, correlationDataCloseDays); // validating correlation id at sender context if (filteredList.isEmpty() && correlationFilteredData.get(0).get(HCX_SENDER_CODE).toString().equals(jweRequest.getHcxSenderCode()) && correlationAuditData.get(0).get(CORRELATION_ID).toString().contains(jweRequest.getCorrelationId())) { From 48ca87d98da21a2fb56dbd36151e4e1992a42cb8 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 17:04:09 +0530 Subject: [PATCH 44/59] feat : testcases --- .../src/main/java/org/swasth/hcx/models/Participant.java | 6 ++---- .../test/java/org/swasth/hcx/models/ParticipantTests.java | 2 +- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java index ab2a833c6..fe1e119db 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java @@ -42,14 +42,12 @@ public String generateCode(String fieldSeparator, String hcxInstanceName) { private String getRoleAppender() { if (getRoles().stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)) { - for (String role : getRoles()) { - return role.substring(9, 13); - } + return getRoles().get(0).substring(9, 13); } else if (getRoles().contains("payor")) { return "payr"; } else if (getRoles().contains("bsp")) { return "bsp"; - } else if (getRoles().contains("provider")){ + } else if (getRoles().contains("provider")) { return "hosp"; } return getRoles().get(0); diff --git a/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java b/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java index 43e3abd57..5e03265cc 100644 --- a/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java +++ b/hcx-apis/src/test/java/org/swasth/hcx/models/ParticipantTests.java @@ -105,7 +105,7 @@ private Map getProviderSpecificRequestBody() { obj.put("participant_name", "Rakshith Hospital"); obj.put("primary_mobile", "9493347239"); obj.put("primary_email", "rakshith123@gmail.com"); - obj.put("roles", new ArrayList<>(Collections.singleton("provider.hospital"))); + obj.put("roles", Arrays.asList("provider.hospital","provider.clinic")); obj.put("applicant_code", "012345"); obj.put("address", new HashMap<>() {{ put("plot", "5-4-199"); From fb665e1744b1840c17d844db339047ab4211e1bc Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 17:22:28 +0530 Subject: [PATCH 45/59] Update BaseRequest.java --- .../java/org/swasth/apigateway/models/BaseRequest.java | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java index db71fd22d..cba8e4235 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java @@ -362,16 +362,10 @@ public String getEntity(String path) { private List> filteredList(List> correlationFilteredData, int days) { return correlationFilteredData.stream() .filter(map -> COMPLETE_STATUS.equals(map.get(STATUS))) - .filter(map -> { - try { - return isWithinLastDays((Long) map.get(UPDATED_TIME), days); - } catch (ParseException e) { - throw new RuntimeException(e); - } - }).collect(Collectors.toList()); + .filter(map -> isWithinLastDays((Long) map.get(UPDATED_TIME), days)).collect(Collectors.toList()); } - private boolean isWithinLastDays(long timestamp ,int days) throws ParseException { + private boolean isWithinLastDays(long timestamp ,int days) { Date currentDate = new Date(); long differenceInMillis = currentDate.getTime() - timestamp; long daysDifference = TimeUnit.DAYS.convert(differenceInMillis, TimeUnit.MILLISECONDS); From 2646f6ab3cea6bcca5e374c59b2353e0b30affe0 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 18:05:36 +0530 Subject: [PATCH 46/59] feat : added loggers --- .../org/swasth/dp/core/function/BaseDispatcherFunction.scala | 2 ++ .../scala/org/swasth/dp/core/job/BaseProcessFunction.scala | 3 --- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala index 822059d71..72be95fbe 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala @@ -168,6 +168,8 @@ abstract class BaseDispatcherFunction(config: BaseJobConfig) if (!result.retry && !result.success) { dispatchError(payloadRefId, event, result, correlationId, senderCtx, context, metrics) } + Console.println("-----The event going to updated -----------------------------------") + Console.println("event ---------" + event) audit(event, context, metrics) } } diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala index 083417890..799b28c93 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala @@ -78,9 +78,6 @@ abstract class BaseProcessFunction[T, R](config: BaseJobConfig) extends ProcessF def setStatus(event: util.Map[String, AnyRef], status: String): Unit = { if (Constants.ALLOWED_STATUS_UPDATE.contains(event.get(Constants.HEADERS).asInstanceOf[util.Map[String, AnyRef]].get(Constants.PROTOCOL).asInstanceOf[util.Map[String, AnyRef]].getOrDefault(Constants.HCX_STATUS, ""))) event.get(Constants.HEADERS).asInstanceOf[util.Map[String, AnyRef]].get(Constants.PROTOCOL).asInstanceOf[util.Map[String, AnyRef]].put(Constants.HCX_STATUS, status) - else { - event.get(Constants.HEADERS).asInstanceOf[util.Map[String, AnyRef]].get(Constants.PROTOCOL).asInstanceOf[util.Map[String, AnyRef]].put(Constants.HCX_STATUS, event.get(Constants.HEADERS).asInstanceOf[util.Map[String, AnyRef]].get(Constants.PROTOCOL).asInstanceOf[util.Map[String, AnyRef]].getOrDefault(Constants.HCX_STATUS, "")) - } } def setErrorDetails(event: util.Map[String, AnyRef], errorDetails: util.Map[String, AnyRef]): Unit ={ From 74aac6b2af70f48f7f5823675b9cb5de04a97706 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 18:20:59 +0530 Subject: [PATCH 47/59] Update BaseDispatcherFunction.scala --- .../org/swasth/dp/core/function/BaseDispatcherFunction.scala | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala index 72be95fbe..58112e681 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala @@ -165,8 +165,12 @@ abstract class BaseDispatcherFunction(config: BaseJobConfig) Console.println("Event is updated for retrying..") } } + Console.println("! result.retry-----" + !result.retry) + Console.println("! result.succes----------" + !result.success) + Console.println("-------result.eroor ---------" + result.error) if (!result.retry && !result.success) { dispatchError(payloadRefId, event, result, correlationId, senderCtx, context, metrics) + Console.println("----------event -------------" + event) } Console.println("-----The event going to updated -----------------------------------") Console.println("event ---------" + event) From de53017a3bd693eea3d62ccebb3086ec45f3b109 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 18:38:40 +0530 Subject: [PATCH 48/59] Update BaseDispatcherFunction.scala --- .../dp/core/function/BaseDispatcherFunction.scala | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala index 58112e681..edf34a812 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala @@ -150,6 +150,7 @@ abstract class BaseDispatcherFunction(config: BaseJobConfig) setStatus(event, Constants.DISPATCH_STATUS) metrics.incCounter(metric = config.dispatcherSuccessCount) generateSuccessMetrics(event, metrics) + audit(event, context, metrics) } if (result.retry) { var retryCount: Int = 0 @@ -164,17 +165,12 @@ abstract class BaseDispatcherFunction(config: BaseJobConfig) generateRetryMetrics(event, metrics) Console.println("Event is updated for retrying..") } + audit(event, context, metrics) } - Console.println("! result.retry-----" + !result.retry) - Console.println("! result.succes----------" + !result.success) - Console.println("-------result.eroor ---------" + result.error) if (!result.retry && !result.success) { dispatchError(payloadRefId, event, result, correlationId, senderCtx, context, metrics) - Console.println("----------event -------------" + event) + audit(event, context, metrics) } - Console.println("-----The event going to updated -----------------------------------") - Console.println("event ---------" + event) - audit(event, context, metrics) } } } catch { From a23fa36e55cdc5c4d25142146b49d2c21e48e442 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 18:58:09 +0530 Subject: [PATCH 49/59] feat : added loggers --- .../org/swasth/dp/core/function/BaseDispatcherFunction.scala | 4 ++++ .../main/scala/org/swasth/dp/core/util/DispatcherUtil.scala | 1 + 2 files changed, 5 insertions(+) diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala index edf34a812..a4696c7b2 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala @@ -150,6 +150,7 @@ abstract class BaseDispatcherFunction(config: BaseJobConfig) setStatus(event, Constants.DISPATCH_STATUS) metrics.incCounter(metric = config.dispatcherSuccessCount) generateSuccessMetrics(event, metrics) + Console.println("-------------It is at the success event--------------") audit(event, context, metrics) } if (result.retry) { @@ -158,6 +159,7 @@ abstract class BaseDispatcherFunction(config: BaseJobConfig) retryCount = event.get(Constants.RETRY_INDEX).asInstanceOf[Int] if (!config.allowedEntitiesForRetry.contains(getEntity(event.get(Constants.ACTION).asInstanceOf[String])) || retryCount == config.maxRetry) { dispatchError(payloadRefId, event, result, correlationId, senderCtx, context, metrics) + Console.println("---------it wenr allowed entitties for retry -----------") } else if (retryCount < config.maxRetry) { updateDBStatus(payloadRefId, Constants.REQ_RETRY) setStatus(event, Constants.QUEUED_STATUS) @@ -165,10 +167,12 @@ abstract class BaseDispatcherFunction(config: BaseJobConfig) generateRetryMetrics(event, metrics) Console.println("Event is updated for retrying..") } + Console.println("---------it is at the retry event -------------------") audit(event, context, metrics) } if (!result.retry && !result.success) { dispatchError(payloadRefId, event, result, correlationId, senderCtx, context, metrics) + Console.println("------------it is at the error event --------------") audit(event, context, metrics) } } diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala index e1f1f1d2c..79afd4d68 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala @@ -39,6 +39,7 @@ class DispatcherUtil(config: BaseJobConfig) extends Serializable { if (config.successCodes.contains(statusCode)) { DispatcherResult(true, statusCode, null, false) } else if (config.errorCodes.contains(statusCode)) { + Console.println("--------it is going inside the errorcodes----------") val errorResponse: ErrorResponse = errorMessageProcess(responseBody) DispatcherResult(false, statusCode, Option(errorResponse), false) } else { From d4001fd7692b5f2b0c53ec3e6d4a9fc9b4c59a34 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 19:10:52 +0530 Subject: [PATCH 50/59] fix : added loggers --- hcx-pipeline-jobs/core/src/main/resources/base-config.conf | 2 +- .../org/swasth/dp/core/function/BaseDispatcherFunction.scala | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/hcx-pipeline-jobs/core/src/main/resources/base-config.conf b/hcx-pipeline-jobs/core/src/main/resources/base-config.conf index a186d5891..80b843f78 100644 --- a/hcx-pipeline-jobs/core/src/main/resources/base-config.conf +++ b/hcx-pipeline-jobs/core/src/main/resources/base-config.conf @@ -76,7 +76,7 @@ postgres { } max.retry = 3 -allowedEntitiesForRetry = ["coverageeligibility", "preauth", "claim"] +allowedEntitiesForRetry = ["coverageeligibility", "preauth", "claim", "communication"] audit { index = "hcx_audit" diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala index a4696c7b2..a44ae3adc 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala @@ -157,6 +157,7 @@ abstract class BaseDispatcherFunction(config: BaseJobConfig) var retryCount: Int = 0 if (event.containsKey(Constants.RETRY_INDEX)) retryCount = event.get(Constants.RETRY_INDEX).asInstanceOf[Int] + Console.println(getEntity(event.get(Constants.ACTION).asInstanceOf[String])) if (!config.allowedEntitiesForRetry.contains(getEntity(event.get(Constants.ACTION).asInstanceOf[String])) || retryCount == config.maxRetry) { dispatchError(payloadRefId, event, result, correlationId, senderCtx, context, metrics) Console.println("---------it wenr allowed entitties for retry -----------") From d2f98ca9520e6548d67df590537b9d3b06ffe4bf Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 19:23:47 +0530 Subject: [PATCH 51/59] Update BaseDispatcherFunction.scala --- .../swasth/dp/core/function/BaseDispatcherFunction.scala | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala index a44ae3adc..add32550a 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala @@ -160,16 +160,16 @@ abstract class BaseDispatcherFunction(config: BaseJobConfig) Console.println(getEntity(event.get(Constants.ACTION).asInstanceOf[String])) if (!config.allowedEntitiesForRetry.contains(getEntity(event.get(Constants.ACTION).asInstanceOf[String])) || retryCount == config.maxRetry) { dispatchError(payloadRefId, event, result, correlationId, senderCtx, context, metrics) - Console.println("---------it wenr allowed entitties for retry -----------") + Console.println(event) + audit(event, context, metrics) } else if (retryCount < config.maxRetry) { updateDBStatus(payloadRefId, Constants.REQ_RETRY) setStatus(event, Constants.QUEUED_STATUS) metrics.incCounter(metric = config.dispatcherRetryCount) generateRetryMetrics(event, metrics) Console.println("Event is updated for retrying..") + audit(event, context, metrics) } - Console.println("---------it is at the retry event -------------------") - audit(event, context, metrics) } if (!result.retry && !result.success) { dispatchError(payloadRefId, event, result, correlationId, senderCtx, context, metrics) From 8e6a22f55bbb331b34b0fb159a73d302c50784d8 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 19:35:15 +0530 Subject: [PATCH 52/59] feat : removed loggers --- .../core/src/main/resources/base-config.conf | 2 +- .../swasth/dp/core/function/BaseDispatcherFunction.scala | 9 +-------- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/hcx-pipeline-jobs/core/src/main/resources/base-config.conf b/hcx-pipeline-jobs/core/src/main/resources/base-config.conf index 80b843f78..a186d5891 100644 --- a/hcx-pipeline-jobs/core/src/main/resources/base-config.conf +++ b/hcx-pipeline-jobs/core/src/main/resources/base-config.conf @@ -76,7 +76,7 @@ postgres { } max.retry = 3 -allowedEntitiesForRetry = ["coverageeligibility", "preauth", "claim", "communication"] +allowedEntitiesForRetry = ["coverageeligibility", "preauth", "claim"] audit { index = "hcx_audit" diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala index add32550a..822059d71 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala @@ -150,32 +150,25 @@ abstract class BaseDispatcherFunction(config: BaseJobConfig) setStatus(event, Constants.DISPATCH_STATUS) metrics.incCounter(metric = config.dispatcherSuccessCount) generateSuccessMetrics(event, metrics) - Console.println("-------------It is at the success event--------------") - audit(event, context, metrics) } if (result.retry) { var retryCount: Int = 0 if (event.containsKey(Constants.RETRY_INDEX)) retryCount = event.get(Constants.RETRY_INDEX).asInstanceOf[Int] - Console.println(getEntity(event.get(Constants.ACTION).asInstanceOf[String])) if (!config.allowedEntitiesForRetry.contains(getEntity(event.get(Constants.ACTION).asInstanceOf[String])) || retryCount == config.maxRetry) { dispatchError(payloadRefId, event, result, correlationId, senderCtx, context, metrics) - Console.println(event) - audit(event, context, metrics) } else if (retryCount < config.maxRetry) { updateDBStatus(payloadRefId, Constants.REQ_RETRY) setStatus(event, Constants.QUEUED_STATUS) metrics.incCounter(metric = config.dispatcherRetryCount) generateRetryMetrics(event, metrics) Console.println("Event is updated for retrying..") - audit(event, context, metrics) } } if (!result.retry && !result.success) { dispatchError(payloadRefId, event, result, correlationId, senderCtx, context, metrics) - Console.println("------------it is at the error event --------------") - audit(event, context, metrics) } + audit(event, context, metrics) } } } catch { From df7303f29e7350785c6cc04a50de704fc64a4345 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 19:48:49 +0530 Subject: [PATCH 53/59] feat : error stat --- hcx-pipeline-jobs/core/src/main/resources/base-config.conf | 2 +- .../org/swasth/dp/core/function/BaseDispatcherFunction.scala | 2 +- .../scala/org/swasth/dp/core/job/BaseProcessFunction.scala | 5 +++++ .../main/scala/org/swasth/dp/core/util/DispatcherUtil.scala | 1 - 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/hcx-pipeline-jobs/core/src/main/resources/base-config.conf b/hcx-pipeline-jobs/core/src/main/resources/base-config.conf index a186d5891..80b843f78 100644 --- a/hcx-pipeline-jobs/core/src/main/resources/base-config.conf +++ b/hcx-pipeline-jobs/core/src/main/resources/base-config.conf @@ -76,7 +76,7 @@ postgres { } max.retry = 3 -allowedEntitiesForRetry = ["coverageeligibility", "preauth", "claim"] +allowedEntitiesForRetry = ["coverageeligibility", "preauth", "claim", "communication"] audit { index = "hcx_audit" diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala index 822059d71..4b280cb5c 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/function/BaseDispatcherFunction.scala @@ -190,7 +190,7 @@ abstract class BaseDispatcherFunction(config: BaseJobConfig) private def dispatchError(payloadRefId: String, event: util.Map[String, AnyRef], result: DispatcherResult, correlationId: String, senderCtx: util.Map[String, AnyRef], context: ProcessFunction[util.Map[String, AnyRef], util.Map[String, AnyRef]]#Context, metrics: Metrics): Unit = { updateDBStatus(payloadRefId, Constants.ERROR_STATUS) - setStatus(event, Constants.ERROR_STATUS) + setErrorStatus(event, Constants.ERROR_STATUS) setErrorDetails(event, createErrorMap(result.error)) metrics.incCounter(metric = config.dispatcherFailedCount) generateFailedMetrics(event, metrics) diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala index 799b28c93..91c93b9f3 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala @@ -80,6 +80,11 @@ abstract class BaseProcessFunction[T, R](config: BaseJobConfig) extends ProcessF event.get(Constants.HEADERS).asInstanceOf[util.Map[String, AnyRef]].get(Constants.PROTOCOL).asInstanceOf[util.Map[String, AnyRef]].put(Constants.HCX_STATUS, status) } + def setErrorStatus(event: util.Map[String, AnyRef], status: String): Unit = { + Console.println("---it came in errors map ------") + event.get(Constants.HEADERS).asInstanceOf[util.Map[String, AnyRef]].get(Constants.PROTOCOL).asInstanceOf[util.Map[String, AnyRef]].put(Constants.HCX_STATUS, status) + } + def setErrorDetails(event: util.Map[String, AnyRef], errorDetails: util.Map[String, AnyRef]): Unit ={ event.get(Constants.HEADERS).asInstanceOf[util.Map[String, AnyRef]].get(Constants.PROTOCOL).asInstanceOf[util.Map[String, AnyRef]].put(Constants.ERROR_DETAILS, errorDetails) } diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala index 79afd4d68..e1f1f1d2c 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/util/DispatcherUtil.scala @@ -39,7 +39,6 @@ class DispatcherUtil(config: BaseJobConfig) extends Serializable { if (config.successCodes.contains(statusCode)) { DispatcherResult(true, statusCode, null, false) } else if (config.errorCodes.contains(statusCode)) { - Console.println("--------it is going inside the errorcodes----------") val errorResponse: ErrorResponse = errorMessageProcess(responseBody) DispatcherResult(false, statusCode, Option(errorResponse), false) } else { From 55babf6a2b9ab8e46f9f7c42ff44df6e72507b67 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Mon, 30 Oct 2023 21:54:20 +0530 Subject: [PATCH 54/59] feat : removed loggers --- .../main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala | 1 - 1 file changed, 1 deletion(-) diff --git a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala index 91c93b9f3..48d2a3694 100644 --- a/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala +++ b/hcx-pipeline-jobs/core/src/main/scala/org/swasth/dp/core/job/BaseProcessFunction.scala @@ -81,7 +81,6 @@ abstract class BaseProcessFunction[T, R](config: BaseJobConfig) extends ProcessF } def setErrorStatus(event: util.Map[String, AnyRef], status: String): Unit = { - Console.println("---it came in errors map ------") event.get(Constants.HEADERS).asInstanceOf[util.Map[String, AnyRef]].get(Constants.PROTOCOL).asInstanceOf[util.Map[String, AnyRef]].put(Constants.HCX_STATUS, status) } From c58f4bf5c32dda70b2b6faeb07561842f1c6b660 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Tue, 31 Oct 2023 12:43:54 +0530 Subject: [PATCH 55/59] Update Participant.java --- .../main/java/org/swasth/hcx/models/Participant.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java index fe1e119db..1d82478e0 100644 --- a/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java +++ b/hcx-apis/src/main/java/org/swasth/hcx/models/Participant.java @@ -41,8 +41,16 @@ public String generateCode(String fieldSeparator, String hcxInstanceName) { } private String getRoleAppender() { - if (getRoles().stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)) { - return getRoles().get(0).substring(9, 13); + if (getRoles().contains("provider.hospital")) { + return "hosp"; + } else if (getRoles().contains("provider.clinic")) { + return "clinic"; + } else if (getRoles().contains("provider.practitioner")) { + return "prac"; + } else if (getRoles().contains("provider.diagnostics")) { + return "diag"; + } else if (getRoles().contains("provider.pharmacy")) { + return "pharm"; } else if (getRoles().contains("payor")) { return "payr"; } else if (getRoles().contains("bsp")) { From 348f5b1c97b7421f2bf684dec83966321f171783 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Tue, 31 Oct 2023 12:59:17 +0530 Subject: [PATCH 56/59] feat : added api in api0gateway --- api-gateway/src/main/resources/application.yaml | 3 ++- api-gateway/src/main/resources/rbac.yaml | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/api-gateway/src/main/resources/application.yaml b/api-gateway/src/main/resources/application.yaml index 3c994f7ee..291b6db58 100644 --- a/api-gateway/src/main/resources/application.yaml +++ b/api-gateway/src/main/resources/application.yaml @@ -201,8 +201,9 @@ spring: - RewritePath=/${version.external08}/applicant/(?/?.*), /${version.internal}/applicant/$\{segment} - RewritePath=/${version.external08}/onboard/user/(?/?.*), /${version.internal}/onboard/user/$\{segment} - RewritePath=/${version.external08}/onboard/applicant/(?/?.*), /${version.internal}/onboard/applicant/$\{segment} + - RewritePath=/${version.external08}/api-access/secret/(?/?.*), /${version.internal}/api-access/secret/$\{segment} predicates: - - Path=/${version.external08}/participant/verify, /${version.external08}/participant/verify/identity, /${version.external08}/participant/verification/link/send, /${version.external08}/participant/onboard/update, /${version.external08}/applicant/getinfo, /${version.external08}/applicant/verify,/${version.external07}/applicant/search*,/${version.external08}/applicant/search*,/url/*, /${version.external08}/onboard/user/invite, /${version.external08}/onboard/user/invite/accept, /${version.external08}/onboard/user/invite/reject, /${version.external08}/onboard/applicant/password/generate + - Path=/${version.external08}/participant/verify, /${version.external08}/participant/verify/identity, /${version.external08}/participant/verification/link/send, /${version.external08}/participant/onboard/update, /${version.external08}/applicant/getinfo, /${version.external08}/applicant/verify,/${version.external07}/applicant/search*,/${version.external08}/applicant/search*,/url/*, /${version.external08}/onboard/user/invite, /${version.external08}/onboard/user/invite/accept, /${version.external08}/onboard/user/invite/reject, /${version.external08}/onboard/applicant/password/generate, /${version.external08}/api-access/secret/generate - id: hcx-mock-service-route uri: ${hcx-mock-service.basePath} diff --git a/api-gateway/src/main/resources/rbac.yaml b/api-gateway/src/main/resources/rbac.yaml index ca0703adf..c434176ac 100644 --- a/api-gateway/src/main/resources/rbac.yaml +++ b/api-gateway/src/main/resources/rbac.yaml @@ -262,6 +262,7 @@ rbac: - /v0.8/participant/update - /v0.8/onboard/applicant/password/generate - /v0.8/participant/onboard/update + - /v0.8/api-access/secret/generate regexPaths: - /v0.8/user/** - /v0.8/participant/user/** From d45188f92205511c4f7b208613952f9ea6718fcb Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Tue, 7 Nov 2023 20:07:35 +0530 Subject: [PATCH 57/59] feat : added brackets --- .../src/main/java/org/swasth/apigateway/models/BaseRequest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java index cba8e4235..f10f606e0 100644 --- a/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java +++ b/api-gateway/src/main/java/org/swasth/apigateway/models/BaseRequest.java @@ -184,7 +184,7 @@ public void validateUsingAuditData(List allowedEntitiesForForward, List< for (Map audit : correlationAuditData) { String action = (String) audit.get(ACTION); String entity = getEntity(action); - validateCondition(!OPERATIONAL_ENTITIES.contains(entity) && action.contains("on_") && (((List) audit.get(RECIPIENT_ROLE)).contains(PROVIDER)) || ((List) audit.get(RECIPIENT_ROLE)).stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains) && audit.get(STATUS).equals(COMPLETE_STATUS), ErrorCodes.ERR_INVALID_CORRELATION_ID, CLOSED_CYCLE_MSG); + validateCondition(!OPERATIONAL_ENTITIES.contains(entity) && action.contains("on_") && ((((List) audit.get(RECIPIENT_ROLE)).contains(PROVIDER)) || ((List) audit.get(RECIPIENT_ROLE)).stream().anyMatch(PROVIDER_SPECIFIC_ROLES::contains)) && audit.get(STATUS).equals(COMPLETE_STATUS), ErrorCodes.ERR_INVALID_CORRELATION_ID, CLOSED_CYCLE_MSG); } String actionEntity = getEntity(jweRequest.getApiAction()); if (!OPERATIONAL_ENTITIES.contains(actionEntity)) { From 4ba8701e2d26eea5a85ccc5a2f8feebc909f0f23 Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Tue, 14 Nov 2023 16:48:45 +0530 Subject: [PATCH 58/59] feat : resend verification issue --- .../java/org/swasth/hcx/controllers/v1/OnboardController.java | 4 ++-- .../src/main/java/org/swasth/hcx/services/OnboardService.java | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/hcx-onboard/src/main/java/org/swasth/hcx/controllers/v1/OnboardController.java b/hcx-onboard/src/main/java/org/swasth/hcx/controllers/v1/OnboardController.java index cae631a94..5d14781c4 100644 --- a/hcx-onboard/src/main/java/org/swasth/hcx/controllers/v1/OnboardController.java +++ b/hcx-onboard/src/main/java/org/swasth/hcx/controllers/v1/OnboardController.java @@ -39,8 +39,8 @@ public ResponseEntity sendVerificationLink(@RequestBody Map sendVerificationLink(Map requestBo } String query = String.format("SELECT regenerate_count, last_regenerate_date, email_verified, phone_verified FROM %s WHERE participant_code='%s'", onboardVerificationTable, requestBody.get(PARTICIPANT_CODE)); ResultSet result = (ResultSet) postgreSQLClient.executeQuery(query); - if (!result.next()) { + boolean hasResult = result.next(); + if (!hasResult) { throw new ClientException(ErrorCodes.ERR_INVALID_REQUEST, INVALID_EMAIL); } int regenerateCount = result.getInt("regenerate_count"); From 089f83cd3a0e3b96aab5da7b1e275d3d41ab844a Mon Sep 17 00:00:00 2001 From: Abhishek gaddi <110591073+AbhiGaddi@users.noreply.github.com> Date: Tue, 14 Nov 2023 17:07:15 +0530 Subject: [PATCH 59/59] Update OnboardService.java --- .../src/main/java/org/swasth/hcx/services/OnboardService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java index 8ff59d255..f52a78022 100644 --- a/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java +++ b/hcx-onboard/src/main/java/org/swasth/hcx/services/OnboardService.java @@ -314,7 +314,7 @@ public ResponseEntity sendVerificationLink(Map requestBo ResultSet result = (ResultSet) postgreSQLClient.executeQuery(query); boolean hasResult = result.next(); if (!hasResult) { - throw new ClientException(ErrorCodes.ERR_INVALID_REQUEST, INVALID_EMAIL); + throw new ClientException(ErrorCodes.ERR_INVALID_REQUEST, String.format("The participant information corresponding to this %s is not present in the database.", requestBody.get(PARTICIPANT_CODE))); } int regenerateCount = result.getInt("regenerate_count"); LocalDate lastRegenerateDate = result.getObject("last_regenerate_date", LocalDate.class);