Skip to content
Merged

3.3.0 #227

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
9f0fbb0
Beneficiary consent
SauravBizbRolly Mar 10, 2025
a94ad60
Beneficiary consent
SauravBizbRolly Mar 10, 2025
64f84be
Merge pull request #170 from toarunmishra/beneficiary_consent
sushant-bizbrolly Mar 13, 2025
01abcbd
Beneficiary consent
SauravBizbRolly Apr 10, 2025
0f0113c
Beneficiary consent
SauravBizbRolly Apr 10, 2025
a5b595e
Beneficiary consent
SauravBizbRolly Apr 10, 2025
a363c33
Beneficiary consent
SauravBizbRolly Apr 10, 2025
72715a7
firebase setup
SauravBizbRolly Apr 11, 2025
121928c
firebase setup
SauravBizbRolly Apr 11, 2025
396359d
firebase setup
SauravBizbRolly Apr 11, 2025
0e24515
firebase setup
SauravBizbRolly Apr 11, 2025
70a4256
firebase setup
SauravBizbRolly Apr 14, 2025
8df1a0f
firebase setup
SauravBizbRolly Apr 17, 2025
7222cbd
Firebase Configuration in ci
SauravBizbRolly Apr 17, 2025
ede0339
Firebase Configuration in ci
SauravBizbRolly Apr 17, 2025
e3a177e
firebase notification setup
SauravBizbRolly May 2, 2025
ea47470
Beneficiary consent
SauravBizbRolly Jun 13, 2025
dbe771c
Merge branch 'enhancement' into beneficiaries_consent
SauravBizbRolly Jun 13, 2025
48344e0
Merge pull request #183 from toarunmishra/firebase_setup
sushant-bizbrolly Jun 13, 2025
23cbcca
Merge branch 'enhancement' into beneficiaries_consent
SauravBizbRolly Jun 19, 2025
e914bd3
Merge pull request #222 from toarunmishra/beneficiaries_consent
SauravBizbRolly Jun 19, 2025
cafa96e
Merge remote-tracking branch 'upstream/develop' into enhancement
SauravBizbRolly Jun 19, 2025
bab8d0a
Firebase update userToken
SauravBizbRolly Jun 19, 2025
8f8cc6f
Firebase update userToken
SauravBizbRolly Jun 19, 2025
afd9a1e
Merge pull request #228 from toarunmishra/firebase_setup
SauravBizbRolly Jun 19, 2025
465795f
Merge remote-tracking branch 'upstream/enhancement' into 3.3.0
SauravBizbRolly Jun 19, 2025
f6ca2b9
Add firebase variables in common_docker.properties
SauravBizbRolly Jun 19, 2025
825c2c2
Add firebase variables in common_docker.properties
SauravBizbRolly Jun 19, 2025
02c5a89
update firebase variables in common_docker.properties
SauravBizbRolly Jun 20, 2025
6e9d253
update firebase variables in common_docker.properties
SauravBizbRolly Jun 20, 2025
cbe0d55
update firebase variables in common_docker.properties
SauravBizbRolly Jun 20, 2025
37aadb5
fixed code
SauravBizbRolly Jun 21, 2025
599ed6e
fixed code
SauravBizbRolly Jun 21, 2025
4970f1e
Fixed security hotspot
SauravBizbRolly Jun 23, 2025
41b327b
Fixed security hotspot
SauravBizbRolly Jun 23, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,12 @@

</exclusions>
</dependency>

<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>9.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
Expand Down
7 changes: 7 additions & 0 deletions src/main/environment/common_ci.properties
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ send-message-url=@env.SMS_MESSAGE_URL@
start-sms-scheduler=true
cron-scheduler-sms=0 0/1 * * * ? *

# Firebase Configuration
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add similar variables to the _docker file

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have added firebase configuration in _ docker file

firebase.enabled=@env.FIREBASE_ENABLE@
# if using file
firebase.credential-file=@env.FIREBASE_CREDENTIAL@
# for CI/CD
firebase.credential-base64=@env.CREDENTIAL_BASE64@

#### Email Configuration
send-email=@env.SEND_EMAIL@
spring.mail.host=@env.MAIL_HOST@
Expand Down
9 changes: 8 additions & 1 deletion src/main/environment/common_docker.properties
Original file line number Diff line number Diff line change
Expand Up @@ -178,4 +178,11 @@ captcha.secret-key=${CAPTCHA_SECRET_KEY}
captcha.verify-url=${CAPTCHA_VERIFY_URL}
captcha.enable-captcha=${ENABLE_CAPTCHA}

