-
Notifications
You must be signed in to change notification settings - Fork 25
CORS Configuration for AMRIT 104 API Services #58
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
WalkthroughThis change introduces a global CORS configuration for the application by adding a centralized Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant SpringApp
participant CorsConfig
participant Controller
Client->>SpringApp: HTTP request (any method)
alt OPTIONS request
SpringApp->>CorsConfig: Apply global CORS settings
SpringApp->>Client: Respond with CORS headers
else Other requests
SpringApp->>CorsConfig: Apply global CORS settings
SpringApp->>Controller: Route to endpoint
Controller-->>SpringApp: Response
SpringApp->>Client: Respond with data and CORS headers
end
Possibly related issues
Suggested reviewers
Poem
β¨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. πͺ§ TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 10
β»οΈ Duplicate comments (2)
src/main/java/com/iemr/helpline104/controller/drugGroup/DrugGroupController.java (2)
77-80: Recommend adding explicitconsumes = MediaType.APPLICATION_JSON_VALUEandproduces = MediaType.APPLICATION_JSON_VALUEto this@PostMappingas well for consistent API contracts.
119-123: As above, please addconsumes/producesattributes to this@PostMappingto standardize response and request handling.
π§Ή Nitpick comments (6)
src/main/environment/104_example.properties (1)
25-27: Wildcard origin (http://localhost:*) is extremely permissiveUsing
*for every port onlocalhostis convenient for dev, but remember to:
- Replace with explicit origins before committing to shared or prod examples.
- Mention in README how to list multiple origins (comma-separated).
Consider
http://localhost:3000,http://localhost:4200instead.src/main/java/com/iemr/helpline104/controller/covidMaster/CovidMasterController.java (1)
46-49: Cosmetic change β tighten the annotation wordingTwo consecutive spaces in the summary string (
"Master data for COVID patient") look accidental and will render oddly in Swagger UI.-@Operation(summary = "Master data for COVID patient") +@Operation(summary = "Master data for COVID patient")src/main/java/com/iemr/helpline104/controller/foodSafetyComplaint/FoodSafetyComplaintController.java (1)
67-69: Remove commented-out logging instead of keeping stale codeThe split, commented log statement is no longer useful and generates noise in diffs.
-// logger.info("saveFoodComplaintDetails request " + -// t_foodSafetyCopmlaint.toString());src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java (1)
137-143: AddSameSiteattribute when clearinguserIdcookieThe static-analysis hint is valid: the cleared cookie is re-set without a
SameSiteflag, weakening CSRF protection.- cookie.setSecure(true); - cookie.setMaxAge(0); // Invalidate the cookie - response.addCookie(cookie); + cookie.setSecure(true); + cookie.setMaxAge(0); // invalidate + response.addCookie(cookie); + // Explicit SameSite attribute (Servlet <6 workaround) + response.addHeader("Set-Cookie", + "userId=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0");This single header addition hardens the endpoint without changing behaviour.
π§° Tools
πͺ ast-grep (0.38.1)
[warning] 142-142: The application does not appear to verify inbound requests which can lead to a Cross-site request forgery (CSRF) vulnerability. If the application uses cookie-based authentication, an attacker can trick users into sending authenticated HTTP requests without their knowledge from any arbitrary domain they visit. To prevent this vulnerability start by identifying if the framework or library leveraged has built-in features or offers plugins for CSRF protection. CSRF tokens should be unique and securely random. The
Synchronizer TokenorDouble Submit Cookiepatterns with defense-in-depth mechanisms such as thesameSitecookie flag can help prevent CSRF. For more information, see: [Cross-site request forgery prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Req\ uest_Forgery_Prevention_Cheat_Sheet.html).
Context: response.addCookie(cookie);
Note: [CWE-352] Cross-Site Request Forgery (CSRF). [REFERENCES]
- https://stackoverflow.com/questions/42717210/samesite-cookie-in-java-application(cookie-missing-samesite-java)
src/main/java/com/iemr/helpline104/controller/drugGroup/DrugGroupController.java (1)
128-129: Program to interface
Use theList<DrugStrength>interface rather than the concreteArrayList<DrugStrength>.- ArrayList<DrugStrength> drugStrength = drugGroupService.getDrugStrength(...); + List<DrugStrength> drugStrength = drugGroupService.getDrugStrength(...);src/main/java/com/iemr/helpline104/controller/secondaryCrmReports/SecondaryCRMReports.java (1)
486-488: Method name mismatch: endpoint path vs method name.
The@PostMappingvalue is/getPDSummaryReportByDatebut the method is namedgetPDSummaryReport. Rename it to match the path for clarity and consistency:- public ResponseEntity<Object> getPDSummaryReport( + public ResponseEntity<Object> getPDSummaryReportByDate(
π Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
π Files selected for processing (34)
src/main/environment/104_ci.properties(1 hunks)src/main/environment/104_example.properties(1 hunks)src/main/java/com/iemr/helpline104/config/CorsConfig.java(1 hunks)src/main/java/com/iemr/helpline104/controller/IMRMMR/IMRMMRController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/balVivha/BalVivahController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/beneficiarycall/BeneficiaryCallController.java(1 hunks)src/main/java/com/iemr/helpline104/controller/bloodComponent/BloodComponentController.java(2 hunks)src/main/java/com/iemr/helpline104/controller/bloodRequest/BloodRequestController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/callqamapping/CallQAMappingController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/casesheet/Helpline104BeneficiaryHistoryController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/cdss/ClinicalDecisionSupportController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/covidMaster/CovidMasterController.java(2 hunks)src/main/java/com/iemr/helpline104/controller/directory/DirectoryServicesController.java(1 hunks)src/main/java/com/iemr/helpline104/controller/disease/DiseaseController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/diseaseScreening/DiseaseScreeningController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/drugGroup/DrugGroupController.java(6 hunks)src/main/java/com/iemr/helpline104/controller/epidemicOutbreak/EpidemicOutbreakController.java(1 hunks)src/main/java/com/iemr/helpline104/controller/feedback/FeedbackController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/feedbackType/FeedbackTypeController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/foodSafetyComplaint/FoodSafetyComplaintController.java(1 hunks)src/main/java/com/iemr/helpline104/controller/healthCareWorkerType/HealthCareWorkerTypeController.java(1 hunks)src/main/java/com/iemr/helpline104/controller/hihl/HIHLController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/location/CountryCityController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/location/LocationController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/organDonation/OrganDonationController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/prescription/PrescriptionController.java(2 hunks)src/main/java/com/iemr/helpline104/controller/scheme/SchemeController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/secondaryCrmReports/SecondaryCRMReports.java(18 hunks)src/main/java/com/iemr/helpline104/controller/sioHistory/ServiceImprovementOfficerController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/snomedct/SnomedController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/users/IEMRAdminController.java(0 hunks)src/main/java/com/iemr/helpline104/controller/version/VersionController.java(1 hunks)src/main/java/com/iemr/helpline104/service/CTI/CTIService.java(1 hunks)src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java(3 hunks)
π€ Files with no reviewable changes (18)
- src/main/java/com/iemr/helpline104/controller/feedbackType/FeedbackTypeController.java
- src/main/java/com/iemr/helpline104/controller/sioHistory/ServiceImprovementOfficerController.java
- src/main/java/com/iemr/helpline104/controller/users/IEMRAdminController.java
- src/main/java/com/iemr/helpline104/controller/hihl/HIHLController.java
- src/main/java/com/iemr/helpline104/controller/diseaseScreening/DiseaseScreeningController.java
- src/main/java/com/iemr/helpline104/controller/location/CountryCityController.java
- src/main/java/com/iemr/helpline104/controller/callqamapping/CallQAMappingController.java
- src/main/java/com/iemr/helpline104/controller/snomedct/SnomedController.java
- src/main/java/com/iemr/helpline104/controller/location/LocationController.java
- src/main/java/com/iemr/helpline104/controller/cdss/ClinicalDecisionSupportController.java
- src/main/java/com/iemr/helpline104/controller/feedback/FeedbackController.java
- src/main/java/com/iemr/helpline104/controller/balVivha/BalVivahController.java
- src/main/java/com/iemr/helpline104/controller/casesheet/Helpline104BeneficiaryHistoryController.java
- src/main/java/com/iemr/helpline104/controller/scheme/SchemeController.java
- src/main/java/com/iemr/helpline104/controller/organDonation/OrganDonationController.java
- src/main/java/com/iemr/helpline104/controller/disease/DiseaseController.java
- src/main/java/com/iemr/helpline104/controller/IMRMMR/IMRMMRController.java
- src/main/java/com/iemr/helpline104/controller/bloodRequest/BloodRequestController.java
π§° Additional context used
𧬠Code Graph Analysis (1)
src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java (1)
src/main/java/com/iemr/helpline104/utils/UserAgentContext.java (1)
UserAgentContext(3-18)
πͺ ast-grep (0.38.1)
src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java
[warning] 142-142: The application does not appear to verify inbound requests which can lead to a Cross-site request forgery (CSRF) vulnerability. If the application uses cookie-based authentication, an attacker can trick users into sending authenticated HTTP requests without their knowledge from any arbitrary domain they visit. To prevent this vulnerability start by identifying if the framework or library leveraged has built-in features or offers plugins for CSRF protection. CSRF tokens should be unique and securely random. The Synchronizer Token or Double Submit Cookie patterns with defense-in-depth mechanisms such as the sameSite cookie flag can help prevent CSRF. For more information, see: [Cross-site request forgery prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Req\ uest_Forgery_Prevention_Cheat_Sheet.html).
Context: response.addCookie(cookie);
Note: [CWE-352] Cross-Site Request Forgery (CSRF). [REFERENCES]
- https://stackoverflow.com/questions/42717210/samesite-cookie-in-java-application
(cookie-missing-samesite-java)
β° Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: Analyze (java)
π Additional comments (12)
src/main/environment/104_ci.properties (1)
29-31: Validate placeholder & value format forcors.allowed-originsAll other placeholders follow the
@env.*@convention, but this one is@CORS_ALLOWED_ORIGINS@.
Confirm that your deployment pipeline replaces this token; otherwise the value will literally be@CORS_ALLOWED_ORIGINS@at runtime and CORS will fail.Also document the expected delimiter for multiple origins (comma-separated? space?).
src/main/java/com/iemr/helpline104/controller/healthCareWorkerType/HealthCareWorkerTypeController.java (1)
30-34: Ensure global CORS config permits POST + Authorization for this endpoint
@CrossOriginwas removed, so/beneficiary/get/healthCareWorkerTypesnow relies solely onCorsConfig.
Double-check that:β’
POSTis in the allowed methods list
β’Authorizationis in allowed and exposed headers
β’allowed-originsproperty covers expected clientsOtherwise existing consumers will see 403 from pre-flight.
src/main/java/com/iemr/helpline104/controller/version/VersionController.java (1)
31-34: Verify CORS accessibility for/versionendpointSimilar to other controllers,
@CrossOriginis gone. If this endpoint is polled by web dashboards, ensureCorsConfigenablesGET /versionfor those origins.src/main/java/com/iemr/helpline104/controller/epidemicOutbreak/EpidemicOutbreakController.java (1)
30-35: CORS annotation successfully removed β verify allowed-origin listThe only change here is the removal of the
@CrossOriginimport (and the related annotations elsewhere).
Given that CORS is now handled globally, this is correct.
Just double-check that the newcors.allowed-originsproperty contains every domain previously whitelisted on this controller, otherwise you may introduce unexpected 4xx responses in production.src/main/java/com/iemr/helpline104/controller/covidMaster/CovidMasterController.java (1)
58-63: Global CORS: ensure OPTIONS isnβt blocked by headers filterWith the
@CrossOriginannotation gone, remember that pre-flightOPTIONScalls will no longer include theAuthorizationheader.
Because this mapping is declared withheaders = "Authorization", Spring will not match it for anOPTIONSrequest, so only the global CORS handler must answer.
If you observe 403s from API gateways, consider dropping theheadersattribute from the mapping.src/main/java/com/iemr/helpline104/controller/bloodComponent/BloodComponentController.java (2)
51-57: LGTM β Signature unchanged, only docstring trimmedThe
@Parameterdescription update is non-functional and safe.
70-76: Same comment as above aboutheaders = "Authorization"If CORS pre-flight failures surface, consider whether this header constraint is still required.
src/main/java/com/iemr/helpline104/controller/prescription/PrescriptionController.java (1)
111-113: No behavioural change β only wrapping lineNothing further to add.
src/main/java/com/iemr/helpline104/config/CorsConfig.java (1)
12-22:Details
β Incorrect review comment
Avoid NPE when
cors.allowed-originsis missing & fall back gracefully
allowedOriginsis injected without a default; if the property is absent or left blank,split(",")will throw aNullPointerException. Provide a default and guard against blank values before splitting.- @Value("${cors.allowed-origins}") - private String allowedOrigins; + @Value("${cors.allowed-origins:}") // empty-string default + private String allowedOrigins; β¦ - registry.addMapping("/**") - .allowedOriginPatterns( - Arrays.stream(allowedOrigins.split(",")) - .map(String::trim) - .toArray(String[]::new)) + String[] originArray = allowedOrigins == null || allowedOrigins.isBlank() + ? new String[]{"*"} // sensible fallback + : Arrays.stream(allowedOrigins.split(",")) + .map(String::trim) + .toArray(String[]::new); + + registry.addMapping("/**") + .allowedOriginPatterns(originArray)Also note that
allowCredentials(true)cannot be combined with wildcard origins in some browsersβdouble-check your runtime configuration.
NPE risk is unlikely; missing property fails startup, not null injection
Springβs @value("${cors.allowed-origins}") will cause the application to fail on startup if the property is absent, and if the property is present but empty you get an empty string (not null), so
allowedOrigins.split(",")wonβt throw an NPE.β’ If you do want to support βno settingβ at runtime, add a default in the annotation or via configuration rather than guarding for null:
@Value("${cors.allowed-origins:*}") // fall back to wildcard if unset private String allowedOrigins;β’ Alternatively, consider using @ConfigurationProperties with validation to enforce a non-blank list.
Also, be aware that some browsers will reject
allowCredentials(true)when paired with wildcard originsβdouble-check your CORS policy if you use"*"here.Likely an incorrect or invalid review comment.
src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java (1)
36-40: OPTIONS short-circuit is spot-onPre-flight requests now skip JWT validation, unblocking CORS. Nice addition.
src/main/java/com/iemr/helpline104/controller/directory/DirectoryServicesController.java (1)
30-31: Removal of unused@CrossOriginimport looks cleanThe stray import was safely eliminated after centralising CORS.
src/main/java/com/iemr/helpline104/controller/secondaryCrmReports/SecondaryCRMReports.java (1)
79-79: Also applies to: 106-106, 133-133, 160-160, 187-187, 214-214, 242-242, 268-268, 296-296, 323-323, 351-351, 379-379, 405-405, 435-435, 460-460
| ResponseEntity<String> res = restTemplate.getForEntity(url, String.class); | ||
|
|
||
| return new Gson().toJson(res.getBody()); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Gson().toJson(res.getBody()) double-encodes JSON
res.getBody() is already a String; wrapping it in toJson turns it into a JSON string containing JSON (adds extra quotes / escapes). Return the body as-is or deserialize and re-serialize properly.
-return new Gson().toJson(res.getBody());
+return res.getBody();π 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.
| ResponseEntity<String> res = restTemplate.getForEntity(url, String.class); | |
| return new Gson().toJson(res.getBody()); | |
| ResponseEntity<String> res = restTemplate.getForEntity(url, String.class); | |
| return res.getBody(); |
π€ Prompt for AI Agents
In src/main/java/com/iemr/helpline104/service/CTI/CTIService.java around lines
58 to 60, the code calls Gson().toJson on res.getBody(), which is already a JSON
string, causing double encoding and extra quotes. To fix this, return
res.getBody() directly without wrapping it in Gson().toJson, or if
transformation is needed, deserialize the string into an object and then
serialize it back properly.
| private String domain = "http://10.201.13.17"; | ||
| private String resFormat = "1"; | ||
| private String ip = "10.208.94.134"; | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π οΈ Refactor suggestion
Externalize domain/IP/format β avoid hard-coding connection details
domain, resFormat, and ip are hard-coded. This prevents environment-specific configuration and makes testing harder.
- private String domain = "http://10.201.13.17";
- private String resFormat = "1";
- private String ip = "10.208.94.134";
+@Value("${cti.domain}")
+private String domain;
+
+@Value("${cti.res-format:1}")
+private String resFormat;
+
+@Value("${cti.ip}")
+private String ip;Add the three keys to the relevant *.properties files and/or Config Server.
π€ Prompt for AI Agents
In src/main/java/com/iemr/helpline104/service/CTI/CTIService.java around lines
43 to 46, the domain, resFormat, and ip variables are hard-coded, which limits
flexibility and environment-specific configuration. To fix this, remove the
hard-coded values and instead load these properties from external configuration
files such as application.properties or from a Config Server. Add corresponding
keys for domain, resFormat, and ip in the properties files and update the code
to read these values using a configuration management approach like Spring's
@Value annotation or a properties loader.
| String url = domain + "/apps/appsHandler.php?transaction_id=" + transaction_id + "&agent_id=" + agent_id | ||
| + "&ip=" + ip + "&resFormat=" + resFormat; | ||
|
|
||
| ResponseEntity<String> res = restTemplate.getForEntity(url, String.class); | ||
|
|
||
| return new Gson().toJson(res.getBody()); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π οΈ Refactor suggestion
Build URLs safely and reuse common code
- Manual string concatenation risks injection and misses URI-encoding for
agent_id. - The same logic exists in all three methods β violates DRY.
-String url = domain + "/apps/appsHandler.php?transaction_id=" + transaction_id +
- "&agent_id=" + agent_id + "&ip=" + ip + "&resFormat=" + resFormat;
+String url = UriComponentsBuilder.fromHttpUrl(domain + "/apps/appsHandler.php")
+ .queryParam("transaction_id", transaction_id)
+ .queryParam("agent_id", agent_id)
+ .queryParam("ip", ip)
+ .queryParam("resFormat", resFormat)
+ .build()
+ .encode()
+ .toUriString();Extract this construction into a private helper so loginAgent, logoutAgent, and transferCall call the same utility.
π 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.
| String url = domain + "/apps/appsHandler.php?transaction_id=" + transaction_id + "&agent_id=" + agent_id | |
| + "&ip=" + ip + "&resFormat=" + resFormat; | |
| ResponseEntity<String> res = restTemplate.getForEntity(url, String.class); | |
| return new Gson().toJson(res.getBody()); | |
| String url = UriComponentsBuilder.fromHttpUrl(domain + "/apps/appsHandler.php") | |
| .queryParam("transaction_id", transaction_id) | |
| .queryParam("agent_id", agent_id) | |
| .queryParam("ip", ip) | |
| .queryParam("resFormat", resFormat) | |
| .build() | |
| .encode() | |
| .toUriString(); | |
| ResponseEntity<String> res = restTemplate.getForEntity(url, String.class); | |
| return new Gson().toJson(res.getBody()); |
π€ Prompt for AI Agents
In src/main/java/com/iemr/helpline104/service/CTI/CTIService.java around lines
55 to 60, the URL is built using manual string concatenation which risks
injection and lacks URI encoding for parameters like agent_id. To fix this,
create a private helper method that safely constructs the URL using proper URI
encoding for all parameters. Then refactor the loginAgent, logoutAgent, and
transferCall methods to call this helper, eliminating duplicated URL
construction code and adhering to DRY principles.
|
|
||
| final String transaction_id = "CTI_TRANSFER_AGENT"; | ||
|
|
||
| InetAddress inetAddress = InetAddress.getLocalHost(); | ||
| //String ip = inetAddress.getHostAddress(); | ||
| // String ip = inetAddress.getHostAddress(); | ||
|
|
||
| RestTemplate restTemplate = new RestTemplate(); | ||
| String url=domain+"/apps/appsHandler.php?transaction_id="+transaction_id+"&transfer_ from="+transfer_from+"&transfer_to="+transfer_to+"&ip="+ip; | ||
|
|
||
| ResponseEntity<String> res= restTemplate.getForEntity(url, String.class); | ||
|
|
||
| String url = domain + "/apps/appsHandler.php?transaction_id=" + transaction_id + "&transfer_ from=" | ||
| + transfer_from + "&transfer_to=" + transfer_to + "&ip=" + ip; | ||
|
|
||
| ResponseEntity<String> res = restTemplate.getForEntity(url, String.class); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Typo in query parameter β space after underscore breaks request
"&transfer_ from=" contains a space, producing an invalid query param name and 400 responses.
-String url = domain + "/apps/appsHandler.php?transaction_id=" + transaction_id + "&transfer_ from="
+String url = domain + "/apps/appsHandler.php?transaction_id=" + transaction_id + "&transfer_from="π 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.
| final String transaction_id = "CTI_TRANSFER_AGENT"; | |
| InetAddress inetAddress = InetAddress.getLocalHost(); | |
| //String ip = inetAddress.getHostAddress(); | |
| // String ip = inetAddress.getHostAddress(); | |
| RestTemplate restTemplate = new RestTemplate(); | |
| String url=domain+"/apps/appsHandler.php?transaction_id="+transaction_id+"&transfer_ from="+transfer_from+"&transfer_to="+transfer_to+"&ip="+ip; | |
| ResponseEntity<String> res= restTemplate.getForEntity(url, String.class); | |
| String url = domain + "/apps/appsHandler.php?transaction_id=" + transaction_id + "&transfer_ from=" | |
| + transfer_from + "&transfer_to=" + transfer_to + "&ip=" + ip; | |
| ResponseEntity<String> res = restTemplate.getForEntity(url, String.class); | |
| final String transaction_id = "CTI_TRANSFER_AGENT"; | |
| InetAddress inetAddress = InetAddress.getLocalHost(); | |
| // String ip = inetAddress.getHostAddress(); | |
| RestTemplate restTemplate = new RestTemplate(); | |
| String url = domain + "/apps/appsHandler.php?transaction_id=" + transaction_id + "&transfer_from=" | |
| + transfer_from + "&transfer_to=" + transfer_to + "&ip=" + ip; | |
| ResponseEntity<String> res = restTemplate.getForEntity(url, String.class); |
π€ Prompt for AI Agents
In src/main/java/com/iemr/helpline104/service/CTI/CTIService.java between lines
80 and 90, the query parameter name "transfer_ from" contains an unintended
space after the underscore, causing an invalid request and 400 errors. Remove
the space so the parameter reads "transfer_from" to correctly format the URL
query string.
| String jwtFromCookie = getJwtTokenFromCookies(request); | ||
| String jwtFromHeader = request.getHeader("JwtToken"); | ||
| String authHeader = request.getHeader("Authorization"); | ||
|
|
||
| if (jwtFromCookie != null) { | ||
| logger.info("Validating JWT token from cookie"); | ||
| if (jwtAuthenticationUtil.validateUserIdAndJwtToken(jwtFromCookie)) { | ||
| AuthorizationHeaderRequestWrapper authorizationHeaderRequestWrapper = new AuthorizationHeaderRequestWrapper( | ||
| request, ""); | ||
| filterChain.doFilter(authorizationHeaderRequestWrapper, servletResponse); | ||
| return; | ||
| } | ||
| } else if (jwtFromHeader != null) { | ||
| logger.info("Validating JWT token from header"); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Header-name mismatch breaks JWT validation for non-cookie flows
jwtFromHeader is read with "JwtToken" (mixed case) while elsewhere you log "Jwttoken". Because header names are case-insensitive but your clients appear to use exactly Jwttoken, this inconsistency is easy to miss and causes silent auth failures.
- String jwtFromCookie = getJwtTokenFromCookies(request);
- String jwtFromHeader = request.getHeader("JwtToken");
+ String jwtFromCookie = getJwtTokenFromCookies(request);
+ // Use the same canonical header everywhere
+ String jwtFromHeader = request.getHeader("Jwttoken");Consider extracting the header name into a constant to avoid future drift.
π 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.
| String jwtFromCookie = getJwtTokenFromCookies(request); | |
| String jwtFromHeader = request.getHeader("JwtToken"); | |
| String authHeader = request.getHeader("Authorization"); | |
| if (jwtFromCookie != null) { | |
| logger.info("Validating JWT token from cookie"); | |
| if (jwtAuthenticationUtil.validateUserIdAndJwtToken(jwtFromCookie)) { | |
| AuthorizationHeaderRequestWrapper authorizationHeaderRequestWrapper = new AuthorizationHeaderRequestWrapper( | |
| request, ""); | |
| filterChain.doFilter(authorizationHeaderRequestWrapper, servletResponse); | |
| return; | |
| } | |
| } else if (jwtFromHeader != null) { | |
| logger.info("Validating JWT token from header"); | |
| String jwtFromCookie = getJwtTokenFromCookies(request); | |
| // Use the same canonical header everywhere | |
| String jwtFromHeader = request.getHeader("Jwttoken"); | |
| String authHeader = request.getHeader("Authorization"); | |
| if (jwtFromCookie != null) { | |
| logger.info("Validating JWT token from cookie"); | |
| if (jwtAuthenticationUtil.validateUserIdAndJwtToken(jwtFromCookie)) { | |
| AuthorizationHeaderRequestWrapper authorizationHeaderRequestWrapper = new AuthorizationHeaderRequestWrapper( | |
| request, ""); | |
| filterChain.doFilter(authorizationHeaderRequestWrapper, servletResponse); | |
| return; | |
| } | |
| } else if (jwtFromHeader != null) { | |
| logger.info("Validating JWT token from header"); |
π€ Prompt for AI Agents
In src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java
around lines 75 to 88, the header name for retrieving the JWT token is
inconsistently cased as "JwtToken" while clients use "Jwttoken". This mismatch
causes silent authentication failures. To fix this, define a constant for the
JWT header name with the exact casing "Jwttoken" and use this constant
everywhere in the code to read the header, ensuring consistent and correct
header access.
| @PostMapping(value = "update/beneficiaryCallID", headers = "Authorization") | ||
| public String updateBeneficiaryIDInCall( | ||
| @Parameter(description = "{\"callID\":\"integer\", \"beneficiaryRegID\":\"long\"}") @RequestBody String beneficiaryCall) { | ||
| OutputResponse output = new OutputResponse(); | ||
| Integer startedCall = null; | ||
| try { | ||
| BeneficiaryCall beneficiarycall = inputMapper.gson().fromJson(beneficiaryCall, BeneficiaryCall.class); | ||
| @Parameter(description = "{\"callID\":\"integer\", \"beneficiaryRegID\":\"long\"}") @RequestBody String beneficiaryCall) { | ||
|
|
||
| OutputResponse output = new OutputResponse(); | ||
| Integer startedCall = null; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Missing leading slash breaks endpoint mapping
Both paths lose the leading /, producing URLs like
/beneficiaryupdate/beneficiaryCallID instead of /beneficiary/update/β¦.
- @PostMapping(value = "update/beneficiaryCallID", headers = "Authorization")
+ @PostMapping(value = "/update/beneficiaryCallID", headers = "Authorization")Do the same for set/callHistory further below:
- @PostMapping(value = "set/callHistory", produces = MediaType.APPLICATION_JSON, headers = "Authorization")
+ @PostMapping(value = "/set/callHistory", produces = MediaType.APPLICATION_JSON, headers = "Authorization")Without this fix, clients will receive 404s.
π 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.
| @PostMapping(value = "update/beneficiaryCallID", headers = "Authorization") | |
| public String updateBeneficiaryIDInCall( | |
| @Parameter(description = "{\"callID\":\"integer\", \"beneficiaryRegID\":\"long\"}") @RequestBody String beneficiaryCall) { | |
| OutputResponse output = new OutputResponse(); | |
| Integer startedCall = null; | |
| try { | |
| BeneficiaryCall beneficiarycall = inputMapper.gson().fromJson(beneficiaryCall, BeneficiaryCall.class); | |
| @Parameter(description = "{\"callID\":\"integer\", \"beneficiaryRegID\":\"long\"}") @RequestBody String beneficiaryCall) { | |
| OutputResponse output = new OutputResponse(); | |
| Integer startedCall = null; | |
| @PostMapping(value = "/update/beneficiaryCallID", headers = "Authorization") | |
| public String updateBeneficiaryIDInCall( | |
| @Parameter(description = "{\"callID\":\"integer\", \"beneficiaryRegID\":\"long\"}") @RequestBody String beneficiaryCall) { | |
| OutputResponse output = new OutputResponse(); | |
| Integer startedCall = null; |
π€ Prompt for AI Agents
In
src/main/java/com/iemr/helpline104/controller/beneficiarycall/BeneficiaryCallController.java
around lines 88 to 93, the @PostMapping path "update/beneficiaryCallID" is
missing a leading slash, causing incorrect endpoint URLs and resulting in 404
errors. Add a leading slash to the path, changing it to
"/update/beneficiaryCallID". Also, apply the same fix to the "set/callHistory"
mapping further down by adding a leading slash to ensure correct URL mapping.
| @Operation(summary = "Fetch drug name list") | ||
| @PostMapping(value = "/getDrugDetailList", headers = "Authorization") | ||
| public String getDrugNameList( | ||
| @Parameter(description = "{\"providerServiceMapID\":\"integer\"}") @RequestBody String request) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π οΈ Refactor suggestion
Inconsistent naming: path vs. method
The endpoint path /getDrugDetailList and method name getDrugNameList are misaligned. Rename one to unify naming conventions and prevent confusion.
π€ Prompt for AI Agents
In
src/main/java/com/iemr/helpline104/controller/drugGroup/DrugGroupController.java
around lines 140 to 143, the method name getDrugNameList does not match the
endpoint path /getDrugDetailList, causing inconsistency. Rename either the
method to getDrugDetailList or the endpoint path to /getDrugNameList so that
both names align and clearly represent the same functionality.
| @Operation(summary = "Fetch drug frequency details") | ||
| @PostMapping(value = "/get/drugFrequency", headers = "Authorization") | ||
| public String getDrugFrequency() { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π οΈ Refactor suggestion
Use GET for idempotent fetch
getDrugFrequency() does not consume a request bodyβconsider switching to @GetMapping("/get/drugFrequency") (and removing the headers restriction) to better reflect REST semantics.
π€ Prompt for AI Agents
In
src/main/java/com/iemr/helpline104/controller/drugGroup/DrugGroupController.java
around lines 102 to 104, change the annotation from @PostMapping to @GetMapping
for the getDrugFrequency() method, remove the headers="Authorization"
restriction, and update the mapping to @GetMapping("/get/drugFrequency") to
correctly use GET for an idempotent fetch operation without requiring a request
body.
| @Operation(summary = "Fetch drug groups") | ||
| @PostMapping(value = "/get/drugGroups", headers = "Authorization") | ||
| public String getDrugGroups(@Parameter(description = "{\"serviceProviderID\":\"integer\"}") @RequestBody String request) { | ||
| public String getDrugGroups( | ||
| @Parameter(description = "{\"serviceProviderID\":\"integer\"}") @RequestBody String request) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π‘ Verification agent
π§© Analysis chain
Centralize CORS & specify media types
Removed controller-level @CrossOrigin; ensure your global CorsConfig bean covers /beneficiary/** and properly handles OPTIONS preflight. For better API clarity, add explicit consumes and produces to the @PostMapping.
As a follow-up, verify preflight handling with:
π Script executed:
#!/bin/bash
# Verify CORS preflight on getDrugGroups endpoint
curl -X OPTIONS http://localhost:8080/beneficiary/get/drugGroups \
-H "Origin: http://example.com" \
-H "Access-Control-Request-Method: POST" -ILength of output: 771
π Script executed:
#!/bin/bash
# Display class-level annotations and mappings in DrugGroupController
sed -n '1,200p' src/main/java/com/iemr/helpline104/controller/drugGroup/DrugGroupController.java
echo "---- @RequestMapping occurrences ----"
rg -n "@RequestMapping" src/main/java/com/iemr/helpline104/controller/drugGroup/DrugGroupController.java || true
echo "---- Global CORS config classes ----"
rg -n "class CorsConfig" -n src
echo "---- CORS registry patterns ----"
# If a CorsConfig exists, inspect its addMapping lines
rg -n "addMapping" -n src/main/java/com/iemr/helpline104/**/CorsConfig.java || trueLength of output: 6620
Add explicit consumes/produces to your endpoint; global CORS is already covering /beneficiary/**
Our global CorsConfig registers /** (including /beneficiary/**), so you can safely remove any controller-level @CrossOrigin. To improve API clarity and ensure correct content negotiation, please update your @PostMapping annotations to declare the media types:
β’ File: src/main/java/com/iemr/helpline104/controller/drugGroup/DrugGroupController.java
Update the mapping on line 56 (and similarly for other endpoints):
- @PostMapping(value = "/get/drugGroups", headers = "Authorization")
+ @PostMapping(
+ value = "/get/drugGroups",
+ consumes = MediaType.APPLICATION_JSON_VALUE,
+ produces = MediaType.APPLICATION_JSON_VALUE,
+ headers = "Authorization"
+ )β’ Donβt forget to add the import:
import org.springframework.http.MediaType;π€ Prompt for AI Agents
In
src/main/java/com/iemr/helpline104/controller/drugGroup/DrugGroupController.java
around lines 56 to 59, the @PostMapping annotation lacks explicit consumes and
produces attributes for media types. To fix this, remove any controller-level
@CrossOrigin annotations since global CorsConfig covers /beneficiary/**, then
update the @PostMapping to include consumes = MediaType.APPLICATION_JSON_VALUE
and produces = MediaType.APPLICATION_JSON_VALUE. Also, add the import for
org.springframework.http.MediaType to support these attributes.
| @PostMapping(value = "/getROSummaryReportByDate", headers = "Authorization") | ||
| public ResponseEntity<Object> getROSummaryReportByDate(@RequestBody String jsonRequest) | ||
| { | ||
| public ResponseEntity<Object> getROSummaryReportByDate(@RequestBody String jsonRequest) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
CORS preflight conflict: remove headers = "Authorization" from mapping.
Restricting the @PostMapping to requests with an Authorization header blocks OPTIONS preflight, breaking CORS. Remove the headers attribute and rely on your global CorsConfig and security filter to enforce auth.
- @PostMapping(value = "/getROSummaryReportByDate", headers = "Authorization")
+ @PostMapping("/getROSummaryReportByDate")Apply the same removal for all other endpoints.
π 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.
| public ResponseEntity<Object> getROSummaryReportByDate(@RequestBody String jsonRequest) { | |
| // Before: | |
| - @PostMapping(value = "/getROSummaryReportByDate", headers = "Authorization") | |
| + @PostMapping("/getROSummaryReportByDate") | |
| public ResponseEntity<Object> getROSummaryReportByDate(@RequestBody String jsonRequest) { | |
| // ... | |
| } |
π€ Prompt for AI Agents
In
src/main/java/com/iemr/helpline104/controller/secondaryCrmReports/SecondaryCRMReports.java
at line 56, remove the headers = "Authorization" attribute from the @PostMapping
annotation on the getROSummaryReportByDate method to avoid blocking CORS
preflight OPTIONS requests. This change should be applied to all other endpoints
in this controller that have the same headers restriction. Rely on the global
CorsConfig and security filters to handle authorization instead.



π Description
JIRA ID: 593
Please provide a summary of the change and the motivation behind it. Include relevant context and details.
β Type of Change
βΉοΈ Additional Information
Please describe how the changes were tested, and include any relevant screenshots, logs, or other information that provides additional context.
Summary by CodeRabbit