From 41a4bc03cf78e17e6390a6d5c27d26ac06224773 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Fri, 13 Dec 2024 18:38:00 +0530 Subject: [PATCH 01/26] Modified tnxId keyword to txnId --- .../java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java | 2 +- .../wipro/fhir/data/v3/abhaCard/RequestOTPEnrollment.java | 2 +- .../ndhm/CreateHealthID_Aadhaar_NDHMServiceImpl.java | 8 ++++---- .../fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java | 8 ++++---- .../fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java b/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java index 2536f29..bde1e58 100644 --- a/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java +++ b/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java @@ -8,7 +8,7 @@ public class LoginMethod { private String loginId; private String loginMethod; private String pId; - private String tnxId; + private String txnId; private String mobileNumber; private String createdBy; private int providerServiceMapId; diff --git a/src/main/java/com/wipro/fhir/data/v3/abhaCard/RequestOTPEnrollment.java b/src/main/java/com/wipro/fhir/data/v3/abhaCard/RequestOTPEnrollment.java index 8eefe19..b49cd0a 100644 --- a/src/main/java/com/wipro/fhir/data/v3/abhaCard/RequestOTPEnrollment.java +++ b/src/main/java/com/wipro/fhir/data/v3/abhaCard/RequestOTPEnrollment.java @@ -5,7 +5,7 @@ @Data public class RequestOTPEnrollment { - String tnxId; + String txnId; String[] scope; String loginHint; String loginId; diff --git a/src/main/java/com/wipro/fhir/service/ndhm/CreateHealthID_Aadhaar_NDHMServiceImpl.java b/src/main/java/com/wipro/fhir/service/ndhm/CreateHealthID_Aadhaar_NDHMServiceImpl.java index 5a43aa2..0a676d7 100644 --- a/src/main/java/com/wipro/fhir/service/ndhm/CreateHealthID_Aadhaar_NDHMServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/ndhm/CreateHealthID_Aadhaar_NDHMServiceImpl.java @@ -177,7 +177,7 @@ public String verifyOTP(String request) throws FHIRException { JsonParser jsnParser = new JsonParser(); JsonElement jsnElmnt = jsnParser.parse(responseStrLogin); jsnOBJ = jsnElmnt.getAsJsonObject(); - resMap.put("tnxId", jsnOBJ.get("txnId").getAsString()); + resMap.put("txnId", jsnOBJ.get("txnId").getAsString()); res = new Gson().toJson(resMap); } else throw new FHIRException("NDHM_FHIR Error while verifying the OTP"); @@ -210,7 +210,7 @@ public String checkAndGenerateMobileOTP(String request) throws FHIRException { jsnOBJ = jsnElmnt.getAsJsonObject(); //String mobileLinked = jsnOBJ.get("mobileLinked").getAsString(); resMap.put("mobileLinked", jsnOBJ.get("mobileLinked").getAsString()); - resMap.put("tnxId", jsnOBJ.get("txnId").getAsString()); + resMap.put("txnId", jsnOBJ.get("txnId").getAsString()); res = new Gson().toJson(resMap); } else @@ -242,7 +242,7 @@ public String verifyMobileOTP(String request) throws FHIRException { JsonParser jsnParser = new JsonParser(); JsonElement jsnElmnt = jsnParser.parse(responseStrLogin); jsnOBJ = jsnElmnt.getAsJsonObject(); - resMap.put("tnxId", jsnOBJ.get("txnId").getAsString()); + resMap.put("txnId", jsnOBJ.get("txnId").getAsString()); res = new Gson().toJson(resMap); } else throw new FHIRException("NDHM_FHIR Error while verifiying mobile OTP"); @@ -367,7 +367,7 @@ public String generateMobileOTP(String request) throws FHIRException { jsnOBJ = jsnElmnt.getAsJsonObject(); // String mobileLinked = jsnOBJ.get("mobileLinked").getAsString(); // resMap.put("mobileLinked", jsnOBJ.get("mobileLinked").getAsString()); - resMap.put("tnxId", jsnOBJ.get("txnId").getAsString()); + resMap.put("txnId", jsnOBJ.get("txnId").getAsString()); res = new Gson().toJson(resMap); } else diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java index 40cdb4e..727231b 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java @@ -114,7 +114,7 @@ public String getOtpForEnrollment(String request) throws FHIRException { reqOtpEnrollment.setScope(new String[] { "abha-enrol" }); } else if ("MOBILE".equalsIgnoreCase(loginMethod.getLoginMethod())) { reqOtpEnrollment.setLoginId(encryptedLoginId); - reqOtpEnrollment.setTnxId(loginMethod.getTnxId()); + reqOtpEnrollment.setTxnId(loginMethod.getTxnId()); reqOtpEnrollment.setOtpSystem("abdm"); reqOtpEnrollment.setLoginHint("mobile"); reqOtpEnrollment.setScope(new String[] { "abha-enrol", "mobile-verify" }); @@ -276,7 +276,7 @@ public String verifyAuthByAbdm(String request) throws FHIRException { String formattedTimestamp = now.format(formatter); otp.setTimestamp(formattedTimestamp); - otp.setTxnId(loginMethod.getTnxId()); + otp.setTxnId(loginMethod.getTxnId()); otp.setOtpValue(encryptedLoginId); String[] scope; @@ -327,7 +327,7 @@ public String formAadharEnrollReqObjByAadhar(LoginMethod loginData, String encry String formattedTimestamp = now.format(formatter); otp.setTimestamp(formattedTimestamp); - otp.setTxnId(loginData.getTnxId()); + otp.setTxnId(loginData.getTxnId()); otp.setOtpValue(encryptedLoginId); otp.setMobile(loginData.getMobileNumber()); @@ -359,7 +359,7 @@ public String formAadharEnrollReqObjByBiometric(LoginMethod loginData, String en String formattedTimestamp = now.format(formatter); bio.setTimestamp(formattedTimestamp); - bio.setTxnId(loginData.getTnxId()); + bio.setTxnId(loginData.getTxnId()); bio.setAadhaar(encryptedLoginId); bio.setFingerPrintAuthPid(loginData.getPId()); diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java index e33fc6a..3263912 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java @@ -170,7 +170,7 @@ public String verifyAbhaLogin(String request) throws FHIRException { OtpRequest otp = new OtpRequest(); - otp.setTxnId(loginData.getTnxId()); + otp.setTxnId(loginData.getTxnId()); otp.setOtpValue(encryptedLoginId); Map authDataMap = new HashMap<>(); From 55e48816ef62241dc109117399e7c91800a0bc63 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Fri, 13 Dec 2024 23:12:19 +0530 Subject: [PATCH 02/26] Abha-address search API changes --- src/main/environment/common_ci.properties | 2 + src/main/environment/common_dev.properties | 2 + .../environment/common_example.properties | 2 + src/main/environment/common_test.properties | 2 + .../v3/abha/LoginAbhaV3ServiceImpl.java | 42 ++++++++++++++++--- 5 files changed, 44 insertions(+), 6 deletions(-) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index f99d537..abbb76c 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -92,6 +92,8 @@ printAbhaCard = @env.ABDM_BASE_URL@/abha/api/v3/profile/account/abha-card abhaLoginRequestOtp = @env.ABDM_BASE_URL@/abha/api/v3/profile/login/request/otp verifyAbhaLogin = @env.ABDM_BASE_URL@/abha/api/v3/profile/login/verify requestAuthByAbdm = @env.ABDM_BASE_URL@/abha/api/v3/enrollment/auth/byAbdm +webLoginAbhaRequestOtp = @env.ABDM_BASE_URL@/abha/api/v3/phr/web/login/abha/request/otp +webLoginAbhaVerify = @env.ABDM_BASE_URL@/abha/api/v3/phr/web/login/abha/verify abhaMode=sbx diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index aca47c2..e6ea966 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -92,6 +92,8 @@ printAbhaCard = https://abhasbx.abdm.gov.in/abha/api/v3/profile/account/abha-car abhaLoginRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/request/otp verifyAbhaLogin = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/verify requestAuthByAbdm = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/auth/byAbdm +webLoginAbhaRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/request/otp +webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify abhaMode=sbx diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index fc9a950..f0a48a6 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -55,6 +55,8 @@ abdmCheckAndGenerateMobileOTP= https://healthidsbx.abdm.gov.in/api/v2/registrati abdmVerifyMobileOTP= https://healthidsbx.abdm.gov.in/api/v1/registration/aadhaar/verifyMobileOTP abdmcreateHealthIdWithPreVerified= https://healthidsbx.abdm.gov.in/api/v1/registration/aadhaar/createHealthIdWithPreVerified requestAuthByAbdm = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/auth/byAbdm +webLoginAbhaRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/request/otp +webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify ##CareContext Creation API generateOTPForCareContext=https://dev.abdm.gov.in/gateway/v0.5/users/auth/init diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties index aca47c2..e6ea966 100644 --- a/src/main/environment/common_test.properties +++ b/src/main/environment/common_test.properties @@ -92,6 +92,8 @@ printAbhaCard = https://abhasbx.abdm.gov.in/abha/api/v3/profile/account/abha-car abhaLoginRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/request/otp verifyAbhaLogin = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/verify requestAuthByAbdm = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/auth/byAbdm +webLoginAbhaRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/request/otp +webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify abhaMode=sbx diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java index 3263912..138b8c1 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java @@ -53,6 +53,12 @@ public class LoginAbhaV3ServiceImpl implements LoginAbhaV3Service { @Value("${abhaLoginRequestOtp}") String abhaLoginRequestOtp; + @Value("${webLoginAbhaRequestOtp}") + String webLoginAbhaRequestOtp; + + @Value("${webLoginAbhaVerify}") + String webLoginAbhaVerify; + @Value("${verifyAbhaLogin}") String verifyAbhaLoginUrl; @@ -65,6 +71,7 @@ public String requestOtpForAbhaLogin(String request) throws FHIRException { RestTemplate restTemplate = new RestTemplate(); String encryptedLoginId = null; String publicKeyString = null; + ResponseEntity responseEntity; try { String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); @@ -89,16 +96,22 @@ public String requestOtpForAbhaLogin(String request) throws FHIRException { reqOtpEnrollment.setLoginId(encryptedLoginId); } - if ("AADHAAR".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && - ("abha-number".equalsIgnoreCase(loginAbhaRequest.getLoginHint()) || "abha-address".equalsIgnoreCase(loginAbhaRequest.getLoginHint()) )) { + if ("AADHAAR".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && "abha-number".equalsIgnoreCase(loginAbhaRequest.getLoginHint() )) { reqOtpEnrollment.setScope(new String[] { "abha-login", "aadhaar-verify" }); reqOtpEnrollment.setLoginHint(loginAbhaRequest.getLoginHint()); reqOtpEnrollment.setOtpSystem("aadhaar"); - } else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) - && ("abha-number".equalsIgnoreCase(loginAbhaRequest.getLoginHint()) || "abha-address".equalsIgnoreCase(loginAbhaRequest.getLoginHint()) )) { + } else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && "abha-number".equalsIgnoreCase(loginAbhaRequest.getLoginHint() )) { reqOtpEnrollment.setScope(new String[] { "abha-login", "mobile-verify" }); reqOtpEnrollment.setLoginHint(loginAbhaRequest.getLoginHint()); reqOtpEnrollment.setOtpSystem("abdm"); + } else if ("aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && "abha-address".equalsIgnoreCase(loginAbhaRequest.getLoginHint() )) { + reqOtpEnrollment.setScope(new String[] { "abha-address-login", "aadhaar-verify" }); + reqOtpEnrollment.setLoginHint(loginAbhaRequest.getLoginHint()); + reqOtpEnrollment.setOtpSystem("aadhaar"); + } else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && "abha-address".equalsIgnoreCase(loginAbhaRequest.getLoginHint() )) { + reqOtpEnrollment.setScope(new String[] { "abha-address-login", "mobile-verify" }); + reqOtpEnrollment.setLoginHint(loginAbhaRequest.getLoginHint()); + reqOtpEnrollment.setOtpSystem("abdm"); } else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && "mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) ) { reqOtpEnrollment.setScope(new String[] { "abha-login", "mobile-verify" }); reqOtpEnrollment.setLoginHint("mobile"); @@ -115,8 +128,13 @@ public String requestOtpForAbhaLogin(String request) throws FHIRException { logger.info("ABDM reqobj for request otp for Abha login: " + requestOBJ); HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); - ResponseEntity responseEntity = restTemplate.exchange(abhaLoginRequestOtp, HttpMethod.POST, + if("abha-address".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) { + responseEntity = restTemplate.exchange(webLoginAbhaRequestOtp, HttpMethod.POST, + httpEntity, String.class); + } else { + responseEntity = restTemplate.exchange(abhaLoginRequestOtp, HttpMethod.POST, httpEntity, String.class); + } logger.info("ABDM response for response otp for Abha login: " + responseEntity); String responseStrLogin = common_NDHMService.getBody(responseEntity); @@ -145,6 +163,7 @@ public String verifyAbhaLogin(String request) throws FHIRException { String encryptedLoginId = null; String publicKeyString = null; HealthIDResponse health = new HealthIDResponse(); + ResponseEntity responseEntity; try { String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); @@ -185,14 +204,25 @@ public String verifyAbhaLogin(String request) throws FHIRException { } else if ("MOBILE".equalsIgnoreCase(loginData.getLoginMethod())) { verifyAbhaLogin.setScope(new String[] {"abha-login", "mobile-verify" } ); + } else if ("abha-mobile".equalsIgnoreCase(loginData.getLoginMethod())) { + verifyAbhaLogin.setScope(new String[] {"abha-address-login", "mobile-verify" } ); + + } else if ("abha-aadhaar".equalsIgnoreCase(loginData.getLoginMethod())) { + verifyAbhaLogin.setScope(new String[] {"abha-address-login", "aadhaar-verify" } ); } String requestObj = new Gson().toJson(verifyAbhaLogin); logger.info("ABDM request for verify abha login: " + requestObj); HttpEntity httpEntity = new HttpEntity<>(requestObj, headers); - ResponseEntity responseEntity = restTemplate.exchange(verifyAbhaLoginUrl, HttpMethod.POST, + + if("abha-aadhaar".equalsIgnoreCase(loginData.getLoginMethod()) || "abha-mobile".equalsIgnoreCase(loginData.getLoginMethod())) { + responseEntity = restTemplate.exchange(webLoginAbhaVerify, HttpMethod.POST, + httpEntity, String.class); + } else { + responseEntity = restTemplate.exchange(verifyAbhaLoginUrl, HttpMethod.POST, httpEntity, String.class); + } logger.info("ABDM response for verify abha login: " + httpEntity); String responseStrLogin = common_NDHMService.getBody(responseEntity); From f3445cb750c84d64836dbe96a3c0306a7aeafc82 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Mon, 16 Dec 2024 14:17:33 +0530 Subject: [PATCH 03/26] added validation for multiple phraddress --- .../service/v3/abha/CreateAbhaV3ServiceImpl.java | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java index 727231b..c233694 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java @@ -26,6 +26,7 @@ import org.springframework.web.client.RestTemplate; import com.google.gson.Gson; +import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.wipro.fhir.data.healthID.HealthIDResponse; @@ -431,8 +432,16 @@ public String getAbhaCardPrinted(String reqObj) throws FHIRException { private void constructHealthIdResponse(HealthIDResponse healthIDResp, JsonObject profile) throws ParseException { healthIDResp.setHealthIdNumber(profile.get("ABHANumber").getAsString()); - String abhaAddress = profile.get("phrAddress").getAsString().replace("[", "").replace("]", ""); - healthIDResp.setHealthId(abhaAddress); + JsonArray phrAddressArray = profile.getAsJsonArray("phrAddress"); + StringBuilder abhaAddressBuilder = new StringBuilder(); + + for (int i = 0; i < phrAddressArray.size(); i++) { + abhaAddressBuilder.append(phrAddressArray.get(i).getAsString()); + if (i < phrAddressArray.size() - 1) { + abhaAddressBuilder.append(", "); + } + } + healthIDResp.setHealthId(abhaAddressBuilder.toString()); healthIDResp.setName( healthIDResp.getFirstName() + " " + healthIDResp.getMiddleName() + " " + healthIDResp.getLastName()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy"); @@ -444,5 +453,5 @@ private void constructHealthIdResponse(HealthIDResponse healthIDResp, JsonObject healthIDResp.setMonthOfBirth(month.format(date)); healthIDResp.setDayOfBirth(day.format(date)); } - + } From f967118995245bff94596c8df4cfa26f32a55703 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Tue, 17 Dec 2024 22:18:05 +0530 Subject: [PATCH 04/26] Abha-address search response changes --- .../fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java index 138b8c1..0d70ae7 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java @@ -224,8 +224,8 @@ public String verifyAbhaLogin(String request) throws FHIRException { httpEntity, String.class); } - logger.info("ABDM response for verify abha login: " + httpEntity); String responseStrLogin = common_NDHMService.getBody(responseEntity); + logger.info("ABDM response for verify abha login: " + responseEntity); if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(200) && responseEntity.hasBody()) { JsonObject jsonResponse = JsonParser.parseString(responseStrLogin).getAsJsonObject(); @@ -239,6 +239,16 @@ public String verifyAbhaLogin(String request) throws FHIRException { if (jsonResponse.has("token")) { responseMap.put("xToken", jsonResponse.get("token").getAsString()); } + } else if(jsonResponse.has("users")) { + responseMap.put("abhaDetails", jsonResponse.get("users").getAsJsonArray().get(0).getAsJsonObject().toString()); + responseMap.put("txnId", jsonResponse.get("txnId").getAsString()); + if (jsonResponse.has("tokens") && jsonResponse.get("tokens").isJsonObject()) { + JsonObject tokensObject = jsonResponse.get("tokens").getAsJsonObject(); + if (tokensObject.has("token") && !tokensObject.get("token").isJsonNull()) { + String token = tokensObject.get("token").getAsString(); + responseMap.put("xToken", token); + } + } } } else { String message = jsonResponse.get("message").getAsString(); From 8430a37def65c225439f7e9a4af8e9b608b064a5 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Tue, 7 Jan 2025 15:22:01 +0530 Subject: [PATCH 05/26] Save facility id variable change chnages --- .../data/mongo/care_context/SaveFacilityIdForVisit.java | 2 +- .../com/wipro/fhir/service/common/CommonServiceImpl.java | 1 + .../wipro/fhir/service/facility/FacilityServiceImpl.java | 8 +++----- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/wipro/fhir/data/mongo/care_context/SaveFacilityIdForVisit.java b/src/main/java/com/wipro/fhir/data/mongo/care_context/SaveFacilityIdForVisit.java index 0a3c9f3..ea5358a 100644 --- a/src/main/java/com/wipro/fhir/data/mongo/care_context/SaveFacilityIdForVisit.java +++ b/src/main/java/com/wipro/fhir/data/mongo/care_context/SaveFacilityIdForVisit.java @@ -7,7 +7,7 @@ @Data public class SaveFacilityIdForVisit { - String facilityId; + String abdmFacilityId; BigInteger visitCode; } diff --git a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java index 5d676d3..1d2fbb1 100644 --- a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java @@ -212,6 +212,7 @@ public String processResourceOperation() throws FHIRException { int j = diagnosticReportRecordBundle.processDiagnosticReportRecordBundle(resourceRequestHandler, p); // 3. prescription Bundle int k = prescriptionBundle.processPrescriptionRecordBundle(resourceRequestHandler, p); + logger.info("The value of i: " +i + " The value of j: " + j + " The value of k: " + k ); if (i > 0 && j > 0 && k > 0) { diff --git a/src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java b/src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java index 117a3c1..bcb6925 100644 --- a/src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java @@ -3,7 +3,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -16,7 +15,6 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import com.wipro.fhir.data.mongo.care_context.AddCareContextRequest; import com.wipro.fhir.data.mongo.care_context.SaveFacilityIdForVisit; import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; import com.wipro.fhir.service.ndhm.Common_NDHMService; @@ -88,10 +86,10 @@ public String saveAbdmFacilityId(String reqObj) throws FHIRException { String res = null; try { SaveFacilityIdForVisit requestObj = InputMapper.gson().fromJson(reqObj, SaveFacilityIdForVisit.class); - if(requestObj.getFacilityId() == null || requestObj.getFacilityId() == "") { - requestObj.setFacilityId(abdmFacilityId); + if(requestObj.getAbdmFacilityId() == null || requestObj.getAbdmFacilityId() == "") { + requestObj.setAbdmFacilityId(abdmFacilityId); } - Integer response = benHealthIDMappingRepo.updateFacilityIdForVisit(requestObj.getVisitCode(), requestObj.getFacilityId()); + Integer response = benHealthIDMappingRepo.updateFacilityIdForVisit(requestObj.getVisitCode(), requestObj.getAbdmFacilityId()); if(response > 0 ) { res = "ABDM Facility ID updated successfully"; } else From 68a81b3a9f13b4c45351ee95900912dcb21ea9c2 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Thu, 9 Jan 2025 17:28:45 +0530 Subject: [PATCH 06/26] Added check to avoid multiple save of single care-context --- .../service/common/CommonServiceImpl.java | 122 +++++++----------- 1 file changed, 50 insertions(+), 72 deletions(-) diff --git a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java index 1d2fbb1..7cc60ff 100644 --- a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java @@ -40,7 +40,6 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.data.mongodb.core.query.Update; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -59,7 +58,6 @@ import com.wipro.fhir.data.mongo.care_context.NDHMResponse; import com.wipro.fhir.data.mongo.care_context.Notification; import com.wipro.fhir.data.mongo.care_context.PatientCareContexts; -import com.wipro.fhir.data.mongo.care_context.PatientCareContextsStringOBJ; import com.wipro.fhir.data.mongo.care_context.SMSNotify; import com.wipro.fhir.data.patient.PatientDemographic; import com.wipro.fhir.data.patient_data_handler.PatientDemographicModel_NDHM_Patient_Profile; @@ -96,17 +94,13 @@ public class CommonServiceImpl implements CommonService { @Value("${patient-search-page-size}") private String patient_search_page_size; - + @Value("${abhaMode}") private String abhaMode; private static String authKey; private UUID uuid; - //public static String NDHM_AUTH_TOKEN; - //public static Long NDHM_TOKEN_EXP; - //public static String NDHM_OTP_TOKEN; - @Value("${clientID}") private String clientID; @@ -127,7 +121,6 @@ public class CommonServiceImpl implements CommonService { private APIChannel aPIChannel; @Autowired private AMRIT_ResourceMongoRepo aMRIT_ResourceMongoRepo; - @Autowired private PatientCareContextsMongoRepo patientCareContextsMongoRepo; @@ -148,7 +141,7 @@ public class CommonServiceImpl implements CommonService { @Autowired private PatientDataGatewayService patientDataGatewayService; - + @Autowired private MongoTemplate mongoTemplate; @@ -159,7 +152,7 @@ public class CommonServiceImpl implements CommonService { private PatientDemographic patientDemographic; @Autowired private Common_NDHMService common_NDHMService; - + @Autowired private BenHealthIDMappingRepo benHealthIDMappingRepo; @@ -168,7 +161,8 @@ public String processResourceOperation() throws FHIRException { String response = null; // list of patient eligible for resource creation List pList = getPatientListForResourceEligible(); - logger.info("No of records available to create FHIR in last 2 dagetPatientListForResourceEligibleys : " + pList.size()); + logger.info("No of records available to create FHIR in last 2 dagetPatientListForResourceEligibleys : " + + pList.size()); ResourceRequestHandler resourceRequestHandler; for (PatientEligibleForResourceCreation p : pList) { @@ -196,10 +190,11 @@ public String processResourceOperation() throws FHIRException { if (patientDemographicOBJ.getPreferredPhoneNo() != null) sendAbdmAdvSMS(patientDemographicOBJ.getPreferredPhoneNo()); else - throw new FHIRException("Advertisement sms could not be sent as beneficiary phone no not found"); - } - else - throw new FHIRException("Beneficiary not found, benRegId = " +resourceRequestHandler.getBeneficiaryRegID()); + throw new FHIRException( + "Advertisement sms could not be sent as beneficiary phone no not found"); + } else + throw new FHIRException( + "Beneficiary not found, benRegId = " + resourceRequestHandler.getBeneficiaryRegID()); } catch (Exception e) { logger.error(e.getMessage()); @@ -212,7 +207,7 @@ public String processResourceOperation() throws FHIRException { int j = diagnosticReportRecordBundle.processDiagnosticReportRecordBundle(resourceRequestHandler, p); // 3. prescription Bundle int k = prescriptionBundle.processPrescriptionRecordBundle(resourceRequestHandler, p); - logger.info("The value of i: " +i + " The value of j: " + j + " The value of k: " + k ); + logger.info("The value of i: " + i + " The value of j: " + j + " The value of k: " + k); if (i > 0 && j > 0 && k > 0) { @@ -290,47 +285,16 @@ public String getUUID() { // 31-03-2021 // @Override - public int addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForResourceCreation pVisit) + public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForResourceCreation pVisit) throws FHIRException { - int response = 0; if (pDemo != null && pVisit != null) { -// JsonObject jsnOBJ = new JsonObject(); -// JsonParser jsnParser = new JsonParser(); -// JsonElement jsnElmnt = jsnParser.parse(requestObj); -// jsnOBJ = jsnElmnt.getAsJsonObject(); - - PatientCareContextsStringOBJ patientCareContextsStringOBJ = new PatientCareContextsStringOBJ(); - - // wrong variable name in request obj for benregid, need to correct in main - // request obj first -// Long benID = null; -// Long benRegID = null; -// Long visitCode = null; -// -// if (jsnOBJ.has("beneficiaryID") && jsnOBJ.get("beneficiaryID") != null) -// benRegID = jsnOBJ.get("beneficiaryID").getAsLong(); -// if (jsnOBJ.has("visitCode") && jsnOBJ.get("visitCode") != null) -// visitCode = jsnOBJ.get("visitCode").getAsLong(); -// String healthID = jsnOBJ.get("healthID").getAsString(); -// String healthIDNumber = jsnOBJ.get("healthIdNumber").getAsString(); -// String visitCategory = jsnOBJ.get("visitCategory").getAsString(); -// String phoneNo; -// String gender; -// String yearOfBirth; -// String name; -// String email; - - // get benid -// if (benRegID != null) -// benID = benHealthIDMappingRepo.getBenID(benRegID); - - // fetch abdm facility id - logger.info("********t_benvisistData fetch request pvisit data :" , pVisit); + // fetch abdm facility id + logger.info("********t_benvisistData fetch request pvisit data :", pVisit); List res = benHealthIDMappingRepo.getAbdmFacilityAndlinkedDate(pVisit.getVisitCode()); - + // check care context record in mongo against beneficiaryID ArrayList ccList = new ArrayList<>(); @@ -338,28 +302,46 @@ public int addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRes logger.info("********t_benvisistData fetch response : {}", res); cc.setReferenceNumber(pVisit.getVisitCode() != null ? pVisit.getVisitCode().toString() : null); - cc.setDisplay(pVisit.getVisitCategory() != null ? pVisit.getVisitCategory().toString() : null); + cc.setDisplay(pVisit.getVisitCategory() != null ? pVisit.getVisitCategory().toString() : null); Object[] resData = null; if (res.get(0) != null) { resData = res.get(0); - cc.setAbdmFacilityId(resData[0] != null ? resData[0].toString() : null ); - cc.setCareContextLinkedDate(resData[1] != null ? resData[1].toString() : null); + cc.setAbdmFacilityId(resData[0] != null ? resData[0].toString() : null); + cc.setCareContextLinkedDate(resData[1] != null ? resData[1].toString() : null); } - - logger.info("********data to be saved in mongo :" , cc); + + logger.info("********data to be saved in mongo :", cc); PatientCareContexts pcc; PatientCareContexts resultSet = null; - if (pDemo.getBeneficiaryID() != null) { pcc = patientCareContextsMongoRepo.findByIdentifier(pDemo.getBeneficiaryID().toString()); if (pcc != null && pcc.getIdentifier() != null) { - ccList = pcc.getCareContextsList(); - ccList.add(cc); - pcc.setCareContextsList(ccList); - resultSet = patientCareContextsMongoRepo.save(pcc); - + // Get the existing careContextsList + if (pcc.getCareContextsList() != null && pcc.getCareContextsList().size() > 0) { + ccList = pcc.getCareContextsList(); + + // Check if the visitCode is already in the careContextsList + boolean visitCodeExists = false; + for (CareContexts existingContext : ccList) { + if (existingContext.getReferenceNumber() != null + && existingContext.getReferenceNumber().equals(pVisit.getVisitCode().toString())) { + visitCodeExists = true; + return; + } + } + ccList.add(cc); + pcc.setCareContextsList(ccList); + resultSet = patientCareContextsMongoRepo.save(pcc); + } +// } +// if (pcc != null && pcc.getIdentifier() != null) { +// ccList = pcc.getCareContextsList(); +// ccList.add(cc); +// pcc.setCareContextsList(ccList); +// resultSet = patientCareContextsMongoRepo.save(pcc); +// } else { pcc = new PatientCareContexts(); pcc.setCaseReferenceNumber(pDemo.getBeneficiaryID().toString()); @@ -396,13 +378,9 @@ public int addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRes // save carecontext back to mongo resultSet = patientCareContextsMongoRepo.save(pcc); } - - if (resultSet != null && resultSet.get_id() != null) - response = 1; } } - return response; } @Deprecated @@ -424,7 +402,7 @@ public String ndhmUserAuthenticate() throws FHIRException { JsonParser jsnParser = new JsonParser(); JsonElement jsnElmnt = jsnParser.parse(responseStrLogin); jsnOBJ = jsnElmnt.getAsJsonObject(); - //NDHM_AUTH_TOKEN = "Bearer" + " " + jsnOBJ.get("accessToken").getAsString(); + // NDHM_AUTH_TOKEN = "Bearer" + " " + jsnOBJ.get("accessToken").getAsString(); Integer expiry = jsnOBJ.get("expiresIn").getAsInt(); double time = expiry / 60; Date date = new Date(); @@ -432,7 +410,7 @@ public String ndhmUserAuthenticate() throws FHIRException { Calendar ndhmCalendar = Calendar.getInstance(); ndhmCalendar.setTime(sqlDate); ndhmCalendar.add(Calendar.MINUTE, (int) time); - + res = "success"; } else res = "Error while accessing authenticate API"; @@ -478,7 +456,7 @@ public List fetchTempResourceFromMongo(ResourceRequestHandler re * @author SH20094090 * @return * - * get the UUID and isoTimestamp for NDMH API's + * get the UUID and isoTimestamp for NDMH API's */ @Deprecated @Override @@ -542,7 +520,7 @@ public String getMongoNDHMResponse(String requestID) throws FHIRException { * @param reqID * @return * - * hitting MongoDB + * hitting MongoDB */ @Deprecated NDHMResponse getResponseMongo(String reqID) { @@ -629,8 +607,8 @@ public void sendAbdmAdvSMS(String phone) throws FHIRException { SMSNotify smsNotify = new SMSNotify(obj.getRequestId(), obj.getTimestamp(), notification); String requestOBJ = new Gson().toJson(smsNotify); logger.info("NDHM_FHIR Generate Notify SMS request Obj: " + requestOBJ); - if(abhaMode !=null && !(abhaMode.equalsIgnoreCase("abdm") || abhaMode.equalsIgnoreCase("sbx"))) - abhaMode="sbx"; + if (abhaMode != null && !(abhaMode.equalsIgnoreCase("abdm") || abhaMode.equalsIgnoreCase("sbx"))) + abhaMode = "sbx"; HttpHeaders headers = common_NDHMService.getHeaders(ndhmAuthToken, abhaMode); ResponseEntity responseEntity = httpUtils.postWithResponseEntity(generateABDM_NotifySMS, requestOBJ, headers); From 44df923ddc4c80f97b8ccd584c1a06e7aaf1165a Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Thu, 9 Jan 2025 18:20:40 +0530 Subject: [PATCH 07/26] removed unused variables --- .../wipro/fhir/service/common/CommonServiceImpl.java | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java index 7cc60ff..85c6973 100644 --- a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java @@ -161,8 +161,7 @@ public String processResourceOperation() throws FHIRException { String response = null; // list of patient eligible for resource creation List pList = getPatientListForResourceEligible(); - logger.info("No of records available to create FHIR in last 2 dagetPatientListForResourceEligibleys : " - + pList.size()); + logger.info("No of records available to create FHIR in last 2 dagetPatientListForResourceEligibleys : " + pList.size()); ResourceRequestHandler resourceRequestHandler; for (PatientEligibleForResourceCreation p : pList) { @@ -312,7 +311,6 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe logger.info("********data to be saved in mongo :", cc); PatientCareContexts pcc; - PatientCareContexts resultSet = null; if (pDemo.getBeneficiaryID() != null) { pcc = patientCareContextsMongoRepo.findByIdentifier(pDemo.getBeneficiaryID().toString()); @@ -323,17 +321,16 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe ccList = pcc.getCareContextsList(); // Check if the visitCode is already in the careContextsList - boolean visitCodeExists = false; for (CareContexts existingContext : ccList) { if (existingContext.getReferenceNumber() != null && existingContext.getReferenceNumber().equals(pVisit.getVisitCode().toString())) { - visitCodeExists = true; + logger.info("Visit code already Exisit in Mongo for benId:" + pDemo.getBeneficiaryID().toString() + "and visit code : " + pVisit.getVisitCode() ); return; } } ccList.add(cc); pcc.setCareContextsList(ccList); - resultSet = patientCareContextsMongoRepo.save(pcc); + patientCareContextsMongoRepo.save(pcc); } // } // if (pcc != null && pcc.getIdentifier() != null) { @@ -376,7 +373,7 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe ccList.add(cc); pcc.setCareContextsList(ccList); // save carecontext back to mongo - resultSet = patientCareContextsMongoRepo.save(pcc); + patientCareContextsMongoRepo.save(pcc); } } From 9c3b51f63d4eb7cbfb84680bed55eb06dd58a07d Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Thu, 30 Jan 2025 14:13:40 +0530 Subject: [PATCH 08/26] Updated public key certificate API --- src/main/environment/common_ci.properties | 1 + src/main/environment/common_dev.properties | 1 + .../environment/common_example.properties | 1 + src/main/environment/common_test.properties | 1 + .../v3/abha/CertificateKeyService.java | 2 +- .../v3/abha/CertificateKeyServiceImpl.java | 58 ++++++++++++++----- .../v3/abha/CreateAbhaV3ServiceImpl.java | 7 +-- .../v3/abha/LoginAbhaV3ServiceImpl.java | 5 +- 8 files changed, 55 insertions(+), 21 deletions(-) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index abbb76c..737e068 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -85,6 +85,7 @@ abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile getAbdmFacilityServicies= @env.ABDM_BASE_URL@/devservice/v1/bridges/getServices ##ABDM V3 APIs +abdmV3UserAuthenticate = @env.ABDM_BASE_URL@/api/hiecm/gateway/v3/sessions getAuthCertPublicKey = @env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/cert requestOtpForEnrollment = @env.ABDM_BASE_URL@/abha/api/v3/enrollment/request/otp abhaEnrollByAadhaar = @env.ABDM_BASE_URL@/abha/api/v3/enrollment/enrol/byAadhaar diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index e6ea966..0b036ba 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -85,6 +85,7 @@ abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices ##ABDM V3 APIs +abdmV3UserAuthenticate = https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions getAuthCertPublicKey = https://healthidsbx.abdm.gov.in/api/v1/auth/cert requestOtpForEnrollment = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/byAadhaar diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index f0a48a6..ce69dea 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -87,6 +87,7 @@ abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices ##ABDM V3 APIs +abdmV3UserAuthenticate = https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions getAuthCertPublicKey = https://healthidsbx.abdm.gov.in/api/v1/auth/cert requestOtpForEnrollment = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/byAadhaar diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties index e6ea966..0b036ba 100644 --- a/src/main/environment/common_test.properties +++ b/src/main/environment/common_test.properties @@ -85,6 +85,7 @@ abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices ##ABDM V3 APIs +abdmV3UserAuthenticate = https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions getAuthCertPublicKey = https://healthidsbx.abdm.gov.in/api/v1/auth/cert requestOtpForEnrollment = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/byAadhaar diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyService.java b/src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyService.java index 63bf1e8..594c137 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyService.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyService.java @@ -4,6 +4,6 @@ public interface CertificateKeyService { - public String getCertPublicKey() throws FHIRException; + public String getCertPublicKey(String ndhmAuthToken) throws FHIRException; } diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java index 71e5845..cbf9f0f 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java @@ -1,41 +1,73 @@ package com.wipro.fhir.service.v3.abha; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; + 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.http.HttpEntity; import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.wipro.fhir.service.ndhm.Common_NDHMService; import com.wipro.fhir.utils.exception.FHIRException; @Service -public class CertificateKeyServiceImpl implements CertificateKeyService{ - +public class CertificateKeyServiceImpl implements CertificateKeyService { + + @Autowired + private Common_NDHMService common_NDHMService; + @Value("${getAuthCertPublicKey}") String getAuthCertPublicKey; - + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - + @Override - public String getCertPublicKey() throws FHIRException { + public String getCertPublicKey(String ndhmAuthToken) throws FHIRException { RestTemplate restTemplate = new RestTemplate(); - HttpEntity requestEntity = new HttpEntity<>(null); + String publicKey = null; - ResponseEntity certResp = restTemplate.exchange(getAuthCertPublicKey, HttpMethod.GET, requestEntity, - String.class); - String body = certResp.getBody(); + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("Authorization", ndhmAuthToken); - String publicKeyString = body.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "") - .replaceAll("\\s+", ""); + HttpEntity httpEntity = new HttpEntity<>(null, headers); + + ResponseEntity certResp = restTemplate.exchange(getAuthCertPublicKey, HttpMethod.GET, httpEntity, + String.class); + String responseStrLogin = common_NDHMService.getBody(certResp); + if (certResp.getStatusCode() == HttpStatusCode.valueOf(200) && certResp.hasBody()) { + JsonObject jsnOBJ = JsonParser.parseString(responseStrLogin).getAsJsonObject(); + publicKey = jsnOBJ.get("publicKey").getAsString(); - logger.info("publicKeyString : " + publicKeyString); + logger.info("publicKeyString : " + publicKey); - return publicKeyString; + return publicKey; + } + return publicKey; } } diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java index c233694..0fce983 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java @@ -103,7 +103,7 @@ public String getOtpForEnrollment(String request) throws FHIRException { RequestOTPEnrollment reqOtpEnrollment = new RequestOTPEnrollment(); LoginMethod loginMethod = InputMapper.gson().fromJson(request, LoginMethod.class); - publicKeyString = certificateKeyService.getCertPublicKey(); + publicKeyString = certificateKeyService.getCertPublicKey(ndhmAuthToken); if (loginMethod.getLoginId() != null) { encryptedLoginId = encryption.encrypt(loginMethod.getLoginId(), publicKeyString); } @@ -169,10 +169,9 @@ public String enrollmentByAadhaar(String request) throws FHIRException { headers.add("Authorization", ndhmAuthToken); // Create the enrollByAadhar object - EnrollByAadhaar enrollByAadhar = new EnrollByAadhaar(); LoginMethod loginData = InputMapper.gson().fromJson(request, LoginMethod.class); - publicKeyString = certificateKeyService.getCertPublicKey(); + publicKeyString = certificateKeyService.getCertPublicKey(ndhmAuthToken); if (loginData.getLoginId() != null) { encryptedLoginId = encryption.encrypt(loginData.getLoginId(), publicKeyString); } @@ -263,7 +262,7 @@ public String verifyAuthByAbdm(String request) throws FHIRException { LoginMethod loginMethod = InputMapper.gson().fromJson(request, LoginMethod.class); - publicKeyString = certificateKeyService.getCertPublicKey(); + publicKeyString = certificateKeyService.getCertPublicKey(ndhmAuthToken); if (loginMethod.getLoginId() != null) { encryptedLoginId = encryption.encrypt(loginMethod.getLoginId(), publicKeyString); } diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java index 0d70ae7..90e759b 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java @@ -90,7 +90,7 @@ public String requestOtpForAbhaLogin(String request) throws FHIRException { RequestOTPEnrollment reqOtpEnrollment = new RequestOTPEnrollment(); LoginAbhaRequest loginAbhaRequest = InputMapper.gson().fromJson(request, LoginAbhaRequest.class); - publicKeyString = certificateKeyService.getCertPublicKey(); + publicKeyString = certificateKeyService.getCertPublicKey(ndhmAuthToken); if (loginAbhaRequest.getLoginId() != null) { encryptedLoginId = encryption.encrypt(loginAbhaRequest.getLoginId(), publicKeyString); reqOtpEnrollment.setLoginId(encryptedLoginId); @@ -181,8 +181,7 @@ public String verifyAbhaLogin(String request) throws FHIRException { // Create the enrollByAadhar object VerifyAbhaLogin verifyAbhaLogin = new VerifyAbhaLogin(); LoginMethod loginData = InputMapper.gson().fromJson(request, LoginMethod.class); - - publicKeyString = certificateKeyService.getCertPublicKey(); + publicKeyString = certificateKeyService.getCertPublicKey(ndhmAuthToken); if (loginData.getLoginId() != null) { encryptedLoginId = encryption.encrypt(loginData.getLoginId(), publicKeyString); } From 114cfff3a27a2968a5293a0634527b398573ab8c Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Mon, 24 Feb 2025 20:58:58 +0530 Subject: [PATCH 09/26] Integrated Abha session v3 APIs and Profile login user verify APIs --- src/main/environment/common_ci.properties | 5 +- src/main/environment/common_dev.properties | 4 + .../environment/common_example.properties | 6 +- src/main/environment/common_test.properties | 4 + .../v3/abha/CreateAbhaV3Controller.java | 1 - .../v3/abha/LoginAbhaV3Controller.java | 19 ++ .../wipro/fhir/data/healthID/Authorize.java | 16 +- .../fhir/data/healthID/HealthIDResponse.java | 192 +---------------- .../v3/abhaCard/VerifyProfileUserLogin.java | 10 + .../v3/abha/CreateAbhaV3ServiceImpl.java | 27 +-- .../v3/abha/GenerateAuthSessionService.java | 11 + .../abha/GenerateAuthSessionServiceImpl.java | 124 +++++++++++ .../service/v3/abha/LoginAbhaV3Service.java | 4 + .../v3/abha/LoginAbhaV3ServiceImpl.java | 201 ++++++++++++++---- 14 files changed, 364 insertions(+), 260 deletions(-) create mode 100644 src/main/java/com/wipro/fhir/data/v3/abhaCard/VerifyProfileUserLogin.java create mode 100644 src/main/java/com/wipro/fhir/service/v3/abha/GenerateAuthSessionService.java create mode 100644 src/main/java/com/wipro/fhir/service/v3/abha/GenerateAuthSessionServiceImpl.java diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index 737e068..ed70c81 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -92,11 +92,14 @@ abhaEnrollByAadhaar = @env.ABDM_BASE_URL@/abha/api/v3/enrollment/enrol/byAadhaar printAbhaCard = @env.ABDM_BASE_URL@/abha/api/v3/profile/account/abha-card abhaLoginRequestOtp = @env.ABDM_BASE_URL@/abha/api/v3/profile/login/request/otp verifyAbhaLogin = @env.ABDM_BASE_URL@/abha/api/v3/profile/login/verify +abhaProfileLoginVerifyUser = @env.ABDM_BASE_URL@/abha/api/v3/profile/login/verify/user requestAuthByAbdm = @env.ABDM_BASE_URL@/abha/api/v3/enrollment/auth/byAbdm webLoginAbhaRequestOtp = @env.ABDM_BASE_URL@/abha/api/v3/phr/web/login/abha/request/otp webLoginAbhaVerify = @env.ABDM_BASE_URL@/abha/api/v3/phr/web/login/abha/verify +webLoginAbhaVerify = @env.ABDM_BASE_URL@/abha/api/v3/phr/web/login/abha/verify +webLoginPhrCard = @env.ABDM_BASE_URL@/abha/api/v3/phr/web/login/profile/abha/phr-card - +x-CM-ID= sbx abhaMode=sbx #logging.pattern.level=DEBUG diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index 0b036ba..db18ad9 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -92,10 +92,14 @@ abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/b printAbhaCard = https://abhasbx.abdm.gov.in/abha/api/v3/profile/account/abha-card abhaLoginRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/request/otp verifyAbhaLogin = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/verify +abhaProfileLoginVerifyUser = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/verify/user requestAuthByAbdm = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/auth/byAbdm webLoginAbhaRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/request/otp webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify +webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify +webLoginPhrCard = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/profile/abha/phr-card +x-CM-ID= sbx abhaMode=sbx #logging.pattern.level=DEBUG diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index bd5e556..803d225 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -95,8 +95,12 @@ abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/b printAbhaCard = https://abhasbx.abdm.gov.in/abha/api/v3/profile/account/abha-card abhaLoginRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/request/otp verifyAbhaLogin = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/verify +abhaProfileLoginVerifyUser = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/verify/user +requestAuthByAbdm = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/auth/byAbdm +webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify +webLoginPhrCard = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/profile/abha/phr-card - +x-CM-ID= sbx abhaMode=sbx #logging.pattern.level=DEBUG diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties index 0b036ba..db18ad9 100644 --- a/src/main/environment/common_test.properties +++ b/src/main/environment/common_test.properties @@ -92,10 +92,14 @@ abhaEnrollByAadhaar = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/enrol/b printAbhaCard = https://abhasbx.abdm.gov.in/abha/api/v3/profile/account/abha-card abhaLoginRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/request/otp verifyAbhaLogin = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/verify +abhaProfileLoginVerifyUser = https://abhasbx.abdm.gov.in/abha/api/v3/profile/login/verify/user requestAuthByAbdm = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/auth/byAbdm webLoginAbhaRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/request/otp webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify +webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify +webLoginPhrCard = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/profile/abha/phr-card +x-CM-ID= sbx abhaMode=sbx #logging.pattern.level=DEBUG diff --git a/src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java b/src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java index 49fbfc6..4e277d9 100644 --- a/src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java +++ b/src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java @@ -105,5 +105,4 @@ public String printAbhaCard(@RequestBody String request) { return response.toString(); } - } diff --git a/src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java b/src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java index 24977f2..7d69230 100644 --- a/src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java +++ b/src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java @@ -64,5 +64,24 @@ public String verifyAbhaLogin(@RequestBody String request) { logger.info("NDHM_FHIR Verify abha login API response " + response.toString()); return response.toString(); } + + @CrossOrigin + @Operation(summary = "Print PHR card - abha address web login") + @PostMapping(value = { "/printWebLoginPhrCard" }) + public String printWebLoginPhrCard(@RequestBody String request) { + OutputResponse response = new OutputResponse(); + try { + if (request != null) { + String s = loginAbhaV3Service.getWebLoginPhrCard(request); + response.setResponse(s); + } else + throw new FHIRException("NDHM_FHIR Empty request object"); + } catch (FHIRException e) { + response.setError(5000, e.getMessage()); + logger.error(e.toString()); + } + logger.info("NDHM_FHIR generate OTP for ABHA card API respponse " + response.toString()); + return response.toString(); + } } diff --git a/src/main/java/com/wipro/fhir/data/healthID/Authorize.java b/src/main/java/com/wipro/fhir/data/healthID/Authorize.java index cb2d07d..8ae94ff 100644 --- a/src/main/java/com/wipro/fhir/data/healthID/Authorize.java +++ b/src/main/java/com/wipro/fhir/data/healthID/Authorize.java @@ -21,19 +21,11 @@ */ package com.wipro.fhir.data.healthID; +import lombok.Data; + +@Data public class Authorize { String clientId; String clientSecret; -public String getClientId() { - return clientId; -} -public void setClientId(String clientId) { - this.clientId = clientId; -} -public String getClientSecret() { - return clientSecret; -} -public void setClientSecret(String clientSecret) { - this.clientSecret = clientSecret; -} +String grantType; } diff --git a/src/main/java/com/wipro/fhir/data/healthID/HealthIDResponse.java b/src/main/java/com/wipro/fhir/data/healthID/HealthIDResponse.java index 99935ae..edb9f15 100644 --- a/src/main/java/com/wipro/fhir/data/healthID/HealthIDResponse.java +++ b/src/main/java/com/wipro/fhir/data/healthID/HealthIDResponse.java @@ -31,10 +31,12 @@ import jakarta.persistence.Id; import jakarta.persistence.Table; import jakarta.persistence.Transient; +import lombok.Data; import com.google.gson.annotations.Expose; +@Data @Entity @Table(name = "t_healthid") public class HealthIDResponse { @@ -125,194 +127,10 @@ public class HealthIDResponse { private String modifiedBy; @Column(name = "LastModDate", insertable = false, updatable = false) private Timestamp lastModDate; - + @Column(name = "isNewAbha") + private Boolean isNewAbha; @Expose @Column(name = "TxnID") - String txnId; - - public String getHealthId() { - return healthId; - } - public void setHealthId(String healthId) { - this.healthId = healthId; - } - public String getHealthIdNumber() { - return healthIdNumber; - } - public void setHealthIdNumber(String healthIdNumber) { - this.healthIdNumber = healthIdNumber; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getGender() { - return gender; - } - public void setGender(String gender) { - this.gender = gender; - } - public String getYearOfBirth() { - return yearOfBirth; - } - public void setYearOfBirth(String yearOfBirth) { - this.yearOfBirth = yearOfBirth; - } - public String getMonthOfBirth() { - return monthOfBirth; - } - public void setMonthOfBirth(String monthOfBirth) { - this.monthOfBirth = monthOfBirth; - } - public String getDayOfBirth() { - return dayOfBirth; - } - public void setDayOfBirth(String dayOfBirth) { - this.dayOfBirth = dayOfBirth; - } - public String getFirstName() { - return firstName; - } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - public String getLastName() { - return lastName; - } - public void setLastName(String lastName) { - this.lastName = lastName; - } - public String getMiddleName() { - return middleName; - } - public void setMiddleName(String middleName) { - this.middleName = middleName; - } - public String getStateCode() { - return stateCode; - } - public void setStateCode(String stateCode) { - this.stateCode = stateCode; - } - public String getDistrictCode() { - return districtCode; - } - public void setDistrictCode(String districtCode) { - this.districtCode = districtCode; - } - public String getStateName() { - return stateName; - } - public void setStateName(String stateName) { - this.stateName = stateName; - } - public String getDistrictName() { - return districtName; - } - public void setDistrictName(String districtName) { - this.districtName = districtName; - } - public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } - public String getKycPhoto() { - return kycPhoto; - } - public void setKycPhoto(String kycPhoto) { - this.kycPhoto = kycPhoto; - } - public String getMobile() { - return mobile; - } - public void setMobile(String mobile) { - this.mobile = mobile; - } - - public Integer getProviderServiceMapID() { - return providerServiceMapID; - } - public void setProviderServiceMapID(Integer providerServiceMapID) { - this.providerServiceMapID = providerServiceMapID; - } - - public List getAuthMethods() { - return authMethods; - } - public void setAuthMethods(List authMethods) { - this.authMethods = authMethods; - } - public Integer gethID() { - return hID; - } - public void sethID(Integer hID) { - this.hID = hID; - } - public Long getBeneficiaryRegId() { - return beneficiaryRegId; - } - public void setBeneficiaryRegId(Long beneficiaryRegId) { - this.beneficiaryRegId = beneficiaryRegId; - } - public String getAuthMethod() { - return authMethod; - } - public void setAuthMethod(String authMethod) { - this.authMethod = authMethod; - } - public Boolean getDeleted() { - return deleted; - } - public void setDeleted(Boolean deleted) { - this.deleted = deleted; - } - public String getProcessed() { - return processed; - } - public void setProcessed(String processed) { - this.processed = processed; - } - public String getCreatedBy() { - return createdBy; - } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - public Timestamp getCreatedDate() { - return createdDate; - } - public void setCreatedDate(Timestamp createdDate) { - this.createdDate = createdDate; - } - public String getModifiedBy() { - return modifiedBy; - } - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - public Timestamp getLastModDate() { - return lastModDate; - } - public void setLastModDate(Timestamp lastModDate) { - this.lastModDate = lastModDate; - } - public String getTxnId() { - return txnId; - } - public void setTxnId(String txnId) { - this.txnId = txnId; - } - public String getAuthenticationMode() { - return authenticationMode; - } - public void setAuthenticationMode(String authenticationMode) { - this.authenticationMode = authenticationMode; - } - - + String txnId; } diff --git a/src/main/java/com/wipro/fhir/data/v3/abhaCard/VerifyProfileUserLogin.java b/src/main/java/com/wipro/fhir/data/v3/abhaCard/VerifyProfileUserLogin.java new file mode 100644 index 0000000..484ea21 --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/v3/abhaCard/VerifyProfileUserLogin.java @@ -0,0 +1,10 @@ +package com.wipro.fhir.data.v3.abhaCard; + +import lombok.Data; + +@Data +public class VerifyProfileUserLogin { + + private String ABHANumber; + private String txnId; +} diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java index 0fce983..4ddc4e9 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java @@ -49,7 +49,7 @@ public class CreateAbhaV3ServiceImpl implements CreateAbhaV3Service { @Autowired - private GenerateSession_NDHMService generateSession_NDHM; + private GenerateAuthSessionService generateAuthSessionService; @Autowired private Common_NDHMService common_NDHMService; @Autowired @@ -87,7 +87,7 @@ public String getOtpForEnrollment(String request) throws FHIRException { String publicKeyString = null; try { - String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + String abhaAuthToken = generateAuthSessionService.getAbhaAuthToken(); MultiValueMap headers = new LinkedMultiValueMap<>(); headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); @@ -98,12 +98,12 @@ public String getOtpForEnrollment(String request) throws FHIRException { df.setTimeZone(tz); String nowAsISO = df.format(new Date()); headers.add("TIMESTAMP", nowAsISO); - headers.add("Authorization", ndhmAuthToken); + headers.add("Authorization", abhaAuthToken); RequestOTPEnrollment reqOtpEnrollment = new RequestOTPEnrollment(); LoginMethod loginMethod = InputMapper.gson().fromJson(request, LoginMethod.class); - publicKeyString = certificateKeyService.getCertPublicKey(ndhmAuthToken); + publicKeyString = certificateKeyService.getCertPublicKey(abhaAuthToken); if (loginMethod.getLoginId() != null) { encryptedLoginId = encryption.encrypt(loginMethod.getLoginId(), publicKeyString); } @@ -156,7 +156,7 @@ public String enrollmentByAadhaar(String request) throws FHIRException { String requestObj = null; try { - String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + String abhaAuthToken = generateAuthSessionService.getAbhaAuthToken(); MultiValueMap headers = new LinkedMultiValueMap<>(); headers.add("Content-Type", MediaType.APPLICATION_JSON.toString()); headers.add("REQUEST-ID", UUID.randomUUID().toString()); @@ -166,12 +166,12 @@ public String enrollmentByAadhaar(String request) throws FHIRException { df.setTimeZone(tz); String nowAsISO = df.format(new Date()); headers.add("TIMESTAMP", nowAsISO); - headers.add("Authorization", ndhmAuthToken); + headers.add("Authorization", abhaAuthToken); // Create the enrollByAadhar object LoginMethod loginData = InputMapper.gson().fromJson(request, LoginMethod.class); - publicKeyString = certificateKeyService.getCertPublicKey(ndhmAuthToken); + publicKeyString = certificateKeyService.getCertPublicKey(abhaAuthToken); if (loginData.getLoginId() != null) { encryptedLoginId = encryption.encrypt(loginData.getLoginId(), publicKeyString); } @@ -211,6 +211,9 @@ public String enrollmentByAadhaar(String request) throws FHIRException { constructHealthIdResponse(healthIDResp, abhaProfileAsJsonObj); healthIDResp.setProviderServiceMapID(loginData.getProviderServiceMapId()); healthIDResp.setCreatedBy(loginData.getCreatedBy()); + if(jsonResponse.get("isNew") != null && jsonResponse.get("isNew").getAsString() == "true") { + healthIDResp.setIsNewAbha(true); + } Integer healthIdCount = healthIDRepo.getCountOfHealthIdNumber(healthIDResp.getHealthIdNumber()); HealthIDResponse save = healthIDResp; if (healthIdCount < 1) { @@ -247,7 +250,7 @@ public String verifyAuthByAbdm(String request) throws FHIRException { String publicKeyString = null; try { - String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + String abhaAuthToken = generateAuthSessionService.getAbhaAuthToken(); MultiValueMap headers = new LinkedMultiValueMap<>(); headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); @@ -258,11 +261,11 @@ public String verifyAuthByAbdm(String request) throws FHIRException { df.setTimeZone(tz); String nowAsISO = df.format(new Date()); headers.add("TIMESTAMP", nowAsISO); - headers.add("Authorization", ndhmAuthToken); + headers.add("Authorization", abhaAuthToken); LoginMethod loginMethod = InputMapper.gson().fromJson(request, LoginMethod.class); - publicKeyString = certificateKeyService.getCertPublicKey(ndhmAuthToken); + publicKeyString = certificateKeyService.getCertPublicKey(abhaAuthToken); if (loginMethod.getLoginId() != null) { encryptedLoginId = encryption.encrypt(loginMethod.getLoginId(), publicKeyString); } @@ -391,7 +394,7 @@ public String getAbhaCardPrinted(String reqObj) throws FHIRException { try { - String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + String abhaAuthToken = generateAuthSessionService.getAbhaAuthToken(); MultiValueMap headers = new LinkedMultiValueMap<>(); headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); @@ -402,7 +405,7 @@ public String getAbhaCardPrinted(String reqObj) throws FHIRException { df.setTimeZone(tz); String nowAsISO = df.format(new Date()); headers.add("TIMESTAMP", nowAsISO); - headers.add("Authorization", ndhmAuthToken); + headers.add("Authorization", abhaAuthToken); JsonObject stringReqObj = JsonParser.parseString(reqObj).getAsJsonObject(); if (stringReqObj.has("xToken") && stringReqObj.get("xToken") != null) { diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/GenerateAuthSessionService.java b/src/main/java/com/wipro/fhir/service/v3/abha/GenerateAuthSessionService.java new file mode 100644 index 0000000..6ff58fc --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/v3/abha/GenerateAuthSessionService.java @@ -0,0 +1,11 @@ +package com.wipro.fhir.service.v3.abha; + +import com.wipro.fhir.utils.exception.FHIRException; + +public interface GenerateAuthSessionService { + + String generateAbhaAuthToken() throws FHIRException; + + String getAbhaAuthToken() throws FHIRException; + +} diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/GenerateAuthSessionServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/GenerateAuthSessionServiceImpl.java new file mode 100644 index 0000000..9074fbd --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/v3/abha/GenerateAuthSessionServiceImpl.java @@ -0,0 +1,124 @@ +package com.wipro.fhir.service.v3.abha; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; + +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.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.wipro.fhir.data.healthID.Authorize; +import com.wipro.fhir.service.ndhm.Common_NDHMService; +import com.wipro.fhir.utils.exception.FHIRException; + +@Service +public class GenerateAuthSessionServiceImpl implements GenerateAuthSessionService { + + Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + private static String ABHA_AUTH_TOKEN; + private static Long ABHA_TOKEN_EXP; + + @Autowired + private Common_NDHMService common_NDHMService; + + @Value("${clientID}") + private String clientID; + + @Value("${clientSecret}") + private String clientSecret; + + @Value("${x-CM-ID}") + private String xCMId; + + @Value("${abdmV3UserAuthenticate}") + private String abdmV3UserAuthenticate; + + @Override + public String generateAbhaAuthToken() throws FHIRException { + + RestTemplate restTemplate = new RestTemplate(); + Authorize obj = new Authorize(); + String res = null; + + try { + obj.setClientId(clientID); + obj.setClientSecret(clientSecret); + obj.setGrantType("client_credentials"); + String requestOBJ = new Gson().toJson(obj); + + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("X-CM-ID", xCMId); + + HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); + ResponseEntity responseEntity = restTemplate.exchange(abdmV3UserAuthenticate, HttpMethod.POST, + httpEntity, String.class); + + String responseStrLogin=common_NDHMService.getBody(responseEntity); + if (responseStrLogin != null) { + JsonObject jsnOBJ = JsonParser.parseString(responseStrLogin).getAsJsonObject(); + ABHA_AUTH_TOKEN = "Bearer" + " " + jsnOBJ.get("accessToken").getAsString(); + Integer expiry = jsnOBJ.get("expiresIn").getAsInt(); + double time = expiry / 60; + Date date = new Date(); + java.sql.Date sqlDate = new java.sql.Date(date.getTime()); + Calendar ndhmCalendar = Calendar.getInstance(); + ndhmCalendar.setTime(sqlDate); + ndhmCalendar.add(Calendar.MINUTE, (int) time); + Date abhaTokenEndTime = ndhmCalendar.getTime(); + ABHA_TOKEN_EXP = abhaTokenEndTime.getTime(); + res = "success"; + } else + throw new FHIRException("NDHM_FHIR Error while accessing authenticate API"); + } catch (Exception e) { + throw new FHIRException("NDHM_FHIR Error while accessing authenticate API " + e); + } + return res; + } + @Override + public String getAbhaAuthToken() throws FHIRException { + try { + if (ABHA_AUTH_TOKEN == null || ABHA_TOKEN_EXP == null + || ABHA_TOKEN_EXP < System.currentTimeMillis()) { + String authenticateMsg = generateAbhaAuthToken(); + + if (authenticateMsg.equalsIgnoreCase("success")) + logger.info("NDHM_FHIR NDHM V3 authentication success at : " + System.currentTimeMillis()); + else { + logger.error("NDHM_FHIR NDHM V3 user authentication failed at : " + System.currentTimeMillis()); + throw new FHIRException("ABHA user authentication failed."); + } + } + + } catch (Exception e) { + throw new FHIRException(e.getMessage()); + } + return ABHA_AUTH_TOKEN; + } + + +} diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3Service.java b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3Service.java index 0ad41fc..92bc9d1 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3Service.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3Service.java @@ -8,4 +8,8 @@ public interface LoginAbhaV3Service { String verifyAbhaLogin(String request) throws FHIRException; + String verifyProfileLoginUser(String tToken, String txnId, String abhaNumber) throws FHIRException; + + String getWebLoginPhrCard(String reqObj) throws FHIRException; + } diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java index 90e759b..7e8e9ff 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java @@ -31,39 +31,45 @@ import com.wipro.fhir.data.v3.abhaCard.OtpRequest; import com.wipro.fhir.data.v3.abhaCard.RequestOTPEnrollment; import com.wipro.fhir.data.v3.abhaCard.VerifyAbhaLogin; +import com.wipro.fhir.data.v3.abhaCard.VerifyProfileUserLogin; import com.wipro.fhir.service.ndhm.Common_NDHMService; import com.wipro.fhir.service.ndhm.GenerateSession_NDHMService; import com.wipro.fhir.utils.Encryption; import com.wipro.fhir.utils.exception.FHIRException; -import com.wipro.fhir.utils.http.HttpUtils; import com.wipro.fhir.utils.mapper.InputMapper; @Service public class LoginAbhaV3ServiceImpl implements LoginAbhaV3Service { - + @Autowired - private GenerateSession_NDHMService generateSession_NDHM; + private GenerateAuthSessionService generateAuthSessionService; @Autowired private Common_NDHMService common_NDHMService; @Autowired private Encryption encryption; @Autowired private CertificateKeyService certificateKeyService; - + @Value("${abhaLoginRequestOtp}") String abhaLoginRequestOtp; - + @Value("${webLoginAbhaRequestOtp}") String webLoginAbhaRequestOtp; - + @Value("${webLoginAbhaVerify}") String webLoginAbhaVerify; - + @Value("${verifyAbhaLogin}") String verifyAbhaLoginUrl; + + @Value("${abhaProfileLoginVerifyUser}") + String abhaProfileLoginVerifyUser; + @Value("${webLoginPhrCard}") + String abhawebProfileLoginPhrCard; + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - + @Override public String requestOtpForAbhaLogin(String request) throws FHIRException { String res = null; @@ -74,7 +80,7 @@ public String requestOtpForAbhaLogin(String request) throws FHIRException { ResponseEntity responseEntity; try { - String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + String abhaAuthToken = generateAuthSessionService.getAbhaAuthToken(); MultiValueMap headers = new LinkedMultiValueMap<>(); headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); @@ -85,38 +91,44 @@ public String requestOtpForAbhaLogin(String request) throws FHIRException { df.setTimeZone(tz); String nowAsISO = df.format(new Date()); headers.add("TIMESTAMP", nowAsISO); - headers.add("Authorization", ndhmAuthToken); + headers.add("Authorization", abhaAuthToken); RequestOTPEnrollment reqOtpEnrollment = new RequestOTPEnrollment(); LoginAbhaRequest loginAbhaRequest = InputMapper.gson().fromJson(request, LoginAbhaRequest.class); - publicKeyString = certificateKeyService.getCertPublicKey(ndhmAuthToken); + publicKeyString = certificateKeyService.getCertPublicKey(abhaAuthToken); if (loginAbhaRequest.getLoginId() != null) { encryptedLoginId = encryption.encrypt(loginAbhaRequest.getLoginId(), publicKeyString); reqOtpEnrollment.setLoginId(encryptedLoginId); } - if ("AADHAAR".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && "abha-number".equalsIgnoreCase(loginAbhaRequest.getLoginHint() )) { + if ("AADHAAR".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) + && "abha-number".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) { reqOtpEnrollment.setScope(new String[] { "abha-login", "aadhaar-verify" }); reqOtpEnrollment.setLoginHint(loginAbhaRequest.getLoginHint()); reqOtpEnrollment.setOtpSystem("aadhaar"); - } else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && "abha-number".equalsIgnoreCase(loginAbhaRequest.getLoginHint() )) { + } else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) + && "abha-number".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) { reqOtpEnrollment.setScope(new String[] { "abha-login", "mobile-verify" }); reqOtpEnrollment.setLoginHint(loginAbhaRequest.getLoginHint()); reqOtpEnrollment.setOtpSystem("abdm"); - } else if ("aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && "abha-address".equalsIgnoreCase(loginAbhaRequest.getLoginHint() )) { + } else if ("aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) + && "abha-address".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) { reqOtpEnrollment.setScope(new String[] { "abha-address-login", "aadhaar-verify" }); reqOtpEnrollment.setLoginHint(loginAbhaRequest.getLoginHint()); reqOtpEnrollment.setOtpSystem("aadhaar"); - } else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && "abha-address".equalsIgnoreCase(loginAbhaRequest.getLoginHint() )) { + } else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) + && "abha-address".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) { reqOtpEnrollment.setScope(new String[] { "abha-address-login", "mobile-verify" }); reqOtpEnrollment.setLoginHint(loginAbhaRequest.getLoginHint()); reqOtpEnrollment.setOtpSystem("abdm"); - } else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && "mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) ) { + } else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) + && "mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())) { reqOtpEnrollment.setScope(new String[] { "abha-login", "mobile-verify" }); reqOtpEnrollment.setLoginHint("mobile"); reqOtpEnrollment.setOtpSystem("abdm"); - } else if ("aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && "aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) ) { + } else if ("aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) + && "aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())) { reqOtpEnrollment.setScope(new String[] { "abha-login", "aadhaar-verify" }); reqOtpEnrollment.setLoginHint("aadhaar"); reqOtpEnrollment.setOtpSystem("aadhaar"); @@ -128,12 +140,11 @@ public String requestOtpForAbhaLogin(String request) throws FHIRException { logger.info("ABDM reqobj for request otp for Abha login: " + requestOBJ); HttpEntity httpEntity = new HttpEntity<>(requestOBJ, headers); - if("abha-address".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) { - responseEntity = restTemplate.exchange(webLoginAbhaRequestOtp, HttpMethod.POST, - httpEntity, String.class); + if ("abha-address".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) { + responseEntity = restTemplate.exchange(webLoginAbhaRequestOtp, HttpMethod.POST, httpEntity, + String.class); } else { - responseEntity = restTemplate.exchange(abhaLoginRequestOtp, HttpMethod.POST, - httpEntity, String.class); + responseEntity = restTemplate.exchange(abhaLoginRequestOtp, HttpMethod.POST, httpEntity, String.class); } logger.info("ABDM response for response otp for Abha login: " + responseEntity); @@ -154,8 +165,7 @@ public String requestOtpForAbhaLogin(String request) throws FHIRException { return res; } - - + @Override public String verifyAbhaLogin(String request) throws FHIRException { Map responseMap = new HashMap<>(); @@ -166,7 +176,7 @@ public String verifyAbhaLogin(String request) throws FHIRException { ResponseEntity responseEntity; try { - String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); + String abhaAuthToken = generateAuthSessionService.getAbhaAuthToken(); MultiValueMap headers = new LinkedMultiValueMap<>(); headers.add("Content-Type", MediaType.APPLICATION_JSON.toString()); headers.add("REQUEST-ID", UUID.randomUUID().toString()); @@ -176,16 +186,16 @@ public String verifyAbhaLogin(String request) throws FHIRException { df.setTimeZone(tz); String nowAsISO = df.format(new Date()); headers.add("TIMESTAMP", nowAsISO); - headers.add("Authorization", ndhmAuthToken); + headers.add("Authorization", abhaAuthToken); // Create the enrollByAadhar object VerifyAbhaLogin verifyAbhaLogin = new VerifyAbhaLogin(); LoginMethod loginData = InputMapper.gson().fromJson(request, LoginMethod.class); - publicKeyString = certificateKeyService.getCertPublicKey(ndhmAuthToken); + publicKeyString = certificateKeyService.getCertPublicKey(abhaAuthToken); if (loginData.getLoginId() != null) { encryptedLoginId = encryption.encrypt(loginData.getLoginId(), publicKeyString); } - + OtpRequest otp = new OtpRequest(); otp.setTxnId(loginData.getTxnId()); @@ -198,29 +208,28 @@ public String verifyAbhaLogin(String request) throws FHIRException { verifyAbhaLogin.setAuthData(authDataMap); if ("AADHAAR".equalsIgnoreCase(loginData.getLoginMethod())) { - verifyAbhaLogin.setScope(new String[] {"abha-login", "aadhaar-verify" } ); + verifyAbhaLogin.setScope(new String[] { "abha-login", "aadhaar-verify" }); } else if ("MOBILE".equalsIgnoreCase(loginData.getLoginMethod())) { - verifyAbhaLogin.setScope(new String[] {"abha-login", "mobile-verify" } ); + verifyAbhaLogin.setScope(new String[] { "abha-login", "mobile-verify" }); } else if ("abha-mobile".equalsIgnoreCase(loginData.getLoginMethod())) { - verifyAbhaLogin.setScope(new String[] {"abha-address-login", "mobile-verify" } ); - + verifyAbhaLogin.setScope(new String[] { "abha-address-login", "mobile-verify" }); + } else if ("abha-aadhaar".equalsIgnoreCase(loginData.getLoginMethod())) { - verifyAbhaLogin.setScope(new String[] {"abha-address-login", "aadhaar-verify" } ); + verifyAbhaLogin.setScope(new String[] { "abha-address-login", "aadhaar-verify" }); } - + String requestObj = new Gson().toJson(verifyAbhaLogin); logger.info("ABDM request for verify abha login: " + requestObj); HttpEntity httpEntity = new HttpEntity<>(requestObj, headers); - - if("abha-aadhaar".equalsIgnoreCase(loginData.getLoginMethod()) || "abha-mobile".equalsIgnoreCase(loginData.getLoginMethod())) { - responseEntity = restTemplate.exchange(webLoginAbhaVerify, HttpMethod.POST, - httpEntity, String.class); + + if ("abha-aadhaar".equalsIgnoreCase(loginData.getLoginMethod()) + || "abha-mobile".equalsIgnoreCase(loginData.getLoginMethod())) { + responseEntity = restTemplate.exchange(webLoginAbhaVerify, HttpMethod.POST, httpEntity, String.class); } else { - responseEntity = restTemplate.exchange(verifyAbhaLoginUrl, HttpMethod.POST, - httpEntity, String.class); + responseEntity = restTemplate.exchange(verifyAbhaLoginUrl, HttpMethod.POST, httpEntity, String.class); } String responseStrLogin = common_NDHMService.getBody(responseEntity); @@ -233,14 +242,21 @@ public String verifyAbhaLogin(String request) throws FHIRException { if (authResult != null && (authResult.equalsIgnoreCase("success"))) { if (jsonResponse.has("accounts")) { - responseMap.put("abhaDetails", jsonResponse.get("accounts").getAsJsonArray().get(0).getAsJsonObject().toString()); + String abhaNumber = jsonResponse.get("accounts").getAsJsonArray().get(0).getAsJsonObject() + .get("ABHANumber").getAsString(); + responseMap.put("abhaDetails", + jsonResponse.get("accounts").getAsJsonArray().get(0).getAsJsonObject().toString()); responseMap.put("txnId", jsonResponse.get("txnId").getAsString()); - if (jsonResponse.has("token")) { + if ("MOBILE".equalsIgnoreCase(loginData.getLoginMethod()) && jsonResponse.has("token")) { + String xtoken = verifyProfileLoginUser(jsonResponse.get("token").getAsString(), + jsonResponse.get("txnId").getAsString(), abhaNumber); + responseMap.put("xToken", xtoken); + } else if (jsonResponse.has("token")) { responseMap.put("xToken", jsonResponse.get("token").getAsString()); } - } else if(jsonResponse.has("users")) { - responseMap.put("abhaDetails", jsonResponse.get("users").getAsJsonArray().get(0).getAsJsonObject().toString()); - responseMap.put("txnId", jsonResponse.get("txnId").getAsString()); + } else if (jsonResponse.has("users")) { + responseMap.put("abhaDetails", + jsonResponse.get("users").getAsJsonArray().get(0).getAsJsonObject().toString()); if (jsonResponse.has("tokens") && jsonResponse.get("tokens").isJsonObject()) { JsonObject tokensObject = jsonResponse.get("tokens").getAsJsonObject(); if (tokensObject.has("token") && !tokensObject.get("token").isJsonNull()) { @@ -250,7 +266,7 @@ public String verifyAbhaLogin(String request) throws FHIRException { } } } else { - String message = jsonResponse.get("message").getAsString(); + String message = jsonResponse.get("message").getAsString(); throw new FHIRException(message); } } else { @@ -263,5 +279,98 @@ public String verifyAbhaLogin(String request) throws FHIRException { return responseMap.toString(); } + @Override + public String verifyProfileLoginUser(String tToken, String txnId, String abhaNumber) throws FHIRException { + + RestTemplate restTemplate = new RestTemplate(); + ResponseEntity responseEntity; + String token = null; + + try { + String abhaAuthToken = generateAuthSessionService.getAbhaAuthToken(); + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON.toString()); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("Authorization", abhaAuthToken); + headers.add("T-token", "Bearer " + tToken); + + VerifyProfileUserLogin verifyUser = new VerifyProfileUserLogin(); + verifyUser.setABHANumber(abhaNumber); + verifyUser.setTxnId(txnId); + + String requestObj = new Gson().toJson(verifyUser); + logger.info("ABDM request for verify profile user login: " + requestObj); + HttpEntity httpEntity = new HttpEntity<>(requestObj, headers); + + responseEntity = restTemplate.exchange(abhaProfileLoginVerifyUser, HttpMethod.POST, httpEntity, + String.class); + + logger.info("ABDM response for response otp for Abha login: " + responseEntity); + String responseStrLogin = common_NDHMService.getBody(responseEntity); + if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(200) && responseEntity.hasBody()) { + JsonObject jsnOBJ = JsonParser.parseString(responseStrLogin).getAsJsonObject(); + token = jsnOBJ.get("token").getAsString(); + } + } catch (Exception e) { + throw new FHIRException(e.getMessage()); + } + + return token; + } + + + @Override + public String getWebLoginPhrCard(String reqObj) throws FHIRException { + + String res = null; + Map responseMap = new HashMap<>(); + RestTemplate restTemplate = new RestTemplate(); + + + try { + String abhaAuthToken = generateAuthSessionService.getAbhaAuthToken(); + + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON + ";charset=utf-8"); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("Authorization", abhaAuthToken); + + JsonObject stringReqObj = JsonParser.parseString(reqObj).getAsJsonObject(); + if (stringReqObj.has("xToken") && stringReqObj.get("xToken") != null) { + String xToken = stringReqObj.get("xToken").getAsString(); + headers.add("X-token", "Bearer " + xToken); + } + HttpEntity httpEntity = new HttpEntity<>(headers); + ResponseEntity responseEntity = restTemplate.exchange(abhawebProfileLoginPhrCard, HttpMethod.GET, httpEntity, + String.class); + + logger.info("ABDM response for print Abha card:" + responseEntity); + String responseStrLogin = common_NDHMService.getBody(responseEntity); + if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(202)) { + responseMap.put("png", responseStrLogin); + res = new Gson().toJson(responseMap); + } else { + throw new FHIRException(responseEntity.getBody()); + } + + } catch (Exception e) { + throw new FHIRException(e.getMessage()); + } + return res; + + } + } From cc1b2527bdd3f04d06f6a60942c032ce7e9d583e Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Tue, 25 Feb 2025 10:40:36 +0530 Subject: [PATCH 10/26] committed coderabitai suggested --- src/main/environment/common_dev.properties | 1 - .../wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index db18ad9..3e012e9 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -96,7 +96,6 @@ abhaProfileLoginVerifyUser = https://abhasbx.abdm.gov.in/abha/api/v3/profile/log requestAuthByAbdm = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/auth/byAbdm webLoginAbhaRequestOtp = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/request/otp webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify -webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify webLoginPhrCard = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/profile/abha/phr-card x-CM-ID= sbx diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java index 7e8e9ff..7c15d3a 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java @@ -123,12 +123,12 @@ public String requestOtpForAbhaLogin(String request) throws FHIRException { reqOtpEnrollment.setLoginHint(loginAbhaRequest.getLoginHint()); reqOtpEnrollment.setOtpSystem("abdm"); } else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) - && "mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())) { + && "mobile".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) { reqOtpEnrollment.setScope(new String[] { "abha-login", "mobile-verify" }); reqOtpEnrollment.setLoginHint("mobile"); reqOtpEnrollment.setOtpSystem("abdm"); } else if ("aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) - && "aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())) { + && "aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) { reqOtpEnrollment.setScope(new String[] { "abha-login", "aadhaar-verify" }); reqOtpEnrollment.setLoginHint("aadhaar"); reqOtpEnrollment.setOtpSystem("aadhaar"); From c38d0995378e199caf284b81b003959f96f8c974 Mon Sep 17 00:00:00 2001 From: Karyamsetty Helen Grace Date: Wed, 26 Feb 2025 12:53:54 +0530 Subject: [PATCH 11/26] Revert "jwt implementation changes (#53)" This reverts commit 5e16b7d4ea27f66e91553d8bbb159648ff10a82b. --- .github/workflows/build-on-pull-request.yml | 3 +- .github/workflows/package.yml | 4 +- .github/workflows/sast.yml | 4 +- pom.xml | 40 ++---- src/main/environment/common_ci.properties | 3 +- src/main/environment/common_dev.properties | 1 - .../environment/common_example.properties | 1 - src/main/environment/common_test.properties | 1 - .../com/wipro/fhir/FhirApiApplication.java | 21 --- .../com/wipro/fhir/config/RedisConfig.java | 40 ------ .../java/com/wipro/fhir/data/users/User.java | 28 ---- .../wipro/fhir/repo/user/UserLoginRepo.java | 16 --- .../service/common/CommonServiceImpl.java | 88 +++--------- .../java/com/wipro/fhir/utils/CookieUtil.java | 31 ----- .../com/wipro/fhir/utils/FilterConfig.java | 19 --- .../fhir/utils/JwtAuthenticationUtil.java | 125 ------------------ .../fhir/utils/JwtUserIdValidationFilter.java | 111 ---------------- .../java/com/wipro/fhir/utils/JwtUtil.java | 68 ---------- 18 files changed, 37 insertions(+), 567 deletions(-) delete mode 100644 src/main/java/com/wipro/fhir/config/RedisConfig.java delete mode 100644 src/main/java/com/wipro/fhir/data/users/User.java delete mode 100644 src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java delete mode 100644 src/main/java/com/wipro/fhir/utils/CookieUtil.java delete mode 100644 src/main/java/com/wipro/fhir/utils/FilterConfig.java delete mode 100644 src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java delete mode 100644 src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java delete mode 100644 src/main/java/com/wipro/fhir/utils/JwtUtil.java diff --git a/.github/workflows/build-on-pull-request.yml b/.github/workflows/build-on-pull-request.yml index 695b179..744b905 100644 --- a/.github/workflows/build-on-pull-request.yml +++ b/.github/workflows/build-on-pull-request.yml @@ -17,7 +17,6 @@ jobs: uses: actions/setup-java@v2 with: java-version: 17 - distribution: 'zulu' - + distribution: 'adopt' - name: Build with Maven run: mvn clean install diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 769fce7..5cc0ca0 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -26,7 +26,7 @@ jobs: uses: actions/setup-java@v2 with: java-version: 17 - distribution: 'zulu' + distribution: 'adopt' - name: Build with Maven run: mvn clean install -DENV_VAR=${{ env.ENV_VAR }} @@ -35,7 +35,7 @@ jobs: run: mvn -B package --file pom.xml - name: Upload WAR file as artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v3 with: name: FHIR-API path: target/fhirapi-v1.0.war diff --git a/.github/workflows/sast.yml b/.github/workflows/sast.yml index a886904..eb8d6b3 100644 --- a/.github/workflows/sast.yml +++ b/.github/workflows/sast.yml @@ -41,10 +41,10 @@ jobs: uses: actions/setup-java@v2 with: java-version: 17 - distribution: 'zulu' + distribution: 'adopt' - name: Build with Maven - run: mvn clean install + run: mvn clean install -DENV_VAR=test - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 diff --git a/pom.xml b/pom.xml index 22e8b75..a345c2c 100644 --- a/pom.xml +++ b/pom.xml @@ -58,10 +58,10 @@ org.springframework.boot spring-boot-starter - - co.elastic.logging - logback-ecs-encoder - 1.3.2 + + co.elastic.logging + logback-ecs-encoder + 1.3.2 @@ -189,7 +189,8 @@ spring-boot-starter-mail - + ca.uhn.hapi.fhir hapi-fhir-structures-r4 @@ -197,7 +198,8 @@ - + ca.uhn.hapi.fhir org.hl7.fhir.utilities @@ -233,27 +235,6 @@ json-path 2.9.0 - - - io.jsonwebtoken - jjwt-api - 0.12.6 - - - - io.jsonwebtoken - jjwt-impl - 0.12.6 - runtime - - - - io.jsonwebtoken - jjwt-jackson - 0.12.6 - runtime - - @@ -269,7 +250,7 @@ HTML nvd - + org.apache.maven.plugins @@ -348,7 +329,8 @@ ${target-properties} and ${source-properties} - diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index f3137e0..ed70c81 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -110,5 +110,4 @@ logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO #ELK logging file name -logging.file.name=@env.FHIR_API_LOGGING_FILE_NAME@ -jwt.secret=@env.JWT_SECRET_KEY@ \ No newline at end of file +logging.file.name=@env.FHIR_API_LOGGING_FILE_NAME@ \ No newline at end of file diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index 6210f9e..3e012e9 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -107,4 +107,3 @@ logging.level.org.springframework.web=INFO logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO -jwt.secret= diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index 0679bed..803d225 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -109,4 +109,3 @@ logging.level.org.springframework.web=INFO logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO -jwt.secret= diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties index 44e1523..db18ad9 100644 --- a/src/main/environment/common_test.properties +++ b/src/main/environment/common_test.properties @@ -108,4 +108,3 @@ logging.level.org.springframework.web=INFO logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO -jwt.secret= diff --git a/src/main/java/com/wipro/fhir/FhirApiApplication.java b/src/main/java/com/wipro/fhir/FhirApiApplication.java index d732a3f..0395010 100644 --- a/src/main/java/com/wipro/fhir/FhirApiApplication.java +++ b/src/main/java/com/wipro/fhir/FhirApiApplication.java @@ -26,12 +26,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; -import org.springframework.data.redis.serializer.StringRedisSerializer; - -import com.wipro.fhir.data.users.User; @SpringBootApplication public class FhirApiApplication { @@ -39,19 +33,4 @@ public class FhirApiApplication { public static void main(String[] args) { SpringApplication.run(FhirApiApplication.class, args); } - - @Bean - public RedisTemplate redisTemplate(RedisConnectionFactory factory) { - RedisTemplate template = new RedisTemplate<>(); - template.setConnectionFactory(factory); - - // Use StringRedisSerializer for keys (userId) - template.setKeySerializer(new StringRedisSerializer()); - - // Use Jackson2JsonRedisSerializer for values (Users objects) - Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(User.class); - template.setValueSerializer(serializer); - - return template; - } } diff --git a/src/main/java/com/wipro/fhir/config/RedisConfig.java b/src/main/java/com/wipro/fhir/config/RedisConfig.java deleted file mode 100644 index d29e7c3..0000000 --- a/src/main/java/com/wipro/fhir/config/RedisConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.wipro.fhir.config; - -import org.springframework.cache.annotation.EnableCaching; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; -import org.springframework.data.redis.serializer.StringRedisSerializer; -import org.springframework.session.data.redis.config.ConfigureRedisAction; - -import com.wipro.fhir.data.users.User; - -@Configuration -@EnableCaching -public class RedisConfig { - - @Bean - public ConfigureRedisAction configureRedisAction() { - return ConfigureRedisAction.NO_OP; - } - - @Bean - public RedisTemplate redisTemplate(RedisConnectionFactory factory) { - RedisTemplate template = new RedisTemplate<>(); - template.setConnectionFactory(factory); - - // Use StringRedisSerializer for keys (userId) - template.setKeySerializer(new StringRedisSerializer()); - - // Use Jackson2JsonRedisSerializer for values (Users objects) - Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(User.class); - template.setValueSerializer(serializer); - - return template; - } - -} - - diff --git a/src/main/java/com/wipro/fhir/data/users/User.java b/src/main/java/com/wipro/fhir/data/users/User.java deleted file mode 100644 index c31049e..0000000 --- a/src/main/java/com/wipro/fhir/data/users/User.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.wipro.fhir.data.users; - -import java.io.Serializable; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.Table; -import lombok.Data; - -@Entity -@Table(name = "m_user") -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class User implements Serializable { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "UserID") - private Long userID; - @Column(name = "userName") - private String userName; - @Column(name = "Deleted", insertable = false, updatable = true) - private Boolean deleted; -} diff --git a/src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java b/src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java deleted file mode 100644 index 1267ab6..0000000 --- a/src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.wipro.fhir.repo.user; - -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.CrudRepository; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import com.wipro.fhir.data.users.User; - -@Repository -public interface UserLoginRepo extends CrudRepository { - - @Query(" SELECT u FROM User u WHERE u.userID = :userID AND u.deleted = false ") - public User getUserByUserID(@Param("userID") Long userID); - -} diff --git a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java index 5fcf125..0c87321 100644 --- a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java @@ -58,13 +58,11 @@ import com.wipro.fhir.data.mongo.care_context.NDHMResponse; import com.wipro.fhir.data.mongo.care_context.Notification; import com.wipro.fhir.data.mongo.care_context.PatientCareContexts; -import com.wipro.fhir.data.mongo.care_context.PatientCareContextsStringOBJ; import com.wipro.fhir.data.mongo.care_context.SMSNotify; import com.wipro.fhir.data.patient.PatientDemographic; import com.wipro.fhir.data.patient_data_handler.PatientDemographicModel_NDHM_Patient_Profile; import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; import com.wipro.fhir.data.request_handler.ResourceRequestHandler; -import com.wipro.fhir.data.users.User; import com.wipro.fhir.repo.common.PatientEligibleForResourceCreationRepo; import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; import com.wipro.fhir.repo.mongo.amrit_resource.AMRIT_ResourceMongoRepo; @@ -103,12 +101,6 @@ public class CommonServiceImpl implements CommonService { private static String authKey; private UUID uuid; - - // public static String NDHM_AUTH_TOKEN; - // public static Long NDHM_TOKEN_EXP; - // public static String NDHM_OTP_TOKEN; - - @Value("${clientID}") private String clientID; @@ -169,8 +161,7 @@ public String processResourceOperation() throws FHIRException { String response = null; // list of patient eligible for resource creation List pList = getPatientListForResourceEligible(); - logger.info("No of records available to create FHIR in last 2 dagetPatientListForResourceEligibleys : " - + pList.size()); + logger.info("No of records available to create FHIR in last 2 dagetPatientListForResourceEligibleys : " + pList.size()); ResourceRequestHandler resourceRequestHandler; for (PatientEligibleForResourceCreation p : pList) { @@ -299,38 +290,6 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe if (pDemo != null && pVisit != null) { - -// JsonObject jsnOBJ = new JsonObject(); -// JsonParser jsnParser = new JsonParser(); -// JsonElement jsnElmnt = jsnParser.parse(requestObj); -// jsnOBJ = jsnElmnt.getAsJsonObject(); - - PatientCareContextsStringOBJ patientCareContextsStringOBJ = new PatientCareContextsStringOBJ(); - - // wrong variable name in request obj for benregid, need to correct in main - // request obj first -// Long benID = null; -// Long benRegID = null; -// Long visitCode = null; -// -// if (jsnOBJ.has("beneficiaryID") && jsnOBJ.get("beneficiaryID") != null) -// benRegID = jsnOBJ.get("beneficiaryID").getAsLong(); -// if (jsnOBJ.has("visitCode") && jsnOBJ.get("visitCode") != null) -// visitCode = jsnOBJ.get("visitCode").getAsLong(); -// String healthID = jsnOBJ.get("healthID").getAsString(); -// String healthIDNumber = jsnOBJ.get("healthIdNumber").getAsString(); -// String visitCategory = jsnOBJ.get("visitCategory").getAsString(); -// String phoneNo; -// String gender; -// String yearOfBirth; -// String name; -// String email; - - // get benid -// if (benRegID != null) -// benID = benHealthIDMappingRepo.getBenID(benRegID); - - // fetch abdm facility id logger.info("********t_benvisistData fetch request pvisit data :", pVisit); @@ -340,7 +299,6 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe ArrayList ccList = new ArrayList<>(); CareContexts cc = new CareContexts(); - logger.info("********t_benvisistData fetch response : {}", res); cc.setReferenceNumber(pVisit.getVisitCode() != null ? pVisit.getVisitCode().toString() : null); @@ -352,22 +310,16 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe cc.setCareContextLinkedDate(resData[1] != null ? resData[1].toString() : null); } - logger.info("********data to be saved in mongo :", cc); PatientCareContexts pcc; - PatientCareContexts resultSet = null; - - - logger.info("********data to be saved in mongo :", cc); - PatientCareContexts pcc1; if (pDemo.getBeneficiaryID() != null) { - pcc1 = patientCareContextsMongoRepo.findByIdentifier(pDemo.getBeneficiaryID().toString()); + pcc = patientCareContextsMongoRepo.findByIdentifier(pDemo.getBeneficiaryID().toString()); - if (pcc1 != null && pcc1.getIdentifier() != null) { + if (pcc != null && pcc.getIdentifier() != null) { // Get the existing careContextsList - if (pcc1.getCareContextsList() != null && pcc1.getCareContextsList().size() > 0) { - ccList = pcc1.getCareContextsList(); + if (pcc.getCareContextsList() != null && pcc.getCareContextsList().size() > 0) { + ccList = pcc.getCareContextsList(); // Check if the visitCode is already in the careContextsList for (CareContexts existingContext : ccList) { @@ -378,8 +330,8 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe } } ccList.add(cc); - pcc1.setCareContextsList(ccList); - patientCareContextsMongoRepo.save(pcc1); + pcc.setCareContextsList(ccList); + patientCareContextsMongoRepo.save(pcc); } // } // if (pcc != null && pcc.getIdentifier() != null) { @@ -389,20 +341,20 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe // resultSet = patientCareContextsMongoRepo.save(pcc); // } else { - pcc1 = new PatientCareContexts(); - pcc1.setCaseReferenceNumber(pDemo.getBeneficiaryID().toString()); - pcc1.setIdentifier(pDemo.getBeneficiaryID().toString()); + pcc = new PatientCareContexts(); + pcc.setCaseReferenceNumber(pDemo.getBeneficiaryID().toString()); + pcc.setIdentifier(pDemo.getBeneficiaryID().toString()); if (pDemo.getGenderID() != null) { switch (pDemo.getGenderID()) { case 1: - pcc1.setGender("M"); + pcc.setGender("M"); break; case 2: - pcc1.setGender("F"); + pcc.setGender("F"); break; case 3: - pcc1.setGender("O"); + pcc.setGender("O"); break; default: @@ -410,19 +362,19 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe } } if (pDemo.getName() != null) - pcc1.setName(pDemo.getName()); + pcc.setName(pDemo.getName()); if (pDemo.getDOB() != null) - pcc1.setYearOfBirth(pDemo.getDOB().toString().split("-")[0]); + pcc.setYearOfBirth(pDemo.getDOB().toString().split("-")[0]); if (pDemo.getPreferredPhoneNo() != null) - pcc1.setPhoneNumber(pDemo.getPreferredPhoneNo()); + pcc.setPhoneNumber(pDemo.getPreferredPhoneNo()); if (pDemo.getHealthID() != null) - pcc1.setHealthId(pDemo.getHealthID()); + pcc.setHealthId(pDemo.getHealthID()); if (pDemo.getHealthIdNo() != null) - pcc1.setHealthNumber(pDemo.getHealthIdNo()); + pcc.setHealthNumber(pDemo.getHealthIdNo()); ccList.add(cc); - pcc1.setCareContextsList(ccList); + pcc.setCareContextsList(ccList); // save carecontext back to mongo - patientCareContextsMongoRepo.save(pcc1); + patientCareContextsMongoRepo.save(pcc); } } diff --git a/src/main/java/com/wipro/fhir/utils/CookieUtil.java b/src/main/java/com/wipro/fhir/utils/CookieUtil.java deleted file mode 100644 index 3ccec9d..0000000 --- a/src/main/java/com/wipro/fhir/utils/CookieUtil.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.wipro.fhir.utils; - -import java.util.Arrays; -import java.util.Optional; - -import org.springframework.stereotype.Service; - -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -@Service -public class CookieUtil { - - public Optional getCookieValue(HttpServletRequest request, String cookieName) { - Cookie[] cookies = request.getCookies(); - if (cookies != null) { - for (Cookie cookie : cookies) { - if (cookieName.equals(cookie.getName())) { - return Optional.of(cookie.getValue()); - } - } - } - return Optional.empty(); - } - - public String getJwtTokenFromCookie(HttpServletRequest request) { - return Arrays.stream(request.getCookies()).filter(cookie -> "Jwttoken".equals(cookie.getName())) - .map(Cookie::getValue).findFirst().orElse(null); - } -} diff --git a/src/main/java/com/wipro/fhir/utils/FilterConfig.java b/src/main/java/com/wipro/fhir/utils/FilterConfig.java deleted file mode 100644 index 5a7ef36..0000000 --- a/src/main/java/com/wipro/fhir/utils/FilterConfig.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.wipro.fhir.utils; - -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class FilterConfig { - - @Bean - public FilterRegistrationBean jwtUserIdValidationFilter( - JwtAuthenticationUtil jwtAuthenticationUtil) { - FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); - registrationBean.setFilter(new JwtUserIdValidationFilter(jwtAuthenticationUtil)); - registrationBean.addUrlPatterns("/*"); // Apply filter to all API endpoints - return registrationBean; - } - -} diff --git a/src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java b/src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java deleted file mode 100644 index 61cdc90..0000000 --- a/src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.wipro.fhir.utils; - -import java.util.Optional; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; - -import com.wipro.fhir.data.users.User; -import com.wipro.fhir.repo.user.UserLoginRepo; - -import io.jsonwebtoken.Claims; -import jakarta.servlet.http.HttpServletRequest; - -@Component -public class JwtAuthenticationUtil { - - @Autowired - private CookieUtil cookieUtil; - @Autowired - private JwtUtil jwtUtil; - @Autowired - private RedisTemplate redisTemplate; - @Autowired - private UserLoginRepo userLoginRepo; - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - - public JwtAuthenticationUtil(CookieUtil cookieUtil, JwtUtil jwtUtil) { - this.cookieUtil = cookieUtil; - this.jwtUtil = jwtUtil; - } - - public ResponseEntity validateJwtToken(HttpServletRequest request) { - Optional jwtTokenOpt = cookieUtil.getCookieValue(request, "Jwttoken"); - - if (jwtTokenOpt.isEmpty()) { - return ResponseEntity.status(HttpStatus.UNAUTHORIZED) - .body("Error 401: Unauthorized - JWT Token is not set!"); - } - - String jwtToken = jwtTokenOpt.get(); - - // Validate the token - Claims claims = jwtUtil.validateToken(jwtToken); - if (claims == null) { - return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Error 401: Unauthorized - Invalid JWT Token!"); - } - - // Extract username from token - String usernameFromToken = claims.getSubject(); - if (usernameFromToken == null || usernameFromToken.isEmpty()) { - return ResponseEntity.status(HttpStatus.UNAUTHORIZED) - .body("Error 401: Unauthorized - Username is missing!"); - } - - // Return the username if valid - return ResponseEntity.ok(usernameFromToken); - } - - public boolean validateUserIdAndJwtToken(String jwtToken) throws Exception { - try { - // Validate JWT token and extract claims - Claims claims = jwtUtil.validateToken(jwtToken); - - if (claims == null) { - throw new Exception("Invalid JWT token."); - } - - String userId = claims.get("userId", String.class); - - // Check if user data is present in Redis - User user = getUserFromCache(userId); - if (user == null) { - // If not in Redis, fetch from DB and cache the result - user = fetchUserFromDB(userId); - } - if (user == null) { - throw new Exception("Invalid User ID."); - } - - return true; // Valid userId and JWT token - } catch (Exception e) { - logger.error("Validation failed: " + e.getMessage(), e); - throw new Exception("Validation error: " + e.getMessage(), e); - } - } - - private User getUserFromCache(String userId) { - String redisKey = "user_" + userId; // The Redis key format - User user = (User) redisTemplate.opsForValue().get(redisKey); - - if (user == null) { - logger.warn("User not found in Redis. Will try to fetch from DB."); - } else { - logger.info("User fetched successfully from Redis."); - } - - return user; // Returns null if not found - } - - private User fetchUserFromDB(String userId) { - // This method will only be called if the user is not found in Redis. - String redisKey = "user_" + userId; // Redis key format - - // Fetch user from DB - User user = userLoginRepo.getUserByUserID(Long.parseLong(userId)); - - if (user != null) { - // Cache the user in Redis for future requests (cache for 30 minutes) - redisTemplate.opsForValue().set(redisKey, user, 30, TimeUnit.MINUTES); - - // Log that the user has been stored in Redis - logger.info("User stored in Redis with key: " + redisKey); - } else { - logger.warn("User not found for userId: " + userId); - } - - return user; - } -} diff --git a/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java b/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java deleted file mode 100644 index 09ae81f..0000000 --- a/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.wipro.fhir.utils; - -import java.io.IOException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import jakarta.servlet.Filter; -import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; -import jakarta.servlet.ServletRequest; -import jakarta.servlet.ServletResponse; -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -@Component -public class JwtUserIdValidationFilter implements Filter { - - private final JwtAuthenticationUtil jwtAuthenticationUtil; - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - - public JwtUserIdValidationFilter(JwtAuthenticationUtil jwtAuthenticationUtil) { - this.jwtAuthenticationUtil = jwtAuthenticationUtil; - } - - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) - throws IOException, ServletException { - HttpServletRequest request = (HttpServletRequest) servletRequest; - HttpServletResponse response = (HttpServletResponse) servletResponse; - - String path = request.getRequestURI(); - String contextPath = request.getContextPath(); - logger.info("JwtUserIdValidationFilter invoked for path: " + path); - - // Log cookies for debugging - Cookie[] cookies = request.getCookies(); - if (cookies != null) { - for (Cookie cookie : cookies) { - if ("userId".equals(cookie.getName())) { - logger.warn("userId found in cookies! Clearing it..."); - clearUserIdCookie(response); // Explicitly remove userId cookie - } - } - } else { - logger.info("No cookies found in the request"); - } - - // Log headers for debugging - String jwtTokenFromHeader = request.getHeader("Jwttoken"); - logger.info("JWT token from header: "); - - // Skip login and public endpoints - if (path.equals(contextPath + "/user/userAuthenticate") - || path.equalsIgnoreCase(contextPath + "/user/logOutUserFromConcurrentSession") - || path.startsWith(contextPath + "/public")) { - logger.info("Skipping filter for path: " + path); - filterChain.doFilter(servletRequest, servletResponse); - return; - } - - try { - // Retrieve JWT token from cookies - String jwtTokenFromCookie = getJwtTokenFromCookies(request); - logger.info("JWT token from cookie: "); - - // Determine which token (cookie or header) to validate - String jwtToken = jwtTokenFromCookie != null ? jwtTokenFromCookie : jwtTokenFromHeader; - if (jwtToken == null) { - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "JWT token not found in cookies or headers"); - return; - } - - // Validate JWT token and userId - boolean isValid = jwtAuthenticationUtil.validateUserIdAndJwtToken(jwtToken); - - if (isValid) { - // If token is valid, allow the request to proceed - filterChain.doFilter(servletRequest, servletResponse); - } else { - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid JWT token"); - } - } catch (Exception e) { - logger.error("Authorization error: ", e); - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization error: " + e.getMessage()); - } - } - - private String getJwtTokenFromCookies(HttpServletRequest request) { - Cookie[] cookies = request.getCookies(); - if (cookies != null) { - for (Cookie cookie : cookies) { - if (cookie.getName().equals("Jwttoken")) { - return cookie.getValue(); - } - } - } - return null; - } - - private void clearUserIdCookie(HttpServletResponse response) { - Cookie cookie = new Cookie("userId", null); - cookie.setPath("/"); - cookie.setHttpOnly(true); - cookie.setSecure(true); - cookie.setMaxAge(0); // Invalidate the cookie - response.addCookie(cookie); - } -} diff --git a/src/main/java/com/wipro/fhir/utils/JwtUtil.java b/src/main/java/com/wipro/fhir/utils/JwtUtil.java deleted file mode 100644 index 6f22eb7..0000000 --- a/src/main/java/com/wipro/fhir/utils/JwtUtil.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.wipro.fhir.utils; - -import java.security.Key; -import java.util.Date; -import java.util.function.Function; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import io.jsonwebtoken.security.Keys; - -@Component -public class JwtUtil { - - @Value("${jwt.secret}") - private String SECRET_KEY; - - private static final long EXPIRATION_TIME = 24L * 60 * 60 * 1000; // 1 day in milliseconds - - // Generate a key using the secret - private Key getSigningKey() { - if (SECRET_KEY == null || SECRET_KEY.isEmpty()) { - throw new IllegalStateException("JWT secret key is not set in application.properties"); - } - return Keys.hmacShaKeyFor(SECRET_KEY.getBytes()); - } - - // Generate JWT Token - public String generateToken(String username, String userId) { - Date now = new Date(); - Date expiryDate = new Date(now.getTime() + EXPIRATION_TIME); - - // Include the userId in the JWT claims - return Jwts.builder().setSubject(username).claim("userId", userId) // Add userId as a claim - .setIssuedAt(now).setExpiration(expiryDate).signWith(getSigningKey(), SignatureAlgorithm.HS256) - .compact(); - } - - // Validate and parse JWT Token - public Claims validateToken(String token) { - try { - // Use the JwtParserBuilder correctly in version 0.12.6 - return Jwts.parser() // Correct method in 0.12.6 to get JwtParserBuilder - .setSigningKey(getSigningKey()) // Set the signing key - .build() // Build the JwtParser - .parseClaimsJws(token) // Parse and validate the token - .getBody(); - } catch (Exception e) { - return null; // Handle token parsing/validation errors - } - } - - public String extractUsername(String token) { - return extractClaim(token, Claims::getSubject); - } - - public T extractClaim(String token, Function claimsResolver) { - final Claims claims = extractAllClaims(token); - return claimsResolver.apply(claims); - } - - private Claims extractAllClaims(String token) { - return Jwts.parser().setSigningKey(getSigningKey()).build().parseClaimsJws(token).getBody(); - } -} From da3053d34e4c52d8a2e08feea543855a1394498e Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Wed, 26 Feb 2025 23:47:22 +0530 Subject: [PATCH 12/26] data Sync for FLW API changes --- .../healthID/CreateHealthIDWithMobileOTP.java | 29 ------ .../healthID/CreateHealthIdRecord.java | 79 ++++++++++++++++ .../data/healthID/HealthIDRequestAadhar.java | 78 ++-------------- .../service/healthID/HealthIDService.java | 1 + .../service/healthID/HealthIDServiceImpl.java | 89 +++++++++++++++++++ 5 files changed, 174 insertions(+), 102 deletions(-) create mode 100644 src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIdRecord.java diff --git a/src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithMobileOTP.java b/src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithMobileOTP.java index 30b4b17..5a5528e 100644 --- a/src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithMobileOTP.java +++ b/src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithMobileOTP.java @@ -109,35 +109,6 @@ public String verifyOTPAndGenerateHealthID( return response.toString(); } - /*** - * - * @param request - * @param Authorization - * @return BenRegID of beneficiary after mapping - */ - @CrossOrigin - @Operation(summary = "Map ABHA to beneficiary") - @PostMapping(value = { "/mapHealthIDToBeneficiary" }) - public String mapHealthIDToBeneficiary( - @Param(value = "{\"beneficiaryRegID\":\"Long\",\"beneficiaryID\":\"Long\",\"healthId\":\"String\",\"healthIdNumber\":\"String\"" - + "providerServiceMapId\":\"Integer\",\"createdBy\":\"String\"}") @RequestBody String request, - @RequestHeader(value = "Authorization") String Authorization) { - logger.info("NDHM_FHIR Map ABHA to beneficiary API request " + request); - OutputResponse response = new OutputResponse(); - try { - if (request != null) { - String s = healthIDService.mapHealthIDToBeneficiary(request); - response.setResponse(s); - } else - throw new FHIRException("NDHM_FHIR Empty request object"); - } catch (FHIRException e) { - response.setError(5000, e.getMessage()); - logger.error(e.toString()); - } - logger.info("NDHM_FHIR Map ABHA to beneficiary API response " + response.toString()); - return response.toString(); - } - /*** * * @param comingRequest diff --git a/src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIdRecord.java b/src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIdRecord.java new file mode 100644 index 0000000..58fa5cb --- /dev/null +++ b/src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIdRecord.java @@ -0,0 +1,79 @@ +package com.wipro.fhir.controller.healthID; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.wipro.fhir.service.healthID.HealthIDService; +import com.wipro.fhir.utils.exception.FHIRException; +import com.wipro.fhir.utils.response.OutputResponse; + +import io.swagger.v3.oas.annotations.Operation; + +@CrossOrigin +@RestController +@RequestMapping(value = "/healthIDRecord", headers = "Authorization", consumes = "application/json", produces = "application/json") +public class CreateHealthIdRecord { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Autowired + private HealthIDService healthIDService; + + /*** + * + * @param request + * @param Authorization + * @return BenRegID of beneficiary after mapping + */ + @CrossOrigin + @Operation(summary = "Map ABHA to beneficiary") + @PostMapping(value = { "/mapHealthIDToBeneficiary" }) + public String mapHealthIDToBeneficiary( + @RequestBody String request, @RequestHeader(value = "Authorization") String Authorization) { + logger.info("NDHM_FHIR Map ABHA to beneficiary API request " + request); + OutputResponse response = new OutputResponse(); + try { + if (request != null) { + String s = healthIDService.mapHealthIDToBeneficiary(request); + response.setResponse(s); + } else + throw new FHIRException("NDHM_FHIR Empty request object"); + } catch (FHIRException e) { + response.setError(5000, e.getMessage()); + logger.error(e.toString()); + } + logger.info("NDHM_FHIR Map ABHA to beneficiary API response " + response.toString()); + return response.toString(); + } + + + @CrossOrigin + @Operation(summary = "Add New health ID record to healthId table") + @PostMapping(value = { "/addHealthIdRecord" }) + public String addRecordToHealthIdTable( + @RequestBody String request, @RequestHeader(value = "Authorization") String Authorization) { + logger.info("NDHM_FHIR API to add the new health record coming from FLW request " + request); + OutputResponse response = new OutputResponse(); + try { + if (request != null) { + String s = healthIDService.addRecordToHealthIdTable(request); + response.setResponse(s); + } else + throw new FHIRException("NDHM_FHIR Empty request object"); + } catch (FHIRException e) { + response.setError(5000, e.getMessage()); + logger.error(e.toString()); + } + logger.info("NDHM_FHIR API to add the new health record coming from FLW response " + response.toString()); + return response.toString(); + } + + +} diff --git a/src/main/java/com/wipro/fhir/data/healthID/HealthIDRequestAadhar.java b/src/main/java/com/wipro/fhir/data/healthID/HealthIDRequestAadhar.java index 4bda2a9..f3da5bd 100644 --- a/src/main/java/com/wipro/fhir/data/healthID/HealthIDRequestAadhar.java +++ b/src/main/java/com/wipro/fhir/data/healthID/HealthIDRequestAadhar.java @@ -21,6 +21,9 @@ */ package com.wipro.fhir.data.healthID; +import lombok.Data; + +@Data public class HealthIDRequestAadhar { String email; @@ -35,77 +38,6 @@ public class HealthIDRequestAadhar { String healthId; String password; String profilePhoto; - public Integer getProviderServiceMapID() { - return providerServiceMapID; - } - public void setProviderServiceMapID(Integer providerServiceMapID) { - this.providerServiceMapID = providerServiceMapID; - } - public String getCreatedBy() { - return createdBy; - } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } - public String getFirstName() { - return firstName; - } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - public String getLastName() { - return lastName; - } - public void setLastName(String lastName) { - this.lastName = lastName; - } - public String getOtp() { - return otp; - } - public void setOtp(String otp) { - this.otp = otp; - } - public String getTxnId() { - return txnId; - } - public void setTxnId(String txnId) { - this.txnId = txnId; - } - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - public String getMiddleName() { - return middleName; - } - public void setMiddleName(String middleName) { - this.middleName = middleName; - } - public String getHealthId() { - return healthId; - } - public void setHealthId(String healthId) { - this.healthId = healthId; - } - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - public String getProfilePhoto() { - return profilePhoto; - } - public void setProfilePhoto(String profilePhoto) { - this.profilePhoto = profilePhoto; - } - + Boolean isNew; + String dob; } diff --git a/src/main/java/com/wipro/fhir/service/healthID/HealthIDService.java b/src/main/java/com/wipro/fhir/service/healthID/HealthIDService.java index 5aa53c8..57619e6 100644 --- a/src/main/java/com/wipro/fhir/service/healthID/HealthIDService.java +++ b/src/main/java/com/wipro/fhir/service/healthID/HealthIDService.java @@ -26,4 +26,5 @@ public interface HealthIDService { String mapHealthIDToBeneficiary(String request) throws FHIRException; public String getBenHealthID(Long benRegID); + public String addRecordToHealthIdTable(String request) throws FHIRException; } diff --git a/src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java b/src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java index 1c8643c..c8891cc 100644 --- a/src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java @@ -21,7 +21,9 @@ */ package com.wipro.fhir.service.healthID; +import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -32,8 +34,14 @@ import org.springframework.stereotype.Service; import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import com.wipro.fhir.data.healthID.BenHealthIDMapping; +import com.wipro.fhir.data.healthID.HealthIDRequestAadhar; +import com.wipro.fhir.data.healthID.HealthIDResponse; import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; +import com.wipro.fhir.repo.healthID.HealthIDRepo; import com.wipro.fhir.utils.exception.FHIRException; import com.wipro.fhir.utils.http.HttpUtils; import com.wipro.fhir.utils.mapper.InputMapper; @@ -46,9 +54,12 @@ public class HealthIDServiceImpl implements HealthIDService { @Autowired private BenHealthIDMappingRepo benHealthIDMappingRepo; + @Autowired + HealthIDRepo healthIDRepo; public String mapHealthIDToBeneficiary(String request) throws FHIRException { BenHealthIDMapping health = InputMapper.gson().fromJson(request, BenHealthIDMapping.class); + health = InputMapper.gson().fromJson(request, BenHealthIDMapping.class); try { if (health.getBeneficiaryRegId() == null && health.getBeneficiaryID() == null) throw new FHIRException("Error in mapping request"); @@ -61,6 +72,40 @@ public String mapHealthIDToBeneficiary(String request) throws FHIRException { health = benHealthIDMappingRepo.save(health); } } + // Adding the code to check if the received healthId is present in t_healthId table and add if missing + Integer healthIdCount = healthIDRepo.getCountOfHealthIdNumber(health.getHealthIdNumber()); + if(healthIdCount < 1) { + JsonObject jsonRequest = JsonParser.parseString(request).getAsJsonObject(); + JsonObject abhaProfileJson = jsonRequest.getAsJsonObject("ABHAProfile"); + HealthIDResponse healthID = InputMapper.gson().fromJson(abhaProfileJson, HealthIDResponse.class); + + healthID.setHealthIdNumber(abhaProfileJson.get("ABHANumber").getAsString()); + JsonArray phrAddressArray = abhaProfileJson.getAsJsonArray("phrAddress"); + StringBuilder abhaAddressBuilder = new StringBuilder(); + + for (int i = 0; i < phrAddressArray.size(); i++) { + abhaAddressBuilder.append(phrAddressArray.get(i).getAsString()); + if (i < phrAddressArray.size() - 1) { + abhaAddressBuilder.append(", "); + } + } + healthID.setHealthId(abhaAddressBuilder.toString()); + healthID.setName( + abhaProfileJson.get("firstName").getAsString() + " " + abhaProfileJson.get("middleName").getAsString() + " " + abhaProfileJson.get("lastName").getAsString()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy"); + Date date = simpleDateFormat.parse(abhaProfileJson.get("dob").getAsString()); + SimpleDateFormat year = new SimpleDateFormat("yyyy"); + SimpleDateFormat month = new SimpleDateFormat("MM"); + SimpleDateFormat day = new SimpleDateFormat("dd"); + healthID.setYearOfBirth(year.format(date)); + healthID.setMonthOfBirth(month.format(date)); + healthID.setDayOfBirth(day.format(date)); + healthID.setCreatedBy(jsonRequest.get("createdBy").getAsString()); + healthID.setProviderServiceMapID(jsonRequest.get("providerServiceMapId").getAsInt()); + healthID.setIsNewAbha(jsonRequest.get("isNew").getAsBoolean()); + healthIDRepo.save(healthID); + } + } catch (Exception e) { throw new FHIRException("Error in saving data"); } @@ -75,4 +120,48 @@ public String getBenHealthID(Long benRegID) { return resMap.toString(); } + + @Override + public String addRecordToHealthIdTable(String request) throws FHIRException { + JsonObject jsonRequest = JsonParser.parseString(request).getAsJsonObject(); + JsonObject abhaProfileJson = jsonRequest.getAsJsonObject("ABHAProfile"); + HealthIDResponse healthID = InputMapper.gson().fromJson(abhaProfileJson, HealthIDResponse.class); + String res = null; + try { + Integer healthIdCount = healthIDRepo.getCountOfHealthIdNumber(healthID.getHealthIdNumber()); + if(healthIdCount < 1) { + healthID.setHealthIdNumber(abhaProfileJson.get("ABHANumber").getAsString()); + JsonArray phrAddressArray = abhaProfileJson.getAsJsonArray("phrAddress"); + StringBuilder abhaAddressBuilder = new StringBuilder(); + + for (int i = 0; i < phrAddressArray.size(); i++) { + abhaAddressBuilder.append(phrAddressArray.get(i).getAsString()); + if (i < phrAddressArray.size() - 1) { + abhaAddressBuilder.append(", "); + } + } + healthID.setHealthId(abhaAddressBuilder.toString()); + healthID.setName( + abhaProfileJson.get("firstName").getAsString() + " " + abhaProfileJson.get("middleName").getAsString() + " " + abhaProfileJson.get("lastName").getAsString()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy"); + Date date = simpleDateFormat.parse(abhaProfileJson.get("dob").getAsString()); + SimpleDateFormat year = new SimpleDateFormat("yyyy"); + SimpleDateFormat month = new SimpleDateFormat("MM"); + SimpleDateFormat day = new SimpleDateFormat("dd"); + healthID.setYearOfBirth(year.format(date)); + healthID.setMonthOfBirth(month.format(date)); + healthID.setDayOfBirth(day.format(date)); + healthID.setCreatedBy(jsonRequest.get("createdBy").getAsString()); + healthID.setProviderServiceMapID(jsonRequest.get("providerServiceMapId").getAsInt()); + healthID.setIsNewAbha(jsonRequest.get("isNew").getAsBoolean()); + healthIDRepo.save(healthID); + res = "Data Saved Successfully"; + } else { + res = "Data already exists"; + } + } catch (Exception e) { + throw new FHIRException("Error in saving data"); + } + return res; + } } \ No newline at end of file From 38dd8467102b07db0d81730de7733607c61dffc8 Mon Sep 17 00:00:00 2001 From: Karyamsetty Helen Grace Date: Thu, 27 Feb 2025 00:08:22 +0530 Subject: [PATCH 13/26] Reapply "jwt implementation changes (#53)" This reverts commit c38d0995378e199caf284b81b003959f96f8c974. --- .github/workflows/build-on-pull-request.yml | 3 +- .github/workflows/package.yml | 4 +- .github/workflows/sast.yml | 4 +- pom.xml | 40 ++++-- src/main/environment/common_ci.properties | 3 +- src/main/environment/common_dev.properties | 1 + .../environment/common_example.properties | 1 + src/main/environment/common_test.properties | 1 + .../com/wipro/fhir/FhirApiApplication.java | 21 +++ .../com/wipro/fhir/config/RedisConfig.java | 40 ++++++ .../java/com/wipro/fhir/data/users/User.java | 28 ++++ .../wipro/fhir/repo/user/UserLoginRepo.java | 16 +++ .../service/common/CommonServiceImpl.java | 88 +++++++++--- .../java/com/wipro/fhir/utils/CookieUtil.java | 31 +++++ .../com/wipro/fhir/utils/FilterConfig.java | 19 +++ .../fhir/utils/JwtAuthenticationUtil.java | 125 ++++++++++++++++++ .../fhir/utils/JwtUserIdValidationFilter.java | 111 ++++++++++++++++ .../java/com/wipro/fhir/utils/JwtUtil.java | 68 ++++++++++ 18 files changed, 567 insertions(+), 37 deletions(-) create mode 100644 src/main/java/com/wipro/fhir/config/RedisConfig.java create mode 100644 src/main/java/com/wipro/fhir/data/users/User.java create mode 100644 src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java create mode 100644 src/main/java/com/wipro/fhir/utils/CookieUtil.java create mode 100644 src/main/java/com/wipro/fhir/utils/FilterConfig.java create mode 100644 src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java create mode 100644 src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java create mode 100644 src/main/java/com/wipro/fhir/utils/JwtUtil.java diff --git a/.github/workflows/build-on-pull-request.yml b/.github/workflows/build-on-pull-request.yml index 744b905..695b179 100644 --- a/.github/workflows/build-on-pull-request.yml +++ b/.github/workflows/build-on-pull-request.yml @@ -17,6 +17,7 @@ jobs: uses: actions/setup-java@v2 with: java-version: 17 - distribution: 'adopt' + distribution: 'zulu' + - name: Build with Maven run: mvn clean install diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 5cc0ca0..769fce7 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -26,7 +26,7 @@ jobs: uses: actions/setup-java@v2 with: java-version: 17 - distribution: 'adopt' + distribution: 'zulu' - name: Build with Maven run: mvn clean install -DENV_VAR=${{ env.ENV_VAR }} @@ -35,7 +35,7 @@ jobs: run: mvn -B package --file pom.xml - name: Upload WAR file as artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: FHIR-API path: target/fhirapi-v1.0.war diff --git a/.github/workflows/sast.yml b/.github/workflows/sast.yml index eb8d6b3..a886904 100644 --- a/.github/workflows/sast.yml +++ b/.github/workflows/sast.yml @@ -41,10 +41,10 @@ jobs: uses: actions/setup-java@v2 with: java-version: 17 - distribution: 'adopt' + distribution: 'zulu' - name: Build with Maven - run: mvn clean install -DENV_VAR=test + run: mvn clean install - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 diff --git a/pom.xml b/pom.xml index a345c2c..22e8b75 100644 --- a/pom.xml +++ b/pom.xml @@ -58,10 +58,10 @@ org.springframework.boot spring-boot-starter - - co.elastic.logging - logback-ecs-encoder - 1.3.2 + + co.elastic.logging + logback-ecs-encoder + 1.3.2 @@ -189,8 +189,7 @@ spring-boot-starter-mail - + ca.uhn.hapi.fhir hapi-fhir-structures-r4 @@ -198,8 +197,7 @@ - + ca.uhn.hapi.fhir org.hl7.fhir.utilities @@ -235,6 +233,27 @@ json-path 2.9.0 + + + io.jsonwebtoken + jjwt-api + 0.12.6 + + + + io.jsonwebtoken + jjwt-impl + 0.12.6 + runtime + + + + io.jsonwebtoken + jjwt-jackson + 0.12.6 + runtime + + @@ -250,7 +269,7 @@ HTML nvd - + org.apache.maven.plugins @@ -329,8 +348,7 @@ ${target-properties} and ${source-properties} - diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index ed70c81..f3137e0 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -110,4 +110,5 @@ logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO #ELK logging file name -logging.file.name=@env.FHIR_API_LOGGING_FILE_NAME@ \ No newline at end of file +logging.file.name=@env.FHIR_API_LOGGING_FILE_NAME@ +jwt.secret=@env.JWT_SECRET_KEY@ \ No newline at end of file diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index 3e012e9..6210f9e 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -107,3 +107,4 @@ logging.level.org.springframework.web=INFO logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO +jwt.secret= diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index 803d225..0679bed 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -109,3 +109,4 @@ logging.level.org.springframework.web=INFO logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO +jwt.secret= diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties index db18ad9..44e1523 100644 --- a/src/main/environment/common_test.properties +++ b/src/main/environment/common_test.properties @@ -108,3 +108,4 @@ logging.level.org.springframework.web=INFO logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO +jwt.secret= diff --git a/src/main/java/com/wipro/fhir/FhirApiApplication.java b/src/main/java/com/wipro/fhir/FhirApiApplication.java index 0395010..d732a3f 100644 --- a/src/main/java/com/wipro/fhir/FhirApiApplication.java +++ b/src/main/java/com/wipro/fhir/FhirApiApplication.java @@ -26,6 +26,12 @@ import org.springframework.context.annotation.Bean; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import com.wipro.fhir.data.users.User; @SpringBootApplication public class FhirApiApplication { @@ -33,4 +39,19 @@ public class FhirApiApplication { public static void main(String[] args) { SpringApplication.run(FhirApiApplication.class, args); } + + @Bean + public RedisTemplate redisTemplate(RedisConnectionFactory factory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(factory); + + // Use StringRedisSerializer for keys (userId) + template.setKeySerializer(new StringRedisSerializer()); + + // Use Jackson2JsonRedisSerializer for values (Users objects) + Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(User.class); + template.setValueSerializer(serializer); + + return template; + } } diff --git a/src/main/java/com/wipro/fhir/config/RedisConfig.java b/src/main/java/com/wipro/fhir/config/RedisConfig.java new file mode 100644 index 0000000..d29e7c3 --- /dev/null +++ b/src/main/java/com/wipro/fhir/config/RedisConfig.java @@ -0,0 +1,40 @@ +package com.wipro.fhir.config; + +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; +import org.springframework.session.data.redis.config.ConfigureRedisAction; + +import com.wipro.fhir.data.users.User; + +@Configuration +@EnableCaching +public class RedisConfig { + + @Bean + public ConfigureRedisAction configureRedisAction() { + return ConfigureRedisAction.NO_OP; + } + + @Bean + public RedisTemplate redisTemplate(RedisConnectionFactory factory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(factory); + + // Use StringRedisSerializer for keys (userId) + template.setKeySerializer(new StringRedisSerializer()); + + // Use Jackson2JsonRedisSerializer for values (Users objects) + Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(User.class); + template.setValueSerializer(serializer); + + return template; + } + +} + + diff --git a/src/main/java/com/wipro/fhir/data/users/User.java b/src/main/java/com/wipro/fhir/data/users/User.java new file mode 100644 index 0000000..c31049e --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/users/User.java @@ -0,0 +1,28 @@ +package com.wipro.fhir.data.users; + +import java.io.Serializable; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import lombok.Data; + +@Entity +@Table(name = "m_user") +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class User implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "UserID") + private Long userID; + @Column(name = "userName") + private String userName; + @Column(name = "Deleted", insertable = false, updatable = true) + private Boolean deleted; +} diff --git a/src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java b/src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java new file mode 100644 index 0000000..1267ab6 --- /dev/null +++ b/src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java @@ -0,0 +1,16 @@ +package com.wipro.fhir.repo.user; + +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import com.wipro.fhir.data.users.User; + +@Repository +public interface UserLoginRepo extends CrudRepository { + + @Query(" SELECT u FROM User u WHERE u.userID = :userID AND u.deleted = false ") + public User getUserByUserID(@Param("userID") Long userID); + +} diff --git a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java index 0c87321..5fcf125 100644 --- a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java @@ -58,11 +58,13 @@ import com.wipro.fhir.data.mongo.care_context.NDHMResponse; import com.wipro.fhir.data.mongo.care_context.Notification; import com.wipro.fhir.data.mongo.care_context.PatientCareContexts; +import com.wipro.fhir.data.mongo.care_context.PatientCareContextsStringOBJ; import com.wipro.fhir.data.mongo.care_context.SMSNotify; import com.wipro.fhir.data.patient.PatientDemographic; import com.wipro.fhir.data.patient_data_handler.PatientDemographicModel_NDHM_Patient_Profile; import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.data.users.User; import com.wipro.fhir.repo.common.PatientEligibleForResourceCreationRepo; import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; import com.wipro.fhir.repo.mongo.amrit_resource.AMRIT_ResourceMongoRepo; @@ -101,6 +103,12 @@ public class CommonServiceImpl implements CommonService { private static String authKey; private UUID uuid; + + // public static String NDHM_AUTH_TOKEN; + // public static Long NDHM_TOKEN_EXP; + // public static String NDHM_OTP_TOKEN; + + @Value("${clientID}") private String clientID; @@ -161,7 +169,8 @@ public String processResourceOperation() throws FHIRException { String response = null; // list of patient eligible for resource creation List pList = getPatientListForResourceEligible(); - logger.info("No of records available to create FHIR in last 2 dagetPatientListForResourceEligibleys : " + pList.size()); + logger.info("No of records available to create FHIR in last 2 dagetPatientListForResourceEligibleys : " + + pList.size()); ResourceRequestHandler resourceRequestHandler; for (PatientEligibleForResourceCreation p : pList) { @@ -290,6 +299,38 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe if (pDemo != null && pVisit != null) { + +// JsonObject jsnOBJ = new JsonObject(); +// JsonParser jsnParser = new JsonParser(); +// JsonElement jsnElmnt = jsnParser.parse(requestObj); +// jsnOBJ = jsnElmnt.getAsJsonObject(); + + PatientCareContextsStringOBJ patientCareContextsStringOBJ = new PatientCareContextsStringOBJ(); + + // wrong variable name in request obj for benregid, need to correct in main + // request obj first +// Long benID = null; +// Long benRegID = null; +// Long visitCode = null; +// +// if (jsnOBJ.has("beneficiaryID") && jsnOBJ.get("beneficiaryID") != null) +// benRegID = jsnOBJ.get("beneficiaryID").getAsLong(); +// if (jsnOBJ.has("visitCode") && jsnOBJ.get("visitCode") != null) +// visitCode = jsnOBJ.get("visitCode").getAsLong(); +// String healthID = jsnOBJ.get("healthID").getAsString(); +// String healthIDNumber = jsnOBJ.get("healthIdNumber").getAsString(); +// String visitCategory = jsnOBJ.get("visitCategory").getAsString(); +// String phoneNo; +// String gender; +// String yearOfBirth; +// String name; +// String email; + + // get benid +// if (benRegID != null) +// benID = benHealthIDMappingRepo.getBenID(benRegID); + + // fetch abdm facility id logger.info("********t_benvisistData fetch request pvisit data :", pVisit); @@ -299,6 +340,7 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe ArrayList ccList = new ArrayList<>(); CareContexts cc = new CareContexts(); + logger.info("********t_benvisistData fetch response : {}", res); cc.setReferenceNumber(pVisit.getVisitCode() != null ? pVisit.getVisitCode().toString() : null); @@ -310,16 +352,22 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe cc.setCareContextLinkedDate(resData[1] != null ? resData[1].toString() : null); } + logger.info("********data to be saved in mongo :", cc); PatientCareContexts pcc; + PatientCareContexts resultSet = null; + + + logger.info("********data to be saved in mongo :", cc); + PatientCareContexts pcc1; if (pDemo.getBeneficiaryID() != null) { - pcc = patientCareContextsMongoRepo.findByIdentifier(pDemo.getBeneficiaryID().toString()); + pcc1 = patientCareContextsMongoRepo.findByIdentifier(pDemo.getBeneficiaryID().toString()); - if (pcc != null && pcc.getIdentifier() != null) { + if (pcc1 != null && pcc1.getIdentifier() != null) { // Get the existing careContextsList - if (pcc.getCareContextsList() != null && pcc.getCareContextsList().size() > 0) { - ccList = pcc.getCareContextsList(); + if (pcc1.getCareContextsList() != null && pcc1.getCareContextsList().size() > 0) { + ccList = pcc1.getCareContextsList(); // Check if the visitCode is already in the careContextsList for (CareContexts existingContext : ccList) { @@ -330,8 +378,8 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe } } ccList.add(cc); - pcc.setCareContextsList(ccList); - patientCareContextsMongoRepo.save(pcc); + pcc1.setCareContextsList(ccList); + patientCareContextsMongoRepo.save(pcc1); } // } // if (pcc != null && pcc.getIdentifier() != null) { @@ -341,20 +389,20 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe // resultSet = patientCareContextsMongoRepo.save(pcc); // } else { - pcc = new PatientCareContexts(); - pcc.setCaseReferenceNumber(pDemo.getBeneficiaryID().toString()); - pcc.setIdentifier(pDemo.getBeneficiaryID().toString()); + pcc1 = new PatientCareContexts(); + pcc1.setCaseReferenceNumber(pDemo.getBeneficiaryID().toString()); + pcc1.setIdentifier(pDemo.getBeneficiaryID().toString()); if (pDemo.getGenderID() != null) { switch (pDemo.getGenderID()) { case 1: - pcc.setGender("M"); + pcc1.setGender("M"); break; case 2: - pcc.setGender("F"); + pcc1.setGender("F"); break; case 3: - pcc.setGender("O"); + pcc1.setGender("O"); break; default: @@ -362,19 +410,19 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe } } if (pDemo.getName() != null) - pcc.setName(pDemo.getName()); + pcc1.setName(pDemo.getName()); if (pDemo.getDOB() != null) - pcc.setYearOfBirth(pDemo.getDOB().toString().split("-")[0]); + pcc1.setYearOfBirth(pDemo.getDOB().toString().split("-")[0]); if (pDemo.getPreferredPhoneNo() != null) - pcc.setPhoneNumber(pDemo.getPreferredPhoneNo()); + pcc1.setPhoneNumber(pDemo.getPreferredPhoneNo()); if (pDemo.getHealthID() != null) - pcc.setHealthId(pDemo.getHealthID()); + pcc1.setHealthId(pDemo.getHealthID()); if (pDemo.getHealthIdNo() != null) - pcc.setHealthNumber(pDemo.getHealthIdNo()); + pcc1.setHealthNumber(pDemo.getHealthIdNo()); ccList.add(cc); - pcc.setCareContextsList(ccList); + pcc1.setCareContextsList(ccList); // save carecontext back to mongo - patientCareContextsMongoRepo.save(pcc); + patientCareContextsMongoRepo.save(pcc1); } } diff --git a/src/main/java/com/wipro/fhir/utils/CookieUtil.java b/src/main/java/com/wipro/fhir/utils/CookieUtil.java new file mode 100644 index 0000000..3ccec9d --- /dev/null +++ b/src/main/java/com/wipro/fhir/utils/CookieUtil.java @@ -0,0 +1,31 @@ +package com.wipro.fhir.utils; + +import java.util.Arrays; +import java.util.Optional; + +import org.springframework.stereotype.Service; + +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@Service +public class CookieUtil { + + public Optional getCookieValue(HttpServletRequest request, String cookieName) { + Cookie[] cookies = request.getCookies(); + if (cookies != null) { + for (Cookie cookie : cookies) { + if (cookieName.equals(cookie.getName())) { + return Optional.of(cookie.getValue()); + } + } + } + return Optional.empty(); + } + + public String getJwtTokenFromCookie(HttpServletRequest request) { + return Arrays.stream(request.getCookies()).filter(cookie -> "Jwttoken".equals(cookie.getName())) + .map(Cookie::getValue).findFirst().orElse(null); + } +} diff --git a/src/main/java/com/wipro/fhir/utils/FilterConfig.java b/src/main/java/com/wipro/fhir/utils/FilterConfig.java new file mode 100644 index 0000000..5a7ef36 --- /dev/null +++ b/src/main/java/com/wipro/fhir/utils/FilterConfig.java @@ -0,0 +1,19 @@ +package com.wipro.fhir.utils; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class FilterConfig { + + @Bean + public FilterRegistrationBean jwtUserIdValidationFilter( + JwtAuthenticationUtil jwtAuthenticationUtil) { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(new JwtUserIdValidationFilter(jwtAuthenticationUtil)); + registrationBean.addUrlPatterns("/*"); // Apply filter to all API endpoints + return registrationBean; + } + +} diff --git a/src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java b/src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java new file mode 100644 index 0000000..61cdc90 --- /dev/null +++ b/src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java @@ -0,0 +1,125 @@ +package com.wipro.fhir.utils; + +import java.util.Optional; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; + +import com.wipro.fhir.data.users.User; +import com.wipro.fhir.repo.user.UserLoginRepo; + +import io.jsonwebtoken.Claims; +import jakarta.servlet.http.HttpServletRequest; + +@Component +public class JwtAuthenticationUtil { + + @Autowired + private CookieUtil cookieUtil; + @Autowired + private JwtUtil jwtUtil; + @Autowired + private RedisTemplate redisTemplate; + @Autowired + private UserLoginRepo userLoginRepo; + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + public JwtAuthenticationUtil(CookieUtil cookieUtil, JwtUtil jwtUtil) { + this.cookieUtil = cookieUtil; + this.jwtUtil = jwtUtil; + } + + public ResponseEntity validateJwtToken(HttpServletRequest request) { + Optional jwtTokenOpt = cookieUtil.getCookieValue(request, "Jwttoken"); + + if (jwtTokenOpt.isEmpty()) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .body("Error 401: Unauthorized - JWT Token is not set!"); + } + + String jwtToken = jwtTokenOpt.get(); + + // Validate the token + Claims claims = jwtUtil.validateToken(jwtToken); + if (claims == null) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Error 401: Unauthorized - Invalid JWT Token!"); + } + + // Extract username from token + String usernameFromToken = claims.getSubject(); + if (usernameFromToken == null || usernameFromToken.isEmpty()) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .body("Error 401: Unauthorized - Username is missing!"); + } + + // Return the username if valid + return ResponseEntity.ok(usernameFromToken); + } + + public boolean validateUserIdAndJwtToken(String jwtToken) throws Exception { + try { + // Validate JWT token and extract claims + Claims claims = jwtUtil.validateToken(jwtToken); + + if (claims == null) { + throw new Exception("Invalid JWT token."); + } + + String userId = claims.get("userId", String.class); + + // Check if user data is present in Redis + User user = getUserFromCache(userId); + if (user == null) { + // If not in Redis, fetch from DB and cache the result + user = fetchUserFromDB(userId); + } + if (user == null) { + throw new Exception("Invalid User ID."); + } + + return true; // Valid userId and JWT token + } catch (Exception e) { + logger.error("Validation failed: " + e.getMessage(), e); + throw new Exception("Validation error: " + e.getMessage(), e); + } + } + + private User getUserFromCache(String userId) { + String redisKey = "user_" + userId; // The Redis key format + User user = (User) redisTemplate.opsForValue().get(redisKey); + + if (user == null) { + logger.warn("User not found in Redis. Will try to fetch from DB."); + } else { + logger.info("User fetched successfully from Redis."); + } + + return user; // Returns null if not found + } + + private User fetchUserFromDB(String userId) { + // This method will only be called if the user is not found in Redis. + String redisKey = "user_" + userId; // Redis key format + + // Fetch user from DB + User user = userLoginRepo.getUserByUserID(Long.parseLong(userId)); + + if (user != null) { + // Cache the user in Redis for future requests (cache for 30 minutes) + redisTemplate.opsForValue().set(redisKey, user, 30, TimeUnit.MINUTES); + + // Log that the user has been stored in Redis + logger.info("User stored in Redis with key: " + redisKey); + } else { + logger.warn("User not found for userId: " + userId); + } + + return user; + } +} diff --git a/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java b/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java new file mode 100644 index 0000000..09ae81f --- /dev/null +++ b/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java @@ -0,0 +1,111 @@ +package com.wipro.fhir.utils; + +import java.io.IOException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@Component +public class JwtUserIdValidationFilter implements Filter { + + private final JwtAuthenticationUtil jwtAuthenticationUtil; + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + public JwtUserIdValidationFilter(JwtAuthenticationUtil jwtAuthenticationUtil) { + this.jwtAuthenticationUtil = jwtAuthenticationUtil; + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + HttpServletRequest request = (HttpServletRequest) servletRequest; + HttpServletResponse response = (HttpServletResponse) servletResponse; + + String path = request.getRequestURI(); + String contextPath = request.getContextPath(); + logger.info("JwtUserIdValidationFilter invoked for path: " + path); + + // Log cookies for debugging + Cookie[] cookies = request.getCookies(); + if (cookies != null) { + for (Cookie cookie : cookies) { + if ("userId".equals(cookie.getName())) { + logger.warn("userId found in cookies! Clearing it..."); + clearUserIdCookie(response); // Explicitly remove userId cookie + } + } + } else { + logger.info("No cookies found in the request"); + } + + // Log headers for debugging + String jwtTokenFromHeader = request.getHeader("Jwttoken"); + logger.info("JWT token from header: "); + + // Skip login and public endpoints + if (path.equals(contextPath + "/user/userAuthenticate") + || path.equalsIgnoreCase(contextPath + "/user/logOutUserFromConcurrentSession") + || path.startsWith(contextPath + "/public")) { + logger.info("Skipping filter for path: " + path); + filterChain.doFilter(servletRequest, servletResponse); + return; + } + + try { + // Retrieve JWT token from cookies + String jwtTokenFromCookie = getJwtTokenFromCookies(request); + logger.info("JWT token from cookie: "); + + // Determine which token (cookie or header) to validate + String jwtToken = jwtTokenFromCookie != null ? jwtTokenFromCookie : jwtTokenFromHeader; + if (jwtToken == null) { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "JWT token not found in cookies or headers"); + return; + } + + // Validate JWT token and userId + boolean isValid = jwtAuthenticationUtil.validateUserIdAndJwtToken(jwtToken); + + if (isValid) { + // If token is valid, allow the request to proceed + filterChain.doFilter(servletRequest, servletResponse); + } else { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid JWT token"); + } + } catch (Exception e) { + logger.error("Authorization error: ", e); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization error: " + e.getMessage()); + } + } + + private String getJwtTokenFromCookies(HttpServletRequest request) { + Cookie[] cookies = request.getCookies(); + if (cookies != null) { + for (Cookie cookie : cookies) { + if (cookie.getName().equals("Jwttoken")) { + return cookie.getValue(); + } + } + } + return null; + } + + private void clearUserIdCookie(HttpServletResponse response) { + Cookie cookie = new Cookie("userId", null); + cookie.setPath("/"); + cookie.setHttpOnly(true); + cookie.setSecure(true); + cookie.setMaxAge(0); // Invalidate the cookie + response.addCookie(cookie); + } +} diff --git a/src/main/java/com/wipro/fhir/utils/JwtUtil.java b/src/main/java/com/wipro/fhir/utils/JwtUtil.java new file mode 100644 index 0000000..6f22eb7 --- /dev/null +++ b/src/main/java/com/wipro/fhir/utils/JwtUtil.java @@ -0,0 +1,68 @@ +package com.wipro.fhir.utils; + +import java.security.Key; +import java.util.Date; +import java.util.function.Function; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.security.Keys; + +@Component +public class JwtUtil { + + @Value("${jwt.secret}") + private String SECRET_KEY; + + private static final long EXPIRATION_TIME = 24L * 60 * 60 * 1000; // 1 day in milliseconds + + // Generate a key using the secret + private Key getSigningKey() { + if (SECRET_KEY == null || SECRET_KEY.isEmpty()) { + throw new IllegalStateException("JWT secret key is not set in application.properties"); + } + return Keys.hmacShaKeyFor(SECRET_KEY.getBytes()); + } + + // Generate JWT Token + public String generateToken(String username, String userId) { + Date now = new Date(); + Date expiryDate = new Date(now.getTime() + EXPIRATION_TIME); + + // Include the userId in the JWT claims + return Jwts.builder().setSubject(username).claim("userId", userId) // Add userId as a claim + .setIssuedAt(now).setExpiration(expiryDate).signWith(getSigningKey(), SignatureAlgorithm.HS256) + .compact(); + } + + // Validate and parse JWT Token + public Claims validateToken(String token) { + try { + // Use the JwtParserBuilder correctly in version 0.12.6 + return Jwts.parser() // Correct method in 0.12.6 to get JwtParserBuilder + .setSigningKey(getSigningKey()) // Set the signing key + .build() // Build the JwtParser + .parseClaimsJws(token) // Parse and validate the token + .getBody(); + } catch (Exception e) { + return null; // Handle token parsing/validation errors + } + } + + public String extractUsername(String token) { + return extractClaim(token, Claims::getSubject); + } + + public T extractClaim(String token, Function claimsResolver) { + final Claims claims = extractAllClaims(token); + return claimsResolver.apply(claims); + } + + private Claims extractAllClaims(String token) { + return Jwts.parser().setSigningKey(getSigningKey()).build().parseClaimsJws(token).getBody(); + } +} From 43d6b48925b19fe4fe3be903b04305995a2ed4d5 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Thu, 27 Feb 2025 14:15:55 +0530 Subject: [PATCH 14/26] changed variable type default value as false --- .../com/wipro/fhir/data/healthID/HealthIDRequestAadhar.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/wipro/fhir/data/healthID/HealthIDRequestAadhar.java b/src/main/java/com/wipro/fhir/data/healthID/HealthIDRequestAadhar.java index f3da5bd..40bd36d 100644 --- a/src/main/java/com/wipro/fhir/data/healthID/HealthIDRequestAadhar.java +++ b/src/main/java/com/wipro/fhir/data/healthID/HealthIDRequestAadhar.java @@ -38,6 +38,6 @@ public class HealthIDRequestAadhar { String healthId; String password; String profilePhoto; - Boolean isNew; + boolean isNew; String dob; } From 86a06f53691a04ba482c10ed5a53bead889f6ff8 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Thu, 27 Feb 2025 20:07:32 +0530 Subject: [PATCH 15/26] addition of isNewAbha in getHealthIdDetails API --- .../data/healthID/BenHealthIDMapping.java | 84 ++----------------- .../repo/healthID/BenHealthIDMappingRepo.java | 3 + .../service/healthID/HealthIDServiceImpl.java | 20 ++++- 3 files changed, 24 insertions(+), 83 deletions(-) diff --git a/src/main/java/com/wipro/fhir/data/healthID/BenHealthIDMapping.java b/src/main/java/com/wipro/fhir/data/healthID/BenHealthIDMapping.java index 65d6a05..8a0fdef 100644 --- a/src/main/java/com/wipro/fhir/data/healthID/BenHealthIDMapping.java +++ b/src/main/java/com/wipro/fhir/data/healthID/BenHealthIDMapping.java @@ -30,10 +30,12 @@ import jakarta.persistence.Id; import jakarta.persistence.Table; import jakarta.persistence.Transient; +import lombok.Data; import com.google.gson.annotations.Expose; @Entity @Table(name = "m_benhealthidmapping") +@Data public class BenHealthIDMapping { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -57,13 +59,6 @@ public class BenHealthIDMapping { @Expose @Column(name = "AuthenticationMode") String authenticationMode; - - public String getAuthenticationMode() { - return authenticationMode; - } - public void setAuthenticationMode(String authenticationMode) { - this.authenticationMode = authenticationMode; - } @Column(name = "Deleted", insertable = false, updatable = true) private Boolean deleted = false; @Expose @@ -79,77 +74,8 @@ public void setAuthenticationMode(String authenticationMode) { private String modifiedBy; @Column(name = "LastModDate", insertable = false, updatable = false) private Timestamp lastModDate; - public Integer getBenHealthID() { - return benHealthID; - } - public void setBenHealthID(Integer benHealthID) { - this.benHealthID = benHealthID; - } - public String getHealthIdNumber() { - return healthIdNumber; - } - public void setHealthIdNumber(String healthIdNumber) { - this.healthIdNumber = healthIdNumber; - } - public Integer getProviderServiceMapID() { - return providerServiceMapId; - } - public void setProviderServiceMapID(Integer providerServiceMapID) { - this.providerServiceMapId = providerServiceMapID; - } - public Long getBeneficiaryRegId() { - return beneficiaryRegID; - } - public void setBeneficiaryRegId(Long beneficiaryRegId) { - this.beneficiaryRegID = beneficiaryRegId; - } - public String getHealthId() { - return healthId; - } - public void setHealthId(String healthId) { - this.healthId = healthId; - } - public Boolean getDeleted() { - return deleted; - } - public void setDeleted(Boolean deleted) { - this.deleted = deleted; - } - public String getProcessed() { - return processed; - } - public void setProcessed(String processed) { - this.processed = processed; - } - public String getCreatedBy() { - return createdBy; - } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - public Timestamp getCreatedDate() { - return createdDate; - } - public void setCreatedDate(Timestamp createdDate) { - this.createdDate = createdDate; - } - public String getModifiedBy() { - return modifiedBy; - } - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - public Timestamp getLastModDate() { - return lastModDate; - } - public void setLastModDate(Timestamp lastModDate) { - this.lastModDate = lastModDate; - } - public Long getBeneficiaryID() { - return beneficiaryID; - } - public void setBeneficiaryID(Long beneficiaryID) { - this.beneficiaryID = beneficiaryID; - } + @Transient + private boolean isNewAbha; + } diff --git a/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java b/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java index f9fd8d4..ef3e226 100644 --- a/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java +++ b/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java @@ -75,5 +75,8 @@ public interface BenHealthIDMappingRepo extends CrudRepository resMap = new HashMap<>(); ArrayList healthDetailsList = benHealthIDMappingRepo.getHealthDetails(benRegID); - resMap.put("BenHealthDetails", new Gson().toJson(healthDetailsList)); + ArrayList healthDetailsWithAbhaList = new ArrayList<>(); + + if(healthDetailsList.size() > 0) { + for(BenHealthIDMapping healthDetails: healthDetailsList) { + String healthIdNumber = healthDetails.getHealthIdNumber(); + boolean isNewAbha = benHealthIDMappingRepo.getIsNewAbha(healthIdNumber); + healthDetails.setNewAbha(isNewAbha); + + healthDetailsWithAbhaList.add(healthDetails); + } + } + resMap.put("BenHealthDetails", new Gson().toJson(healthDetailsWithAbhaList)); return resMap.toString(); } From 9f0372cb5394b7c5bd394f8f2812626dc2385d98 Mon Sep 17 00:00:00 2001 From: Karyamsetty Helen Grace Date: Thu, 27 Feb 2025 20:13:31 +0530 Subject: [PATCH 16/26] Revert "jwt implementation changes (#53)" This reverts commit 5e16b7d4ea27f66e91553d8bbb159648ff10a82b. --- .github/workflows/build-on-pull-request.yml | 3 +- .github/workflows/package.yml | 4 +- .github/workflows/sast.yml | 4 +- pom.xml | 40 ++---- src/main/environment/common_ci.properties | 3 +- src/main/environment/common_dev.properties | 1 - .../environment/common_example.properties | 1 - src/main/environment/common_test.properties | 1 - .../com/wipro/fhir/FhirApiApplication.java | 21 --- .../com/wipro/fhir/config/RedisConfig.java | 40 ------ .../java/com/wipro/fhir/data/users/User.java | 28 ---- .../wipro/fhir/repo/user/UserLoginRepo.java | 16 --- .../service/common/CommonServiceImpl.java | 88 +++--------- .../java/com/wipro/fhir/utils/CookieUtil.java | 31 ----- .../com/wipro/fhir/utils/FilterConfig.java | 19 --- .../fhir/utils/JwtAuthenticationUtil.java | 125 ------------------ .../fhir/utils/JwtUserIdValidationFilter.java | 111 ---------------- .../java/com/wipro/fhir/utils/JwtUtil.java | 68 ---------- 18 files changed, 37 insertions(+), 567 deletions(-) delete mode 100644 src/main/java/com/wipro/fhir/config/RedisConfig.java delete mode 100644 src/main/java/com/wipro/fhir/data/users/User.java delete mode 100644 src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java delete mode 100644 src/main/java/com/wipro/fhir/utils/CookieUtil.java delete mode 100644 src/main/java/com/wipro/fhir/utils/FilterConfig.java delete mode 100644 src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java delete mode 100644 src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java delete mode 100644 src/main/java/com/wipro/fhir/utils/JwtUtil.java diff --git a/.github/workflows/build-on-pull-request.yml b/.github/workflows/build-on-pull-request.yml index 695b179..744b905 100644 --- a/.github/workflows/build-on-pull-request.yml +++ b/.github/workflows/build-on-pull-request.yml @@ -17,7 +17,6 @@ jobs: uses: actions/setup-java@v2 with: java-version: 17 - distribution: 'zulu' - + distribution: 'adopt' - name: Build with Maven run: mvn clean install diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 769fce7..5cc0ca0 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -26,7 +26,7 @@ jobs: uses: actions/setup-java@v2 with: java-version: 17 - distribution: 'zulu' + distribution: 'adopt' - name: Build with Maven run: mvn clean install -DENV_VAR=${{ env.ENV_VAR }} @@ -35,7 +35,7 @@ jobs: run: mvn -B package --file pom.xml - name: Upload WAR file as artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v3 with: name: FHIR-API path: target/fhirapi-v1.0.war diff --git a/.github/workflows/sast.yml b/.github/workflows/sast.yml index a886904..eb8d6b3 100644 --- a/.github/workflows/sast.yml +++ b/.github/workflows/sast.yml @@ -41,10 +41,10 @@ jobs: uses: actions/setup-java@v2 with: java-version: 17 - distribution: 'zulu' + distribution: 'adopt' - name: Build with Maven - run: mvn clean install + run: mvn clean install -DENV_VAR=test - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 diff --git a/pom.xml b/pom.xml index 22e8b75..a345c2c 100644 --- a/pom.xml +++ b/pom.xml @@ -58,10 +58,10 @@ org.springframework.boot spring-boot-starter - - co.elastic.logging - logback-ecs-encoder - 1.3.2 + + co.elastic.logging + logback-ecs-encoder + 1.3.2 @@ -189,7 +189,8 @@ spring-boot-starter-mail - + ca.uhn.hapi.fhir hapi-fhir-structures-r4 @@ -197,7 +198,8 @@ - + ca.uhn.hapi.fhir org.hl7.fhir.utilities @@ -233,27 +235,6 @@ json-path 2.9.0 - - - io.jsonwebtoken - jjwt-api - 0.12.6 - - - - io.jsonwebtoken - jjwt-impl - 0.12.6 - runtime - - - - io.jsonwebtoken - jjwt-jackson - 0.12.6 - runtime - - @@ -269,7 +250,7 @@ HTML nvd - + org.apache.maven.plugins @@ -348,7 +329,8 @@ ${target-properties} and ${source-properties} - diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index f3137e0..ed70c81 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -110,5 +110,4 @@ logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO #ELK logging file name -logging.file.name=@env.FHIR_API_LOGGING_FILE_NAME@ -jwt.secret=@env.JWT_SECRET_KEY@ \ No newline at end of file +logging.file.name=@env.FHIR_API_LOGGING_FILE_NAME@ \ No newline at end of file diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index 6210f9e..3e012e9 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -107,4 +107,3 @@ logging.level.org.springframework.web=INFO logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO -jwt.secret= diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index 0679bed..803d225 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -109,4 +109,3 @@ logging.level.org.springframework.web=INFO logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO -jwt.secret= diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties index 44e1523..db18ad9 100644 --- a/src/main/environment/common_test.properties +++ b/src/main/environment/common_test.properties @@ -108,4 +108,3 @@ logging.level.org.springframework.web=INFO logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO -jwt.secret= diff --git a/src/main/java/com/wipro/fhir/FhirApiApplication.java b/src/main/java/com/wipro/fhir/FhirApiApplication.java index d732a3f..0395010 100644 --- a/src/main/java/com/wipro/fhir/FhirApiApplication.java +++ b/src/main/java/com/wipro/fhir/FhirApiApplication.java @@ -26,12 +26,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; -import org.springframework.data.redis.serializer.StringRedisSerializer; - -import com.wipro.fhir.data.users.User; @SpringBootApplication public class FhirApiApplication { @@ -39,19 +33,4 @@ public class FhirApiApplication { public static void main(String[] args) { SpringApplication.run(FhirApiApplication.class, args); } - - @Bean - public RedisTemplate redisTemplate(RedisConnectionFactory factory) { - RedisTemplate template = new RedisTemplate<>(); - template.setConnectionFactory(factory); - - // Use StringRedisSerializer for keys (userId) - template.setKeySerializer(new StringRedisSerializer()); - - // Use Jackson2JsonRedisSerializer for values (Users objects) - Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(User.class); - template.setValueSerializer(serializer); - - return template; - } } diff --git a/src/main/java/com/wipro/fhir/config/RedisConfig.java b/src/main/java/com/wipro/fhir/config/RedisConfig.java deleted file mode 100644 index d29e7c3..0000000 --- a/src/main/java/com/wipro/fhir/config/RedisConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.wipro.fhir.config; - -import org.springframework.cache.annotation.EnableCaching; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; -import org.springframework.data.redis.serializer.StringRedisSerializer; -import org.springframework.session.data.redis.config.ConfigureRedisAction; - -import com.wipro.fhir.data.users.User; - -@Configuration -@EnableCaching -public class RedisConfig { - - @Bean - public ConfigureRedisAction configureRedisAction() { - return ConfigureRedisAction.NO_OP; - } - - @Bean - public RedisTemplate redisTemplate(RedisConnectionFactory factory) { - RedisTemplate template = new RedisTemplate<>(); - template.setConnectionFactory(factory); - - // Use StringRedisSerializer for keys (userId) - template.setKeySerializer(new StringRedisSerializer()); - - // Use Jackson2JsonRedisSerializer for values (Users objects) - Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(User.class); - template.setValueSerializer(serializer); - - return template; - } - -} - - diff --git a/src/main/java/com/wipro/fhir/data/users/User.java b/src/main/java/com/wipro/fhir/data/users/User.java deleted file mode 100644 index c31049e..0000000 --- a/src/main/java/com/wipro/fhir/data/users/User.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.wipro.fhir.data.users; - -import java.io.Serializable; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.Table; -import lombok.Data; - -@Entity -@Table(name = "m_user") -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class User implements Serializable { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "UserID") - private Long userID; - @Column(name = "userName") - private String userName; - @Column(name = "Deleted", insertable = false, updatable = true) - private Boolean deleted; -} diff --git a/src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java b/src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java deleted file mode 100644 index 1267ab6..0000000 --- a/src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.wipro.fhir.repo.user; - -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.CrudRepository; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import com.wipro.fhir.data.users.User; - -@Repository -public interface UserLoginRepo extends CrudRepository { - - @Query(" SELECT u FROM User u WHERE u.userID = :userID AND u.deleted = false ") - public User getUserByUserID(@Param("userID") Long userID); - -} diff --git a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java index 5fcf125..0c87321 100644 --- a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java @@ -58,13 +58,11 @@ import com.wipro.fhir.data.mongo.care_context.NDHMResponse; import com.wipro.fhir.data.mongo.care_context.Notification; import com.wipro.fhir.data.mongo.care_context.PatientCareContexts; -import com.wipro.fhir.data.mongo.care_context.PatientCareContextsStringOBJ; import com.wipro.fhir.data.mongo.care_context.SMSNotify; import com.wipro.fhir.data.patient.PatientDemographic; import com.wipro.fhir.data.patient_data_handler.PatientDemographicModel_NDHM_Patient_Profile; import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; import com.wipro.fhir.data.request_handler.ResourceRequestHandler; -import com.wipro.fhir.data.users.User; import com.wipro.fhir.repo.common.PatientEligibleForResourceCreationRepo; import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; import com.wipro.fhir.repo.mongo.amrit_resource.AMRIT_ResourceMongoRepo; @@ -103,12 +101,6 @@ public class CommonServiceImpl implements CommonService { private static String authKey; private UUID uuid; - - // public static String NDHM_AUTH_TOKEN; - // public static Long NDHM_TOKEN_EXP; - // public static String NDHM_OTP_TOKEN; - - @Value("${clientID}") private String clientID; @@ -169,8 +161,7 @@ public String processResourceOperation() throws FHIRException { String response = null; // list of patient eligible for resource creation List pList = getPatientListForResourceEligible(); - logger.info("No of records available to create FHIR in last 2 dagetPatientListForResourceEligibleys : " - + pList.size()); + logger.info("No of records available to create FHIR in last 2 dagetPatientListForResourceEligibleys : " + pList.size()); ResourceRequestHandler resourceRequestHandler; for (PatientEligibleForResourceCreation p : pList) { @@ -299,38 +290,6 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe if (pDemo != null && pVisit != null) { - -// JsonObject jsnOBJ = new JsonObject(); -// JsonParser jsnParser = new JsonParser(); -// JsonElement jsnElmnt = jsnParser.parse(requestObj); -// jsnOBJ = jsnElmnt.getAsJsonObject(); - - PatientCareContextsStringOBJ patientCareContextsStringOBJ = new PatientCareContextsStringOBJ(); - - // wrong variable name in request obj for benregid, need to correct in main - // request obj first -// Long benID = null; -// Long benRegID = null; -// Long visitCode = null; -// -// if (jsnOBJ.has("beneficiaryID") && jsnOBJ.get("beneficiaryID") != null) -// benRegID = jsnOBJ.get("beneficiaryID").getAsLong(); -// if (jsnOBJ.has("visitCode") && jsnOBJ.get("visitCode") != null) -// visitCode = jsnOBJ.get("visitCode").getAsLong(); -// String healthID = jsnOBJ.get("healthID").getAsString(); -// String healthIDNumber = jsnOBJ.get("healthIdNumber").getAsString(); -// String visitCategory = jsnOBJ.get("visitCategory").getAsString(); -// String phoneNo; -// String gender; -// String yearOfBirth; -// String name; -// String email; - - // get benid -// if (benRegID != null) -// benID = benHealthIDMappingRepo.getBenID(benRegID); - - // fetch abdm facility id logger.info("********t_benvisistData fetch request pvisit data :", pVisit); @@ -340,7 +299,6 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe ArrayList ccList = new ArrayList<>(); CareContexts cc = new CareContexts(); - logger.info("********t_benvisistData fetch response : {}", res); cc.setReferenceNumber(pVisit.getVisitCode() != null ? pVisit.getVisitCode().toString() : null); @@ -352,22 +310,16 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe cc.setCareContextLinkedDate(resData[1] != null ? resData[1].toString() : null); } - logger.info("********data to be saved in mongo :", cc); PatientCareContexts pcc; - PatientCareContexts resultSet = null; - - - logger.info("********data to be saved in mongo :", cc); - PatientCareContexts pcc1; if (pDemo.getBeneficiaryID() != null) { - pcc1 = patientCareContextsMongoRepo.findByIdentifier(pDemo.getBeneficiaryID().toString()); + pcc = patientCareContextsMongoRepo.findByIdentifier(pDemo.getBeneficiaryID().toString()); - if (pcc1 != null && pcc1.getIdentifier() != null) { + if (pcc != null && pcc.getIdentifier() != null) { // Get the existing careContextsList - if (pcc1.getCareContextsList() != null && pcc1.getCareContextsList().size() > 0) { - ccList = pcc1.getCareContextsList(); + if (pcc.getCareContextsList() != null && pcc.getCareContextsList().size() > 0) { + ccList = pcc.getCareContextsList(); // Check if the visitCode is already in the careContextsList for (CareContexts existingContext : ccList) { @@ -378,8 +330,8 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe } } ccList.add(cc); - pcc1.setCareContextsList(ccList); - patientCareContextsMongoRepo.save(pcc1); + pcc.setCareContextsList(ccList); + patientCareContextsMongoRepo.save(pcc); } // } // if (pcc != null && pcc.getIdentifier() != null) { @@ -389,20 +341,20 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe // resultSet = patientCareContextsMongoRepo.save(pcc); // } else { - pcc1 = new PatientCareContexts(); - pcc1.setCaseReferenceNumber(pDemo.getBeneficiaryID().toString()); - pcc1.setIdentifier(pDemo.getBeneficiaryID().toString()); + pcc = new PatientCareContexts(); + pcc.setCaseReferenceNumber(pDemo.getBeneficiaryID().toString()); + pcc.setIdentifier(pDemo.getBeneficiaryID().toString()); if (pDemo.getGenderID() != null) { switch (pDemo.getGenderID()) { case 1: - pcc1.setGender("M"); + pcc.setGender("M"); break; case 2: - pcc1.setGender("F"); + pcc.setGender("F"); break; case 3: - pcc1.setGender("O"); + pcc.setGender("O"); break; default: @@ -410,19 +362,19 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe } } if (pDemo.getName() != null) - pcc1.setName(pDemo.getName()); + pcc.setName(pDemo.getName()); if (pDemo.getDOB() != null) - pcc1.setYearOfBirth(pDemo.getDOB().toString().split("-")[0]); + pcc.setYearOfBirth(pDemo.getDOB().toString().split("-")[0]); if (pDemo.getPreferredPhoneNo() != null) - pcc1.setPhoneNumber(pDemo.getPreferredPhoneNo()); + pcc.setPhoneNumber(pDemo.getPreferredPhoneNo()); if (pDemo.getHealthID() != null) - pcc1.setHealthId(pDemo.getHealthID()); + pcc.setHealthId(pDemo.getHealthID()); if (pDemo.getHealthIdNo() != null) - pcc1.setHealthNumber(pDemo.getHealthIdNo()); + pcc.setHealthNumber(pDemo.getHealthIdNo()); ccList.add(cc); - pcc1.setCareContextsList(ccList); + pcc.setCareContextsList(ccList); // save carecontext back to mongo - patientCareContextsMongoRepo.save(pcc1); + patientCareContextsMongoRepo.save(pcc); } } diff --git a/src/main/java/com/wipro/fhir/utils/CookieUtil.java b/src/main/java/com/wipro/fhir/utils/CookieUtil.java deleted file mode 100644 index 3ccec9d..0000000 --- a/src/main/java/com/wipro/fhir/utils/CookieUtil.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.wipro.fhir.utils; - -import java.util.Arrays; -import java.util.Optional; - -import org.springframework.stereotype.Service; - -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -@Service -public class CookieUtil { - - public Optional getCookieValue(HttpServletRequest request, String cookieName) { - Cookie[] cookies = request.getCookies(); - if (cookies != null) { - for (Cookie cookie : cookies) { - if (cookieName.equals(cookie.getName())) { - return Optional.of(cookie.getValue()); - } - } - } - return Optional.empty(); - } - - public String getJwtTokenFromCookie(HttpServletRequest request) { - return Arrays.stream(request.getCookies()).filter(cookie -> "Jwttoken".equals(cookie.getName())) - .map(Cookie::getValue).findFirst().orElse(null); - } -} diff --git a/src/main/java/com/wipro/fhir/utils/FilterConfig.java b/src/main/java/com/wipro/fhir/utils/FilterConfig.java deleted file mode 100644 index 5a7ef36..0000000 --- a/src/main/java/com/wipro/fhir/utils/FilterConfig.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.wipro.fhir.utils; - -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class FilterConfig { - - @Bean - public FilterRegistrationBean jwtUserIdValidationFilter( - JwtAuthenticationUtil jwtAuthenticationUtil) { - FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); - registrationBean.setFilter(new JwtUserIdValidationFilter(jwtAuthenticationUtil)); - registrationBean.addUrlPatterns("/*"); // Apply filter to all API endpoints - return registrationBean; - } - -} diff --git a/src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java b/src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java deleted file mode 100644 index 61cdc90..0000000 --- a/src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.wipro.fhir.utils; - -import java.util.Optional; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; - -import com.wipro.fhir.data.users.User; -import com.wipro.fhir.repo.user.UserLoginRepo; - -import io.jsonwebtoken.Claims; -import jakarta.servlet.http.HttpServletRequest; - -@Component -public class JwtAuthenticationUtil { - - @Autowired - private CookieUtil cookieUtil; - @Autowired - private JwtUtil jwtUtil; - @Autowired - private RedisTemplate redisTemplate; - @Autowired - private UserLoginRepo userLoginRepo; - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - - public JwtAuthenticationUtil(CookieUtil cookieUtil, JwtUtil jwtUtil) { - this.cookieUtil = cookieUtil; - this.jwtUtil = jwtUtil; - } - - public ResponseEntity validateJwtToken(HttpServletRequest request) { - Optional jwtTokenOpt = cookieUtil.getCookieValue(request, "Jwttoken"); - - if (jwtTokenOpt.isEmpty()) { - return ResponseEntity.status(HttpStatus.UNAUTHORIZED) - .body("Error 401: Unauthorized - JWT Token is not set!"); - } - - String jwtToken = jwtTokenOpt.get(); - - // Validate the token - Claims claims = jwtUtil.validateToken(jwtToken); - if (claims == null) { - return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Error 401: Unauthorized - Invalid JWT Token!"); - } - - // Extract username from token - String usernameFromToken = claims.getSubject(); - if (usernameFromToken == null || usernameFromToken.isEmpty()) { - return ResponseEntity.status(HttpStatus.UNAUTHORIZED) - .body("Error 401: Unauthorized - Username is missing!"); - } - - // Return the username if valid - return ResponseEntity.ok(usernameFromToken); - } - - public boolean validateUserIdAndJwtToken(String jwtToken) throws Exception { - try { - // Validate JWT token and extract claims - Claims claims = jwtUtil.validateToken(jwtToken); - - if (claims == null) { - throw new Exception("Invalid JWT token."); - } - - String userId = claims.get("userId", String.class); - - // Check if user data is present in Redis - User user = getUserFromCache(userId); - if (user == null) { - // If not in Redis, fetch from DB and cache the result - user = fetchUserFromDB(userId); - } - if (user == null) { - throw new Exception("Invalid User ID."); - } - - return true; // Valid userId and JWT token - } catch (Exception e) { - logger.error("Validation failed: " + e.getMessage(), e); - throw new Exception("Validation error: " + e.getMessage(), e); - } - } - - private User getUserFromCache(String userId) { - String redisKey = "user_" + userId; // The Redis key format - User user = (User) redisTemplate.opsForValue().get(redisKey); - - if (user == null) { - logger.warn("User not found in Redis. Will try to fetch from DB."); - } else { - logger.info("User fetched successfully from Redis."); - } - - return user; // Returns null if not found - } - - private User fetchUserFromDB(String userId) { - // This method will only be called if the user is not found in Redis. - String redisKey = "user_" + userId; // Redis key format - - // Fetch user from DB - User user = userLoginRepo.getUserByUserID(Long.parseLong(userId)); - - if (user != null) { - // Cache the user in Redis for future requests (cache for 30 minutes) - redisTemplate.opsForValue().set(redisKey, user, 30, TimeUnit.MINUTES); - - // Log that the user has been stored in Redis - logger.info("User stored in Redis with key: " + redisKey); - } else { - logger.warn("User not found for userId: " + userId); - } - - return user; - } -} diff --git a/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java b/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java deleted file mode 100644 index 09ae81f..0000000 --- a/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.wipro.fhir.utils; - -import java.io.IOException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import jakarta.servlet.Filter; -import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; -import jakarta.servlet.ServletRequest; -import jakarta.servlet.ServletResponse; -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -@Component -public class JwtUserIdValidationFilter implements Filter { - - private final JwtAuthenticationUtil jwtAuthenticationUtil; - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - - public JwtUserIdValidationFilter(JwtAuthenticationUtil jwtAuthenticationUtil) { - this.jwtAuthenticationUtil = jwtAuthenticationUtil; - } - - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) - throws IOException, ServletException { - HttpServletRequest request = (HttpServletRequest) servletRequest; - HttpServletResponse response = (HttpServletResponse) servletResponse; - - String path = request.getRequestURI(); - String contextPath = request.getContextPath(); - logger.info("JwtUserIdValidationFilter invoked for path: " + path); - - // Log cookies for debugging - Cookie[] cookies = request.getCookies(); - if (cookies != null) { - for (Cookie cookie : cookies) { - if ("userId".equals(cookie.getName())) { - logger.warn("userId found in cookies! Clearing it..."); - clearUserIdCookie(response); // Explicitly remove userId cookie - } - } - } else { - logger.info("No cookies found in the request"); - } - - // Log headers for debugging - String jwtTokenFromHeader = request.getHeader("Jwttoken"); - logger.info("JWT token from header: "); - - // Skip login and public endpoints - if (path.equals(contextPath + "/user/userAuthenticate") - || path.equalsIgnoreCase(contextPath + "/user/logOutUserFromConcurrentSession") - || path.startsWith(contextPath + "/public")) { - logger.info("Skipping filter for path: " + path); - filterChain.doFilter(servletRequest, servletResponse); - return; - } - - try { - // Retrieve JWT token from cookies - String jwtTokenFromCookie = getJwtTokenFromCookies(request); - logger.info("JWT token from cookie: "); - - // Determine which token (cookie or header) to validate - String jwtToken = jwtTokenFromCookie != null ? jwtTokenFromCookie : jwtTokenFromHeader; - if (jwtToken == null) { - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "JWT token not found in cookies or headers"); - return; - } - - // Validate JWT token and userId - boolean isValid = jwtAuthenticationUtil.validateUserIdAndJwtToken(jwtToken); - - if (isValid) { - // If token is valid, allow the request to proceed - filterChain.doFilter(servletRequest, servletResponse); - } else { - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid JWT token"); - } - } catch (Exception e) { - logger.error("Authorization error: ", e); - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization error: " + e.getMessage()); - } - } - - private String getJwtTokenFromCookies(HttpServletRequest request) { - Cookie[] cookies = request.getCookies(); - if (cookies != null) { - for (Cookie cookie : cookies) { - if (cookie.getName().equals("Jwttoken")) { - return cookie.getValue(); - } - } - } - return null; - } - - private void clearUserIdCookie(HttpServletResponse response) { - Cookie cookie = new Cookie("userId", null); - cookie.setPath("/"); - cookie.setHttpOnly(true); - cookie.setSecure(true); - cookie.setMaxAge(0); // Invalidate the cookie - response.addCookie(cookie); - } -} diff --git a/src/main/java/com/wipro/fhir/utils/JwtUtil.java b/src/main/java/com/wipro/fhir/utils/JwtUtil.java deleted file mode 100644 index 6f22eb7..0000000 --- a/src/main/java/com/wipro/fhir/utils/JwtUtil.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.wipro.fhir.utils; - -import java.security.Key; -import java.util.Date; -import java.util.function.Function; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import io.jsonwebtoken.security.Keys; - -@Component -public class JwtUtil { - - @Value("${jwt.secret}") - private String SECRET_KEY; - - private static final long EXPIRATION_TIME = 24L * 60 * 60 * 1000; // 1 day in milliseconds - - // Generate a key using the secret - private Key getSigningKey() { - if (SECRET_KEY == null || SECRET_KEY.isEmpty()) { - throw new IllegalStateException("JWT secret key is not set in application.properties"); - } - return Keys.hmacShaKeyFor(SECRET_KEY.getBytes()); - } - - // Generate JWT Token - public String generateToken(String username, String userId) { - Date now = new Date(); - Date expiryDate = new Date(now.getTime() + EXPIRATION_TIME); - - // Include the userId in the JWT claims - return Jwts.builder().setSubject(username).claim("userId", userId) // Add userId as a claim - .setIssuedAt(now).setExpiration(expiryDate).signWith(getSigningKey(), SignatureAlgorithm.HS256) - .compact(); - } - - // Validate and parse JWT Token - public Claims validateToken(String token) { - try { - // Use the JwtParserBuilder correctly in version 0.12.6 - return Jwts.parser() // Correct method in 0.12.6 to get JwtParserBuilder - .setSigningKey(getSigningKey()) // Set the signing key - .build() // Build the JwtParser - .parseClaimsJws(token) // Parse and validate the token - .getBody(); - } catch (Exception e) { - return null; // Handle token parsing/validation errors - } - } - - public String extractUsername(String token) { - return extractClaim(token, Claims::getSubject); - } - - public T extractClaim(String token, Function claimsResolver) { - final Claims claims = extractAllClaims(token); - return claimsResolver.apply(claims); - } - - private Claims extractAllClaims(String token) { - return Jwts.parser().setSigningKey(getSigningKey()).build().parseClaimsJws(token).getBody(); - } -} From ebff8ad117d8c913f636c848cdd9fda8175b11e9 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Fri, 21 Mar 2025 14:07:11 +0530 Subject: [PATCH 17/26] verify abha issue with mobile number --- src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java | 1 + .../com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java b/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java index bde1e58..27863f1 100644 --- a/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java +++ b/src/main/java/com/wipro/fhir/data/v3/abhaCard/LoginMethod.java @@ -7,6 +7,7 @@ public class LoginMethod { private String loginId; private String loginMethod; + private String loginHint; private String pId; private String txnId; private String mobileNumber; diff --git a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java index 7c15d3a..4d6b278 100644 --- a/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java @@ -247,7 +247,8 @@ public String verifyAbhaLogin(String request) throws FHIRException { responseMap.put("abhaDetails", jsonResponse.get("accounts").getAsJsonArray().get(0).getAsJsonObject().toString()); responseMap.put("txnId", jsonResponse.get("txnId").getAsString()); - if ("MOBILE".equalsIgnoreCase(loginData.getLoginMethod()) && jsonResponse.has("token")) { + if ("MOBILE".equalsIgnoreCase(loginData.getLoginMethod()) && "MOBILE".equalsIgnoreCase(loginData.getLoginHint()) + && jsonResponse.has("token")) { String xtoken = verifyProfileLoginUser(jsonResponse.get("token").getAsString(), jsonResponse.get("txnId").getAsString(), abhaNumber); responseMap.put("xToken", xtoken); From ba89acc93b6b4f61be5472942a903d8c830e9fd0 Mon Sep 17 00:00:00 2001 From: Karyamsetty Helen Grace Date: Fri, 21 Mar 2025 14:27:15 +0530 Subject: [PATCH 18/26] Reapply "jwt implementation changes (#53)" This reverts commit 9f0372cb5394b7c5bd394f8f2812626dc2385d98. --- .github/workflows/build-on-pull-request.yml | 3 +- .github/workflows/package.yml | 4 +- .github/workflows/sast.yml | 4 +- pom.xml | 40 ++++-- src/main/environment/common_ci.properties | 3 +- src/main/environment/common_dev.properties | 1 + .../environment/common_example.properties | 1 + src/main/environment/common_test.properties | 1 + .../com/wipro/fhir/FhirApiApplication.java | 21 +++ .../com/wipro/fhir/config/RedisConfig.java | 40 ++++++ .../java/com/wipro/fhir/data/users/User.java | 28 ++++ .../wipro/fhir/repo/user/UserLoginRepo.java | 16 +++ .../service/common/CommonServiceImpl.java | 88 +++++++++--- .../java/com/wipro/fhir/utils/CookieUtil.java | 31 +++++ .../com/wipro/fhir/utils/FilterConfig.java | 19 +++ .../fhir/utils/JwtAuthenticationUtil.java | 125 ++++++++++++++++++ .../fhir/utils/JwtUserIdValidationFilter.java | 111 ++++++++++++++++ .../java/com/wipro/fhir/utils/JwtUtil.java | 68 ++++++++++ 18 files changed, 567 insertions(+), 37 deletions(-) create mode 100644 src/main/java/com/wipro/fhir/config/RedisConfig.java create mode 100644 src/main/java/com/wipro/fhir/data/users/User.java create mode 100644 src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java create mode 100644 src/main/java/com/wipro/fhir/utils/CookieUtil.java create mode 100644 src/main/java/com/wipro/fhir/utils/FilterConfig.java create mode 100644 src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java create mode 100644 src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java create mode 100644 src/main/java/com/wipro/fhir/utils/JwtUtil.java diff --git a/.github/workflows/build-on-pull-request.yml b/.github/workflows/build-on-pull-request.yml index 744b905..695b179 100644 --- a/.github/workflows/build-on-pull-request.yml +++ b/.github/workflows/build-on-pull-request.yml @@ -17,6 +17,7 @@ jobs: uses: actions/setup-java@v2 with: java-version: 17 - distribution: 'adopt' + distribution: 'zulu' + - name: Build with Maven run: mvn clean install diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 5cc0ca0..769fce7 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -26,7 +26,7 @@ jobs: uses: actions/setup-java@v2 with: java-version: 17 - distribution: 'adopt' + distribution: 'zulu' - name: Build with Maven run: mvn clean install -DENV_VAR=${{ env.ENV_VAR }} @@ -35,7 +35,7 @@ jobs: run: mvn -B package --file pom.xml - name: Upload WAR file as artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: FHIR-API path: target/fhirapi-v1.0.war diff --git a/.github/workflows/sast.yml b/.github/workflows/sast.yml index eb8d6b3..a886904 100644 --- a/.github/workflows/sast.yml +++ b/.github/workflows/sast.yml @@ -41,10 +41,10 @@ jobs: uses: actions/setup-java@v2 with: java-version: 17 - distribution: 'adopt' + distribution: 'zulu' - name: Build with Maven - run: mvn clean install -DENV_VAR=test + run: mvn clean install - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 diff --git a/pom.xml b/pom.xml index a345c2c..22e8b75 100644 --- a/pom.xml +++ b/pom.xml @@ -58,10 +58,10 @@ org.springframework.boot spring-boot-starter - - co.elastic.logging - logback-ecs-encoder - 1.3.2 + + co.elastic.logging + logback-ecs-encoder + 1.3.2 @@ -189,8 +189,7 @@ spring-boot-starter-mail - + ca.uhn.hapi.fhir hapi-fhir-structures-r4 @@ -198,8 +197,7 @@ - + ca.uhn.hapi.fhir org.hl7.fhir.utilities @@ -235,6 +233,27 @@ json-path 2.9.0 + + + io.jsonwebtoken + jjwt-api + 0.12.6 + + + + io.jsonwebtoken + jjwt-impl + 0.12.6 + runtime + + + + io.jsonwebtoken + jjwt-jackson + 0.12.6 + runtime + + @@ -250,7 +269,7 @@ HTML nvd - + org.apache.maven.plugins @@ -329,8 +348,7 @@ ${target-properties} and ${source-properties} - diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index ed70c81..f3137e0 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -110,4 +110,5 @@ logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO #ELK logging file name -logging.file.name=@env.FHIR_API_LOGGING_FILE_NAME@ \ No newline at end of file +logging.file.name=@env.FHIR_API_LOGGING_FILE_NAME@ +jwt.secret=@env.JWT_SECRET_KEY@ \ No newline at end of file diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index 3e012e9..6210f9e 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -107,3 +107,4 @@ logging.level.org.springframework.web=INFO logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO +jwt.secret= diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index 803d225..0679bed 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -109,3 +109,4 @@ logging.level.org.springframework.web=INFO logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO +jwt.secret= diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties index db18ad9..44e1523 100644 --- a/src/main/environment/common_test.properties +++ b/src/main/environment/common_test.properties @@ -108,3 +108,4 @@ logging.level.org.springframework.web=INFO logging.level.org.hibernate=INFO logging.level.com.iemr=DEBUG logging.level.org.springframework=INFO +jwt.secret= diff --git a/src/main/java/com/wipro/fhir/FhirApiApplication.java b/src/main/java/com/wipro/fhir/FhirApiApplication.java index 0395010..d732a3f 100644 --- a/src/main/java/com/wipro/fhir/FhirApiApplication.java +++ b/src/main/java/com/wipro/fhir/FhirApiApplication.java @@ -26,6 +26,12 @@ import org.springframework.context.annotation.Bean; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import com.wipro.fhir.data.users.User; @SpringBootApplication public class FhirApiApplication { @@ -33,4 +39,19 @@ public class FhirApiApplication { public static void main(String[] args) { SpringApplication.run(FhirApiApplication.class, args); } + + @Bean + public RedisTemplate redisTemplate(RedisConnectionFactory factory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(factory); + + // Use StringRedisSerializer for keys (userId) + template.setKeySerializer(new StringRedisSerializer()); + + // Use Jackson2JsonRedisSerializer for values (Users objects) + Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(User.class); + template.setValueSerializer(serializer); + + return template; + } } diff --git a/src/main/java/com/wipro/fhir/config/RedisConfig.java b/src/main/java/com/wipro/fhir/config/RedisConfig.java new file mode 100644 index 0000000..d29e7c3 --- /dev/null +++ b/src/main/java/com/wipro/fhir/config/RedisConfig.java @@ -0,0 +1,40 @@ +package com.wipro.fhir.config; + +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; +import org.springframework.session.data.redis.config.ConfigureRedisAction; + +import com.wipro.fhir.data.users.User; + +@Configuration +@EnableCaching +public class RedisConfig { + + @Bean + public ConfigureRedisAction configureRedisAction() { + return ConfigureRedisAction.NO_OP; + } + + @Bean + public RedisTemplate redisTemplate(RedisConnectionFactory factory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(factory); + + // Use StringRedisSerializer for keys (userId) + template.setKeySerializer(new StringRedisSerializer()); + + // Use Jackson2JsonRedisSerializer for values (Users objects) + Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(User.class); + template.setValueSerializer(serializer); + + return template; + } + +} + + diff --git a/src/main/java/com/wipro/fhir/data/users/User.java b/src/main/java/com/wipro/fhir/data/users/User.java new file mode 100644 index 0000000..c31049e --- /dev/null +++ b/src/main/java/com/wipro/fhir/data/users/User.java @@ -0,0 +1,28 @@ +package com.wipro.fhir.data.users; + +import java.io.Serializable; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import lombok.Data; + +@Entity +@Table(name = "m_user") +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class User implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "UserID") + private Long userID; + @Column(name = "userName") + private String userName; + @Column(name = "Deleted", insertable = false, updatable = true) + private Boolean deleted; +} diff --git a/src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java b/src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java new file mode 100644 index 0000000..1267ab6 --- /dev/null +++ b/src/main/java/com/wipro/fhir/repo/user/UserLoginRepo.java @@ -0,0 +1,16 @@ +package com.wipro.fhir.repo.user; + +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import com.wipro.fhir.data.users.User; + +@Repository +public interface UserLoginRepo extends CrudRepository { + + @Query(" SELECT u FROM User u WHERE u.userID = :userID AND u.deleted = false ") + public User getUserByUserID(@Param("userID") Long userID); + +} diff --git a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java index 0c87321..5fcf125 100644 --- a/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java @@ -58,11 +58,13 @@ import com.wipro.fhir.data.mongo.care_context.NDHMResponse; import com.wipro.fhir.data.mongo.care_context.Notification; import com.wipro.fhir.data.mongo.care_context.PatientCareContexts; +import com.wipro.fhir.data.mongo.care_context.PatientCareContextsStringOBJ; import com.wipro.fhir.data.mongo.care_context.SMSNotify; import com.wipro.fhir.data.patient.PatientDemographic; import com.wipro.fhir.data.patient_data_handler.PatientDemographicModel_NDHM_Patient_Profile; import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation; import com.wipro.fhir.data.request_handler.ResourceRequestHandler; +import com.wipro.fhir.data.users.User; import com.wipro.fhir.repo.common.PatientEligibleForResourceCreationRepo; import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; import com.wipro.fhir.repo.mongo.amrit_resource.AMRIT_ResourceMongoRepo; @@ -101,6 +103,12 @@ public class CommonServiceImpl implements CommonService { private static String authKey; private UUID uuid; + + // public static String NDHM_AUTH_TOKEN; + // public static Long NDHM_TOKEN_EXP; + // public static String NDHM_OTP_TOKEN; + + @Value("${clientID}") private String clientID; @@ -161,7 +169,8 @@ public String processResourceOperation() throws FHIRException { String response = null; // list of patient eligible for resource creation List pList = getPatientListForResourceEligible(); - logger.info("No of records available to create FHIR in last 2 dagetPatientListForResourceEligibleys : " + pList.size()); + logger.info("No of records available to create FHIR in last 2 dagetPatientListForResourceEligibleys : " + + pList.size()); ResourceRequestHandler resourceRequestHandler; for (PatientEligibleForResourceCreation p : pList) { @@ -290,6 +299,38 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe if (pDemo != null && pVisit != null) { + +// JsonObject jsnOBJ = new JsonObject(); +// JsonParser jsnParser = new JsonParser(); +// JsonElement jsnElmnt = jsnParser.parse(requestObj); +// jsnOBJ = jsnElmnt.getAsJsonObject(); + + PatientCareContextsStringOBJ patientCareContextsStringOBJ = new PatientCareContextsStringOBJ(); + + // wrong variable name in request obj for benregid, need to correct in main + // request obj first +// Long benID = null; +// Long benRegID = null; +// Long visitCode = null; +// +// if (jsnOBJ.has("beneficiaryID") && jsnOBJ.get("beneficiaryID") != null) +// benRegID = jsnOBJ.get("beneficiaryID").getAsLong(); +// if (jsnOBJ.has("visitCode") && jsnOBJ.get("visitCode") != null) +// visitCode = jsnOBJ.get("visitCode").getAsLong(); +// String healthID = jsnOBJ.get("healthID").getAsString(); +// String healthIDNumber = jsnOBJ.get("healthIdNumber").getAsString(); +// String visitCategory = jsnOBJ.get("visitCategory").getAsString(); +// String phoneNo; +// String gender; +// String yearOfBirth; +// String name; +// String email; + + // get benid +// if (benRegID != null) +// benID = benHealthIDMappingRepo.getBenID(benRegID); + + // fetch abdm facility id logger.info("********t_benvisistData fetch request pvisit data :", pVisit); @@ -299,6 +340,7 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe ArrayList ccList = new ArrayList<>(); CareContexts cc = new CareContexts(); + logger.info("********t_benvisistData fetch response : {}", res); cc.setReferenceNumber(pVisit.getVisitCode() != null ? pVisit.getVisitCode().toString() : null); @@ -310,16 +352,22 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe cc.setCareContextLinkedDate(resData[1] != null ? resData[1].toString() : null); } + logger.info("********data to be saved in mongo :", cc); PatientCareContexts pcc; + PatientCareContexts resultSet = null; + + + logger.info("********data to be saved in mongo :", cc); + PatientCareContexts pcc1; if (pDemo.getBeneficiaryID() != null) { - pcc = patientCareContextsMongoRepo.findByIdentifier(pDemo.getBeneficiaryID().toString()); + pcc1 = patientCareContextsMongoRepo.findByIdentifier(pDemo.getBeneficiaryID().toString()); - if (pcc != null && pcc.getIdentifier() != null) { + if (pcc1 != null && pcc1.getIdentifier() != null) { // Get the existing careContextsList - if (pcc.getCareContextsList() != null && pcc.getCareContextsList().size() > 0) { - ccList = pcc.getCareContextsList(); + if (pcc1.getCareContextsList() != null && pcc1.getCareContextsList().size() > 0) { + ccList = pcc1.getCareContextsList(); // Check if the visitCode is already in the careContextsList for (CareContexts existingContext : ccList) { @@ -330,8 +378,8 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe } } ccList.add(cc); - pcc.setCareContextsList(ccList); - patientCareContextsMongoRepo.save(pcc); + pcc1.setCareContextsList(ccList); + patientCareContextsMongoRepo.save(pcc1); } // } // if (pcc != null && pcc.getIdentifier() != null) { @@ -341,20 +389,20 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe // resultSet = patientCareContextsMongoRepo.save(pcc); // } else { - pcc = new PatientCareContexts(); - pcc.setCaseReferenceNumber(pDemo.getBeneficiaryID().toString()); - pcc.setIdentifier(pDemo.getBeneficiaryID().toString()); + pcc1 = new PatientCareContexts(); + pcc1.setCaseReferenceNumber(pDemo.getBeneficiaryID().toString()); + pcc1.setIdentifier(pDemo.getBeneficiaryID().toString()); if (pDemo.getGenderID() != null) { switch (pDemo.getGenderID()) { case 1: - pcc.setGender("M"); + pcc1.setGender("M"); break; case 2: - pcc.setGender("F"); + pcc1.setGender("F"); break; case 3: - pcc.setGender("O"); + pcc1.setGender("O"); break; default: @@ -362,19 +410,19 @@ public void addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRe } } if (pDemo.getName() != null) - pcc.setName(pDemo.getName()); + pcc1.setName(pDemo.getName()); if (pDemo.getDOB() != null) - pcc.setYearOfBirth(pDemo.getDOB().toString().split("-")[0]); + pcc1.setYearOfBirth(pDemo.getDOB().toString().split("-")[0]); if (pDemo.getPreferredPhoneNo() != null) - pcc.setPhoneNumber(pDemo.getPreferredPhoneNo()); + pcc1.setPhoneNumber(pDemo.getPreferredPhoneNo()); if (pDemo.getHealthID() != null) - pcc.setHealthId(pDemo.getHealthID()); + pcc1.setHealthId(pDemo.getHealthID()); if (pDemo.getHealthIdNo() != null) - pcc.setHealthNumber(pDemo.getHealthIdNo()); + pcc1.setHealthNumber(pDemo.getHealthIdNo()); ccList.add(cc); - pcc.setCareContextsList(ccList); + pcc1.setCareContextsList(ccList); // save carecontext back to mongo - patientCareContextsMongoRepo.save(pcc); + patientCareContextsMongoRepo.save(pcc1); } } diff --git a/src/main/java/com/wipro/fhir/utils/CookieUtil.java b/src/main/java/com/wipro/fhir/utils/CookieUtil.java new file mode 100644 index 0000000..3ccec9d --- /dev/null +++ b/src/main/java/com/wipro/fhir/utils/CookieUtil.java @@ -0,0 +1,31 @@ +package com.wipro.fhir.utils; + +import java.util.Arrays; +import java.util.Optional; + +import org.springframework.stereotype.Service; + +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@Service +public class CookieUtil { + + public Optional getCookieValue(HttpServletRequest request, String cookieName) { + Cookie[] cookies = request.getCookies(); + if (cookies != null) { + for (Cookie cookie : cookies) { + if (cookieName.equals(cookie.getName())) { + return Optional.of(cookie.getValue()); + } + } + } + return Optional.empty(); + } + + public String getJwtTokenFromCookie(HttpServletRequest request) { + return Arrays.stream(request.getCookies()).filter(cookie -> "Jwttoken".equals(cookie.getName())) + .map(Cookie::getValue).findFirst().orElse(null); + } +} diff --git a/src/main/java/com/wipro/fhir/utils/FilterConfig.java b/src/main/java/com/wipro/fhir/utils/FilterConfig.java new file mode 100644 index 0000000..5a7ef36 --- /dev/null +++ b/src/main/java/com/wipro/fhir/utils/FilterConfig.java @@ -0,0 +1,19 @@ +package com.wipro.fhir.utils; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class FilterConfig { + + @Bean + public FilterRegistrationBean jwtUserIdValidationFilter( + JwtAuthenticationUtil jwtAuthenticationUtil) { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(new JwtUserIdValidationFilter(jwtAuthenticationUtil)); + registrationBean.addUrlPatterns("/*"); // Apply filter to all API endpoints + return registrationBean; + } + +} diff --git a/src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java b/src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java new file mode 100644 index 0000000..61cdc90 --- /dev/null +++ b/src/main/java/com/wipro/fhir/utils/JwtAuthenticationUtil.java @@ -0,0 +1,125 @@ +package com.wipro.fhir.utils; + +import java.util.Optional; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; + +import com.wipro.fhir.data.users.User; +import com.wipro.fhir.repo.user.UserLoginRepo; + +import io.jsonwebtoken.Claims; +import jakarta.servlet.http.HttpServletRequest; + +@Component +public class JwtAuthenticationUtil { + + @Autowired + private CookieUtil cookieUtil; + @Autowired + private JwtUtil jwtUtil; + @Autowired + private RedisTemplate redisTemplate; + @Autowired + private UserLoginRepo userLoginRepo; + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + public JwtAuthenticationUtil(CookieUtil cookieUtil, JwtUtil jwtUtil) { + this.cookieUtil = cookieUtil; + this.jwtUtil = jwtUtil; + } + + public ResponseEntity validateJwtToken(HttpServletRequest request) { + Optional jwtTokenOpt = cookieUtil.getCookieValue(request, "Jwttoken"); + + if (jwtTokenOpt.isEmpty()) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .body("Error 401: Unauthorized - JWT Token is not set!"); + } + + String jwtToken = jwtTokenOpt.get(); + + // Validate the token + Claims claims = jwtUtil.validateToken(jwtToken); + if (claims == null) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Error 401: Unauthorized - Invalid JWT Token!"); + } + + // Extract username from token + String usernameFromToken = claims.getSubject(); + if (usernameFromToken == null || usernameFromToken.isEmpty()) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .body("Error 401: Unauthorized - Username is missing!"); + } + + // Return the username if valid + return ResponseEntity.ok(usernameFromToken); + } + + public boolean validateUserIdAndJwtToken(String jwtToken) throws Exception { + try { + // Validate JWT token and extract claims + Claims claims = jwtUtil.validateToken(jwtToken); + + if (claims == null) { + throw new Exception("Invalid JWT token."); + } + + String userId = claims.get("userId", String.class); + + // Check if user data is present in Redis + User user = getUserFromCache(userId); + if (user == null) { + // If not in Redis, fetch from DB and cache the result + user = fetchUserFromDB(userId); + } + if (user == null) { + throw new Exception("Invalid User ID."); + } + + return true; // Valid userId and JWT token + } catch (Exception e) { + logger.error("Validation failed: " + e.getMessage(), e); + throw new Exception("Validation error: " + e.getMessage(), e); + } + } + + private User getUserFromCache(String userId) { + String redisKey = "user_" + userId; // The Redis key format + User user = (User) redisTemplate.opsForValue().get(redisKey); + + if (user == null) { + logger.warn("User not found in Redis. Will try to fetch from DB."); + } else { + logger.info("User fetched successfully from Redis."); + } + + return user; // Returns null if not found + } + + private User fetchUserFromDB(String userId) { + // This method will only be called if the user is not found in Redis. + String redisKey = "user_" + userId; // Redis key format + + // Fetch user from DB + User user = userLoginRepo.getUserByUserID(Long.parseLong(userId)); + + if (user != null) { + // Cache the user in Redis for future requests (cache for 30 minutes) + redisTemplate.opsForValue().set(redisKey, user, 30, TimeUnit.MINUTES); + + // Log that the user has been stored in Redis + logger.info("User stored in Redis with key: " + redisKey); + } else { + logger.warn("User not found for userId: " + userId); + } + + return user; + } +} diff --git a/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java b/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java new file mode 100644 index 0000000..09ae81f --- /dev/null +++ b/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java @@ -0,0 +1,111 @@ +package com.wipro.fhir.utils; + +import java.io.IOException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@Component +public class JwtUserIdValidationFilter implements Filter { + + private final JwtAuthenticationUtil jwtAuthenticationUtil; + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + public JwtUserIdValidationFilter(JwtAuthenticationUtil jwtAuthenticationUtil) { + this.jwtAuthenticationUtil = jwtAuthenticationUtil; + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + HttpServletRequest request = (HttpServletRequest) servletRequest; + HttpServletResponse response = (HttpServletResponse) servletResponse; + + String path = request.getRequestURI(); + String contextPath = request.getContextPath(); + logger.info("JwtUserIdValidationFilter invoked for path: " + path); + + // Log cookies for debugging + Cookie[] cookies = request.getCookies(); + if (cookies != null) { + for (Cookie cookie : cookies) { + if ("userId".equals(cookie.getName())) { + logger.warn("userId found in cookies! Clearing it..."); + clearUserIdCookie(response); // Explicitly remove userId cookie + } + } + } else { + logger.info("No cookies found in the request"); + } + + // Log headers for debugging + String jwtTokenFromHeader = request.getHeader("Jwttoken"); + logger.info("JWT token from header: "); + + // Skip login and public endpoints + if (path.equals(contextPath + "/user/userAuthenticate") + || path.equalsIgnoreCase(contextPath + "/user/logOutUserFromConcurrentSession") + || path.startsWith(contextPath + "/public")) { + logger.info("Skipping filter for path: " + path); + filterChain.doFilter(servletRequest, servletResponse); + return; + } + + try { + // Retrieve JWT token from cookies + String jwtTokenFromCookie = getJwtTokenFromCookies(request); + logger.info("JWT token from cookie: "); + + // Determine which token (cookie or header) to validate + String jwtToken = jwtTokenFromCookie != null ? jwtTokenFromCookie : jwtTokenFromHeader; + if (jwtToken == null) { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "JWT token not found in cookies or headers"); + return; + } + + // Validate JWT token and userId + boolean isValid = jwtAuthenticationUtil.validateUserIdAndJwtToken(jwtToken); + + if (isValid) { + // If token is valid, allow the request to proceed + filterChain.doFilter(servletRequest, servletResponse); + } else { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid JWT token"); + } + } catch (Exception e) { + logger.error("Authorization error: ", e); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization error: " + e.getMessage()); + } + } + + private String getJwtTokenFromCookies(HttpServletRequest request) { + Cookie[] cookies = request.getCookies(); + if (cookies != null) { + for (Cookie cookie : cookies) { + if (cookie.getName().equals("Jwttoken")) { + return cookie.getValue(); + } + } + } + return null; + } + + private void clearUserIdCookie(HttpServletResponse response) { + Cookie cookie = new Cookie("userId", null); + cookie.setPath("/"); + cookie.setHttpOnly(true); + cookie.setSecure(true); + cookie.setMaxAge(0); // Invalidate the cookie + response.addCookie(cookie); + } +} diff --git a/src/main/java/com/wipro/fhir/utils/JwtUtil.java b/src/main/java/com/wipro/fhir/utils/JwtUtil.java new file mode 100644 index 0000000..6f22eb7 --- /dev/null +++ b/src/main/java/com/wipro/fhir/utils/JwtUtil.java @@ -0,0 +1,68 @@ +package com.wipro.fhir.utils; + +import java.security.Key; +import java.util.Date; +import java.util.function.Function; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.security.Keys; + +@Component +public class JwtUtil { + + @Value("${jwt.secret}") + private String SECRET_KEY; + + private static final long EXPIRATION_TIME = 24L * 60 * 60 * 1000; // 1 day in milliseconds + + // Generate a key using the secret + private Key getSigningKey() { + if (SECRET_KEY == null || SECRET_KEY.isEmpty()) { + throw new IllegalStateException("JWT secret key is not set in application.properties"); + } + return Keys.hmacShaKeyFor(SECRET_KEY.getBytes()); + } + + // Generate JWT Token + public String generateToken(String username, String userId) { + Date now = new Date(); + Date expiryDate = new Date(now.getTime() + EXPIRATION_TIME); + + // Include the userId in the JWT claims + return Jwts.builder().setSubject(username).claim("userId", userId) // Add userId as a claim + .setIssuedAt(now).setExpiration(expiryDate).signWith(getSigningKey(), SignatureAlgorithm.HS256) + .compact(); + } + + // Validate and parse JWT Token + public Claims validateToken(String token) { + try { + // Use the JwtParserBuilder correctly in version 0.12.6 + return Jwts.parser() // Correct method in 0.12.6 to get JwtParserBuilder + .setSigningKey(getSigningKey()) // Set the signing key + .build() // Build the JwtParser + .parseClaimsJws(token) // Parse and validate the token + .getBody(); + } catch (Exception e) { + return null; // Handle token parsing/validation errors + } + } + + public String extractUsername(String token) { + return extractClaim(token, Claims::getSubject); + } + + public T extractClaim(String token, Function claimsResolver) { + final Claims claims = extractAllClaims(token); + return claimsResolver.apply(claims); + } + + private Claims extractAllClaims(String token) { + return Jwts.parser().setSigningKey(getSigningKey()).build().parseClaimsJws(token).getBody(); + } +} From 86617604fc975cf637a2aab594ab8c813bfa974e Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Fri, 21 Mar 2025 14:44:04 +0530 Subject: [PATCH 19/26] lombok version changes --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 22e8b75..eb98740 100644 --- a/pom.xml +++ b/pom.xml @@ -27,7 +27,7 @@ jdt_apt 1.2.0.Final - 1.16.18 + 1.18.36 ${ENV_VAR} target/classes/application.properties @@ -292,7 +292,7 @@ org.projectlombok lombok - ${lombok.version} + ${org.projectlombok.version} org.mapstruct From 3e2c7b2f4c084c1ce121624df6c5ca9ac487c37f Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Thu, 3 Apr 2025 20:09:59 +0530 Subject: [PATCH 20/26] API to fetch beneficiary ID linked with HealthID --- .../healthID/CreateHealthIDWithMobileOTP.java | 26 +++++++++++++++++++ .../repo/healthID/BenHealthIDMappingRepo.java | 6 +++++ .../service/healthID/HealthIDService.java | 1 + .../service/healthID/HealthIDServiceImpl.java | 12 +++++++++ 4 files changed, 45 insertions(+) diff --git a/src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithMobileOTP.java b/src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithMobileOTP.java index 5a5528e..99eebb2 100644 --- a/src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithMobileOTP.java +++ b/src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithMobileOTP.java @@ -139,5 +139,31 @@ public String getBenhealthID( logger.info("NDHM_FHIR get beneficiary ABHA response:" + response.toString()); return response.toString(); } + + @CrossOrigin() + @Operation(summary = "Get Beneficiary Id for ABHA Id") + @PostMapping(value = { "/getBenIdForhealthID" }) + public String getBenIdForhealthID( + @Param(value = "{\"healthIdNumber\":\"String\"}") @RequestBody String request) { + OutputResponse response = new OutputResponse(); + + logger.info("NDHM_FHIR Request obj to fetch beneficiary Ids for HealthID :" + request); + try { + JSONObject obj = new JSONObject(request); + if (request != null) { + String healthId = obj.getString("healthIdNumber"); + String res = healthIDService.getMappedBenIdForHealthId(healthId); + response.setResponse(res); + } else { + logger.info("NDHM_FHIR Invalid Request Data."); + response.setError(5000, "NDHM_FHIR Invalid request"); + } + } catch (Exception e) { + response.setError(5000, e.getMessage()); + logger.error("NDHM_FHIR Error while getting beneficiary Ids for HealthID:" + e); + } + logger.info("NDHM_FHIR get beneficiary Ids for HealthID response:" + response.toString()); + return response.toString(); + } } diff --git a/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java b/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java index ef3e226..d79212e 100644 --- a/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java +++ b/src/main/java/com/wipro/fhir/repo/healthID/BenHealthIDMappingRepo.java @@ -45,6 +45,12 @@ public interface BenHealthIDMappingRepo extends CrudRepository getHealthDetails(@Param("benRegID") Long benRegID); + @Query("SELECT bvd.beneficiaryRegID from BenHealthIDMapping bvd WHERE bvd.healthIdNumber = :healthIdNumber") + public String[] getBenIdForHealthId(@Param("healthIdNumber") String healthIdNumber); + + @Query(value = "SELECT BeneficiaryID FROM db_identity.m_beneficiaryregidmapping where BenRegId in (:benIds)", nativeQuery = true) + public String[] getBeneficiaryIds(@Param("benIds") String[] benIds); + @Transactional @Modifying @Query(value = "UPDATE db_iemr.t_benvisitdetail SET HealthID= :healthID,HealthIdNumber= :healthIdNumber,CarecontextLinkDate=CURRENT_TIMESTAMP() WHERE VisitCode= :visitCode ", nativeQuery = true) diff --git a/src/main/java/com/wipro/fhir/service/healthID/HealthIDService.java b/src/main/java/com/wipro/fhir/service/healthID/HealthIDService.java index 57619e6..51785c9 100644 --- a/src/main/java/com/wipro/fhir/service/healthID/HealthIDService.java +++ b/src/main/java/com/wipro/fhir/service/healthID/HealthIDService.java @@ -27,4 +27,5 @@ public interface HealthIDService { String mapHealthIDToBeneficiary(String request) throws FHIRException; public String getBenHealthID(Long benRegID); public String addRecordToHealthIdTable(String request) throws FHIRException; +public String getMappedBenIdForHealthId(String healthIdNumber); } diff --git a/src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java b/src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java index f89c793..c7ed50f 100644 --- a/src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java @@ -176,4 +176,16 @@ public String addRecordToHealthIdTable(String request) throws FHIRException { } return res; } + + @Override + public String getMappedBenIdForHealthId(String healthIdNumber) { + String[] beneficiaryIdsList = benHealthIDMappingRepo.getBenIdForHealthId(healthIdNumber); + + if(beneficiaryIdsList.length > 0) { + String[] benIds = benHealthIDMappingRepo.getBeneficiaryIds(beneficiaryIdsList); + return String.join(",", benIds); + } + return "No Beneficiary Found"; + } + } \ No newline at end of file From d77f370175ea2eaecfc57e7d27f4b8bbeb477093 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Tue, 8 Apr 2025 11:58:33 +0530 Subject: [PATCH 21/26] modified sending benIds --- .../com/wipro/fhir/service/healthID/HealthIDServiceImpl.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java b/src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java index c7ed50f..7fef7de 100644 --- a/src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java @@ -23,6 +23,7 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -183,7 +184,7 @@ public String getMappedBenIdForHealthId(String healthIdNumber) { if(beneficiaryIdsList.length > 0) { String[] benIds = benHealthIDMappingRepo.getBeneficiaryIds(beneficiaryIdsList); - return String.join(",", benIds); + return Arrays.toString(benIds); } return "No Beneficiary Found"; } From 925dad383b756564cb5ec979378cedaded35d4cd Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Tue, 8 Apr 2025 17:41:29 +0530 Subject: [PATCH 22/26] getServices API upgrade to V3 --- .../service/facility/FacilityServiceImpl.java | 42 ++++++++++++++++--- 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java b/src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java index bcb6925..b066fee 100644 --- a/src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/facility/FacilityServiceImpl.java @@ -1,14 +1,26 @@ package com.wipro.fhir.service.facility; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Date; import java.util.HashMap; import java.util.List; +import java.util.TimeZone; +import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; import com.google.gson.Gson; import com.google.gson.JsonArray; @@ -19,6 +31,7 @@ import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo; import com.wipro.fhir.service.ndhm.Common_NDHMService; import com.wipro.fhir.service.ndhm.GenerateSession_NDHMService; +import com.wipro.fhir.service.v3.abha.GenerateAuthSessionService; import com.wipro.fhir.utils.exception.FHIRException; import com.wipro.fhir.utils.http.HttpUtils; import com.wipro.fhir.utils.mapper.InputMapper; @@ -27,10 +40,12 @@ public class FacilityServiceImpl implements FacilityService{ @Value("${getAbdmFacilityServicies}") private String getAbdmServicies; - @Value("${abdmFacilityId}") private String abdmFacilityId; + @Value("${x-CM-ID}") + private String xCMId; + @Autowired private HttpUtils httpUtils; @@ -38,7 +53,7 @@ public class FacilityServiceImpl implements FacilityService{ private Common_NDHMService common_NDHMService; @Autowired - private GenerateSession_NDHMService generateSession_NDHM; + private GenerateAuthSessionService generateAuthSessionService; @Autowired private BenHealthIDMappingRepo benHealthIDMappingRepo; @@ -47,13 +62,28 @@ public class FacilityServiceImpl implements FacilityService{ public String fetchRegisteredFacilities() throws FHIRException { String res = null; List> list = new ArrayList<>(); + RestTemplate restTemplate = new RestTemplate(); HashMap map = new HashMap<>(); try { - String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); - HttpHeaders headers = common_NDHMService.getHeaders(ndhmAuthToken); - ResponseEntity responseEntity = httpUtils.getWithResponseEntity(getAbdmServicies, headers); + String abhaAuthToken = generateAuthSessionService.getAbhaAuthToken(); + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON.toString()); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + String nowAsISO = df.format(new Date()); + headers.add("TIMESTAMP", nowAsISO); + headers.add("X-CM-ID", xCMId); + headers.add("Authorization", abhaAuthToken); + + HttpEntity httpEntity = new HttpEntity<>(headers); + ResponseEntity responseEntity = restTemplate.exchange(getAbdmServicies, HttpMethod.GET, + httpEntity, String.class); + String responseStrLogin = common_NDHMService.getBody(responseEntity); - if (responseStrLogin != null) { + if (responseEntity.getStatusCode() == HttpStatusCode.valueOf(200) && responseEntity.hasBody()) { JsonObject jsnOBJ = new JsonObject(); JsonParser jsnParser = new JsonParser(); JsonElement jsnElmnt = jsnParser.parse(responseStrLogin); From 0a4881e6db9ba906fb6271666759390da5775268 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Tue, 8 Apr 2025 18:25:47 +0530 Subject: [PATCH 23/26] Updated environment files --- src/main/environment/common_ci.properties | 2 +- src/main/environment/common_dev.properties | 2 +- src/main/environment/common_example.properties | 2 +- src/main/environment/common_test.properties | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index f3137e0..0ae3e9a 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -82,7 +82,7 @@ abdmConfirmAadhaarBio=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/confirmWithAadha abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile ##ABDM Facility services -getAbdmFacilityServicies= @env.ABDM_BASE_URL@/devservice/v1/bridges/getServices +getAbdmFacilityServicies= @env.ABDM_BASE_URL@/api/hiecm/gateway/v3/bridge-services ##ABDM V3 APIs abdmV3UserAuthenticate = @env.ABDM_BASE_URL@/api/hiecm/gateway/v3/sessions diff --git a/src/main/environment/common_dev.properties b/src/main/environment/common_dev.properties index 6210f9e..c0d1bf8 100644 --- a/src/main/environment/common_dev.properties +++ b/src/main/environment/common_dev.properties @@ -82,7 +82,7 @@ abdmConfirmAadhaarBio=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/confirmWithAadha abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile ##ABDM Facility services -getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices +getAbdmFacilityServicies= https://dev.abdm.gov.in/api/hiecm/gateway/v3/bridge-services ##ABDM V3 APIs abdmV3UserAuthenticate = https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index 0679bed..ed56841 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -85,7 +85,7 @@ abdmConfirmAadhaarBio=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/confirmWithAadha abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile ##ABDM Facility services -getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices +getAbdmFacilityServicies= https://dev.abdm.gov.in/api/hiecm/gateway/v3/bridge-services ##ABDM V3 APIs abdmV3UserAuthenticate = https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions diff --git a/src/main/environment/common_test.properties b/src/main/environment/common_test.properties index 44e1523..8195ad8 100644 --- a/src/main/environment/common_test.properties +++ b/src/main/environment/common_test.properties @@ -82,7 +82,7 @@ abdmConfirmAadhaarBio=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/confirmWithAadha abdmAccountProfile=@env.ABDM_Account_ID_BASE_URL@/api/v1/account/profile ##ABDM Facility services -getAbdmFacilityServicies= https://dev.abdm.gov.in/devservice/v1/bridges/getServices +getAbdmFacilityServicies= https://dev.abdm.gov.in/api/hiecm/gateway/v3/bridge-services ##ABDM V3 APIs abdmV3UserAuthenticate = https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions From 00e28eb4f388dbeb2f7d86dd99f410f75d60c59f Mon Sep 17 00:00:00 2001 From: Helen Grace Karyamsetty <133211481+helenKaryamsetty@users.noreply.github.com> Date: Mon, 19 May 2025 17:02:32 +0530 Subject: [PATCH 24/26] fix(bug): fhir bundle creation scheduler calling for every 5mins --- src/main/resources/application.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 4b0490d..dd90173 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -31,7 +31,7 @@ enableIPValidation=false ## quartz setup - fhir resource - bundle generation start-FHIR-resource-bundle-scheduler=true -cron-scheduler-FHIR-resource-bundle=0 0/1 * * * ? * +cron-scheduler-FHIR-resource-bundle=0 0/5 * * * ? * ## quartz setup - patient profile creation start-FHIR-patient-profile-scheduler=false From fa6ef697026198fce84cafbd3a656c4527c56c07 Mon Sep 17 00:00:00 2001 From: KA40094929 Date: Tue, 20 May 2025 17:55:53 +0530 Subject: [PATCH 25/26] fix(bug): changed to objectmapper to gson malformed error --- .../fhir/service/ndhm/GenerateHealthID_CardServiceImpl.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/wipro/fhir/service/ndhm/GenerateHealthID_CardServiceImpl.java b/src/main/java/com/wipro/fhir/service/ndhm/GenerateHealthID_CardServiceImpl.java index 61780c7..c23d964 100644 --- a/src/main/java/com/wipro/fhir/service/ndhm/GenerateHealthID_CardServiceImpl.java +++ b/src/main/java/com/wipro/fhir/service/ndhm/GenerateHealthID_CardServiceImpl.java @@ -34,6 +34,7 @@ import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -78,7 +79,8 @@ public String generateOTP(String request) throws FHIRException { String ndhmAuthToken = generateSession_NDHM.getNDHMAuthToken(); Map responseMap = new HashMap(); - SendOTPForCard obj = InputMapper.gson().fromJson(request, SendOTPForCard.class); + ObjectMapper objectMapper = new ObjectMapper(); + SendOTPForCard obj = objectMapper.convertValue(request, SendOTPForCard.class); Map requestMap = null; requestMap = new HashMap(); From 35bd3f8041faa02736a5e58ba1fe6626ddb49087 Mon Sep 17 00:00:00 2001 From: Helen Grace Karyamsetty <133211481+helenKaryamsetty@users.noreply.github.com> Date: Tue, 20 May 2025 19:08:45 +0530 Subject: [PATCH 26/26] fix(bug): bymistake removed comment --- src/main/environment/common_ci.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index 51771c1..eff10a9 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -81,7 +81,7 @@ abdmGenerateMobileOTP=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/registration/aadhaar/ abdmConfirmAadhaarBio=@env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/confirmWithAadhaarBio abdmAccountProfile=@env.ABDM_ACCOUNT_ID_BASE_URL@/api/v1/account/profile - +##ABDM Facility services getAbdmFacilityServicies= @env.ABDM_HIECM_BASE_URL@/api/hiecm/gateway/v3/bridge-services ##ABDM V3 APIs