cors.allowed-origins=${CORS_ALLOWED_ORIGINS}
cors.allowed-origins=${CORS_ALLOWED_ORIGINS}

# Firebase Configuration
firebase.enabled=${FIREBASE_ENABLE}
# if using file
firebase.credential-file=${FIREBASE_CREDENTIAL}
# for CI/CD
firebase.credential-base64=${CREDENTIAL_BASE64}
9 changes: 9 additions & 0 deletions src/main/java/com/iemr/common/CommonApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,16 @@
*/
package com.iemr.common;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
Expand All @@ -36,6 +41,8 @@
import com.iemr.common.data.users.User;
import com.iemr.common.utils.IEMRApplBeans;

import java.io.IOException;

@SpringBootApplication
@EnableScheduling
public class CommonApplication extends SpringBootServletInitializer {
Expand Down Expand Up @@ -73,4 +80,6 @@ public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factor
return template;
}


}

Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.iemr.common.config.firebase;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;

@Configuration
public class FirebaseMessagingConfig {

@Value("${firebase.enabled:false}")
private boolean firebaseEnabled;

@Value("${firebase.credential-file:}")
private String firebaseCredentialFile;

@Value("${firebase.credential-base64:}")
private String firebaseCredentialBase64;

@Bean
public FirebaseMessaging firebaseMessaging() throws IOException {
if (!firebaseEnabled) {
throw new IllegalStateException("Firebase is disabled");
}

GoogleCredentials credentials;

if (!firebaseCredentialBase64.isBlank()) {
byte[] decoded = Base64.getDecoder().decode(firebaseCredentialBase64);
credentials = GoogleCredentials.fromStream(new ByteArrayInputStream(decoded));
} else if (!firebaseCredentialFile.isBlank()) {
credentials = GoogleCredentials.fromStream(
new ClassPathResource(firebaseCredentialFile).getInputStream()
);
} else {
throw new IllegalStateException("No Firebase credentials provided");
}

FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(credentials)
.build();

FirebaseApp firebaseApp = FirebaseApp.getApps().isEmpty()
? FirebaseApp.initializeApp(options)
: FirebaseApp.getInstance();

return FirebaseMessaging.getInstance(firebaseApp);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* AMRIT – Accessible Medical Records via Integrated Technology
* Integrated EHR (Electronic Health Records) Solution
*
* Copyright (C) "Piramal Swasthya Management and Research Institute"
*
* This file is part of AMRIT.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
package com.iemr.common.controller.beneficiaryConsent;

import com.iemr.common.data.beneficiaryConsent.BeneficiaryConsentRequest;
import com.iemr.common.service.beneficiaryOTPHandler.BeneficiaryOTPHandler;
import com.iemr.common.utils.mapper.InputMapper;
import com.iemr.common.utils.response.OutputResponse;
import io.lettuce.core.dynamic.annotation.Param;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.ws.rs.core.MediaType;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping(value = { "/beneficiaryConsent" },headers ="Authorization" )
@RestController
public class BeneficiaryConsentController {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add missing @RestController annotation.

The class is missing the @RestController annotation, which is required for Spring to recognize it as a REST controller and handle HTTP requests properly.

+@RestController
 public class BeneficiaryConsentController {
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public class BeneficiaryConsentController {
@RestController
public class BeneficiaryConsentController {
πŸ€– Prompt for AI Agents
In
src/main/java/com/iemr/common/controller/beneficiaryConsent/BeneficiaryConsentController.java
at line 20, the class lacks the @RestController annotation. Add the
@RestController annotation above the class declaration to ensure Spring
recognizes this class as a REST controller and properly handles HTTP requests.

final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

@Autowired
private BeneficiaryOTPHandler beneficiaryOTPHandler;

@Operation(summary = "Send Consent")
@RequestMapping(value = "/sendConsent", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization")
public String sendConsent(@Param(value = "{\"mobNo\":\"String\"}") @RequestBody String requestOBJ) {

OutputResponse response = new OutputResponse();

try {
BeneficiaryConsentRequest obj = InputMapper.gson().fromJson(requestOBJ, BeneficiaryConsentRequest.class);

String success = beneficiaryOTPHandler.sendOTP(obj); // method name unchanged if internal logic still uses 'OTP'
logger.info(success.toString());
response.setResponse(success);


} catch (Exception e) {
response.setError(500, "error : " + e);
}
return response.toString();
}

@Operation(summary = "Validate Consent")
@RequestMapping(value = "/validateConsent", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization")
public String validateConsent(@Param(value = "{\"mobNo\":\"String\",\"otp\":\"Integer\"}") @RequestBody String requestOBJ) {

OutputResponse response = new OutputResponse();

try {
BeneficiaryConsentRequest obj = InputMapper.gson().fromJson(requestOBJ, BeneficiaryConsentRequest.class);

JSONObject responseOBJ = beneficiaryOTPHandler.validateOTP(obj);
if (responseOBJ != null)
response.setResponse(responseOBJ.toString());
else
response.setError(500, "failure");

} catch (Exception e) {
logger.error("error in validating Consent : " + e);
response.setError(500, "error : " + e);
}
return response.toString();
}

@Operation(summary = "Resend Consent")
@RequestMapping(value = "/resendConsent", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization")
public String resendConsent(@Param(value = "{\"mobNo\":\"String\"}") @RequestBody String requestOBJ) {
logger.info(requestOBJ.toString());

Check notice

Code scanning / SonarCloud

Logging should not be vulnerable to injection attacks Low

Change this code to not log user-controlled data. See more on SonarQube Cloud

OutputResponse response = new OutputResponse();

try {
BeneficiaryConsentRequest obj = InputMapper.gson().fromJson(requestOBJ, BeneficiaryConsentRequest.class);

String success = beneficiaryOTPHandler.resendOTP(obj);
logger.info(success.toString());

if (success.contains("otp"))
response.setResponse(success);
else
response.setError(500, "failure");
Comment on lines +103 to +106
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix success condition logic in resendConsent method.

Same issue as in sendConsent - the success condition logic is incorrect.

-            if (success.contains("otp"))
+            if (success.equals("success"))
                 response.setResponse(success);
             else
                 response.setError(500, "failure");
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (success.contains("otp"))
response.setResponse(success);
else
response.setError(500, "failure");
if (success.equals("success"))
response.setResponse(success);
else
response.setError(500, "failure");
πŸ€– Prompt for AI Agents
In
src/main/java/com/iemr/common/controller/beneficiaryConsent/BeneficiaryConsentController.java
around lines 85 to 88, the success condition logic in the resendConsent method
is incorrect as it only checks if the success string contains "otp". Update the
condition to correctly reflect the success criteria used in the sendConsent
method, ensuring that the response is set to success only when the operation
truly succeeds; otherwise, set the error response appropriately.


} catch (Exception e) {
logger.error("error in re-sending Consent : " + e);
response.setError(500, "error : " + e);
}
return response.toString();
}


}


Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* AMRIT – Accessible Medical Records via Integrated Technology
* Integrated EHR (Electronic Health Records) Solution
*
* Copyright (C) "Piramal Swasthya Management and Research Institute"
*
* This file is part of AMRIT.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
/*
* AMRIT – Accessible Medical Records via Integrated Technology
*/
package com.iemr.common.controller.firebaseNotification;

import com.iemr.common.model.notification.NotificationMessage;
import com.iemr.common.model.notification.UserToken;
import com.iemr.common.service.firebaseNotification.FirebaseNotificationService;
import com.iemr.common.utils.exception.IEMRException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value= "/firebaseNotification",headers = "Authorization")
public class FirebaseNotificationController {
final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

@Autowired
FirebaseNotificationService firebaseNotificationService;

@RequestMapping(value = "sendNotification",method = RequestMethod.POST)
public String sendNotificationByToken(@RequestBody NotificationMessage notificationMessage){
return firebaseNotificationService.sendNotification(notificationMessage);
}
Comment on lines +44 to +47
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

πŸ› οΈ Refactor suggestion

Add error handling and input validation.

The controller lacks error handling and input validation, which could lead to runtime exceptions and poor user experience. Consider adding validation and proper error responses.

 @RequestMapping(value = "sendNotification",method = RequestMethod.POST)
-public String sendNotificationByToken(@RequestBody NotificationMessage notificationMessage){
+public ResponseEntity<String> sendNotificationByToken(@Valid @RequestBody NotificationMessage notificationMessage){
+    try {
+        if (notificationMessage == null) {
+            return ResponseEntity.badRequest().body("Notification message is required");
+        }
+        String result = firebaseNotificationService.sendNotification(notificationMessage);
+        return ResponseEntity.ok(result);
+    } catch (Exception e) {
+        logger.error("Error sending notification: ", e);
+        return ResponseEntity.internalServerError().body("Failed to send notification");
+    }
-    return firebaseNotificationService.sendNotification(notificationMessage);
 }
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@RequestMapping(value = "sendNotification",method = RequestMethod.POST)
public String sendNotificationByToken(@RequestBody NotificationMessage notificationMessage){
return firebaseNotificationService.sendNotification(notificationMessage);
}
@RequestMapping(value = "sendNotification", method = RequestMethod.POST)
public ResponseEntity<String> sendNotificationByToken(@Valid @RequestBody NotificationMessage notificationMessage) {
try {
if (notificationMessage == null) {
return ResponseEntity.badRequest().body("Notification message is required");
}
String result = firebaseNotificationService.sendNotification(notificationMessage);
return ResponseEntity.ok(result);
} catch (Exception e) {
logger.error("Error sending notification: ", e);
return ResponseEntity.internalServerError().body("Failed to send notification");
}
}
πŸ€– Prompt for AI Agents
In
src/main/java/com/iemr/common/controller/firebaseNotification/FirebaseNotificationController.java
around lines 18 to 21, the sendNotificationByToken method lacks input validation
and error handling. Add validation annotations to the NotificationMessage
parameter or manually validate its fields to ensure required data is present.
Wrap the service call in a try-catch block to handle potential exceptions and
return appropriate HTTP error responses with meaningful messages to improve
robustness and user experience.


@RequestMapping(value = "updateToken",method = RequestMethod.POST)
public String updateToken(@RequestBody UserToken userToken){
return firebaseNotificationService.updateToken(userToken);
}
Comment on lines +49 to +52
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

πŸ› οΈ Refactor suggestion

Add error handling and input validation for updateToken endpoint.

Similar to the sendNotification endpoint, this method lacks error handling and input validation. Consider returning proper HTTP status codes and handling potential exceptions.

 @RequestMapping(value = "updateToken",method = RequestMethod.POST)
-public String  updateToken(@RequestBody UserToken userToken){
+public ResponseEntity<String> updateToken(@Valid @RequestBody UserToken userToken){
+    try {
+        if (userToken == null || userToken.getUserId() == null || userToken.getToken() == null) {
+            return ResponseEntity.badRequest().body("User ID and token are required");
+        }
+        String result = firebaseNotificationService.updateToken(userToken);
+        return ResponseEntity.ok(result);
+    } catch (Exception e) {
+        logger.error("Error updating token: ", e);
+        return ResponseEntity.internalServerError().body("Failed to update token");
+    }
-    return firebaseNotificationService.updateToken(userToken);
 }
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@RequestMapping(value = "updateToken",method = RequestMethod.POST)
public String updateToken(@RequestBody UserToken userToken){
return firebaseNotificationService.updateToken(userToken);
}
@RequestMapping(value = "updateToken", method = RequestMethod.POST)
public ResponseEntity<String> updateToken(@Valid @RequestBody UserToken userToken) {
try {
if (userToken == null || userToken.getUserId() == null || userToken.getToken() == null) {
return ResponseEntity.badRequest().body("User ID and token are required");
}
String result = firebaseNotificationService.updateToken(userToken);
return ResponseEntity.ok(result);
} catch (Exception e) {
logger.error("Error updating token: ", e);
return ResponseEntity.internalServerError().body("Failed to update token");
}
}
πŸ€– Prompt for AI Agents
In
src/main/java/com/iemr/common/controller/firebaseNotification/FirebaseNotificationController.java
around lines 49 to 52, the updateToken method lacks error handling and input
validation. Add validation to check the userToken input for null or invalid
fields before processing. Wrap the service call in a try-catch block to handle
exceptions and return appropriate HTTP status codes, such as 400 for bad input
and 500 for server errors, using ResponseEntity to provide meaningful responses.

πŸ› οΈ Refactor suggestion

Add input validation and error handling for consistency.

Similar to the sendNotificationByToken method, this endpoint lacks input validation and error handling. Consider applying the same improvements for consistency.

 @RequestMapping(value = "updateToken",method = RequestMethod.POST)
-public String  updateToken(@RequestBody UserToken userToken){
+public ResponseEntity<String> updateToken(@Valid @RequestBody UserToken userToken){
+    try {
+        if (userToken == null) {
+            return ResponseEntity.badRequest().body("User token is required");
+        }
         String result = firebaseNotificationService.updateToken(userToken);
-        return firebaseNotificationService.updateToken(userToken);
+        return ResponseEntity.ok(result);
+    } catch (Exception e) {
+        logger.error("Error updating token: ", e);
+        return ResponseEntity.internalServerError().body("Failed to update token");
+    }
 }

Committable suggestion skipped: line range outside the PR's diff.

πŸ€– Prompt for AI Agents
In
src/main/java/com/iemr/common/controller/firebaseNotification/FirebaseNotificationController.java
around lines 49 to 52, the updateToken method lacks input validation and error
handling. Add validation to check if the userToken object and its required
fields are not null or empty before proceeding. Wrap the service call in a
try-catch block to handle potential exceptions and return appropriate error
responses or messages for consistency with the sendNotificationByToken method.


@RequestMapping(value = "getToken",method = RequestMethod.GET,headers = "Authorization")
public String getUserToken() throws IEMRException {

return firebaseNotificationService.getUserToken();
}
Comment on lines +54 to +58
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

πŸ› οΈ Refactor suggestion

Improve error handling for getUserToken endpoint.

The getUserToken method throws IEMRException but doesn't handle it properly at the controller level. Consider wrapping in try-catch and returning appropriate HTTP responses.

 @RequestMapping(value = "getToken",method = RequestMethod.GET,headers = "Authorization")
-public String  getUserToken() throws IEMRException {
-
-    return  firebaseNotificationService.getUserToken();
+public ResponseEntity<String> getUserToken() {
+    try {
+        String token = firebaseNotificationService.getUserToken();
+        if (token == null) {
+            return ResponseEntity.notFound().build();
+        }
+        return ResponseEntity.ok(token);
+    } catch (IEMRException e) {
+        logger.error("Error retrieving user token: ", e);
+        return ResponseEntity.internalServerError().body("Failed to retrieve token");
+    }
 }
πŸ€– Prompt for AI Agents
In
src/main/java/com/iemr/common/controller/firebaseNotification/FirebaseNotificationController.java
around lines 54 to 58, the getUserToken method declares throwing IEMRException
but does not handle it within the controller. Modify the method to wrap the call
to firebaseNotificationService.getUserToken() in a try-catch block, catch
IEMRException, and return an appropriate HTTP response (e.g., ResponseEntity
with error status and message) instead of letting the exception propagate.



}
9 changes: 7 additions & 2 deletions src/main/java/com/iemr/common/controller/otp/OTPGateway.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,16 @@
@Operation(summary = "Send OTP")
@RequestMapping(value = "/sendOTP", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization")
public String sendOTP(@Param(value = "{\"mobNo\":\"String\"}") @RequestBody String requestOBJ) {
logger.info(requestOBJ.toString());

Check notice

Code scanning / SonarCloud

Logging should not be vulnerable to injection attacks Low

Change this code to not log user-controlled data. See more on SonarQube Cloud

OutputResponse response = new OutputResponse();

try {
OTPRequestParsor obj = InputMapper.gson().fromJson(requestOBJ, OTPRequestParsor.class);

String success = otpHandler.sendOTP(obj);
if (success.equalsIgnoreCase("success"))
logger.info(success.toString());
if (success.contains("otp"))
response.setResponse(success);
else
response.setError(5000, "failure");
Expand Down Expand Up @@ -98,14 +100,17 @@
@Operation(summary = "Resend OTP")
@RequestMapping(value = "/resendOTP", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, headers = "Authorization")
public String resendOTP(@Param(value = "{\"mobNo\":\"String\"}") @RequestBody String requestOBJ) {
logger.info(requestOBJ.toString());

Check notice

Code scanning / SonarCloud

Logging should not be vulnerable to injection attacks Low

Change this code to not log user-controlled data. See more on SonarQube Cloud

OutputResponse response = new OutputResponse();

try {
OTPRequestParsor obj = InputMapper.gson().fromJson(requestOBJ, OTPRequestParsor.class);

String success = otpHandler.resendOTP(obj);
if (success.equalsIgnoreCase("success"))
logger.info(success.toString());

if (success.contains("otp"))
response.setResponse(success);
else
response.setError(5000, "failure");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -567,7 +567,7 @@ public String getLoginResponse(HttpServletRequest request) {
}

// Extract user ID from the JWT token
String userId = jwtUtil.getUserIdFromToken(jwtToken);
String userId = jwtUtil.extractUserId(jwtToken);

// Get user details and prepare response
User user = iemrAdminUserServiceImpl.getUserById(Long.parseLong(userId));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.iemr.common.data.beneficiaryConsent;

import lombok.Data;

@Data
public class BeneficiaryConsentRequest {
private String mobNo;
private int otp;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Change OTP field type to String to preserve leading zeros.

Using int for OTP can cause issues if the OTP starts with zero, as leading zeros will be lost. OTPs should be treated as strings to preserve their exact format.

-    private int otp;
+    private String otp;
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private int otp;
- private int otp;
+ private String otp;
πŸ€– Prompt for AI Agents
In
src/main/java/com/iemr/common/data/beneficiaryConsent/BeneficiaryConsentRequest.java
at line 8, change the type of the otp field from int to String to ensure leading
zeros are preserved and the OTP format remains accurate.

private String userName;
private String designation;

}
Loading