Skip to content

Conversation

@vishwab1
Copy link
Member

@vishwab1 vishwab1 commented Jun 17, 2025

πŸ“‹ Description

JIRA ID: AMM-1246

Please provide a summary of the change and the motivation behind it. Include relevant context and details.


βœ… Type of Change

  • 🐞 Bug fix (non-breaking change which resolves an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • πŸ”₯ Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • πŸ›  Refactor (change that is neither a fix nor a new feature)
  • βš™οΈ Config change (configuration file or build script updates)
  • πŸ“š Documentation (updates to docs or readme)
  • πŸ§ͺ Tests (adding new or updating existing tests)
  • 🎨 UI/UX (changes that affect the user interface)
  • πŸš€ Performance (improves performance)
  • 🧹 Chore (miscellaneous changes that don't modify src or test files)

ℹ️ 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

  • New Features

    • Centralized CORS (Cross-Origin Resource Sharing) configuration is now managed through environment properties, allowing for flexible control of allowed origins.
  • Refactor

    • All controller-level CORS annotations have been removed in favor of global CORS handling.
    • Request filtering has been updated to enforce CORS policies based on the new configuration.
  • Chores

    • Added and documented new configuration properties for CORS allowed origins.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 17, 2025

Walkthrough

This change removes all @CrossOrigin annotations from controller classes and methods, centralizing CORS handling in the JwtUserIdValidationFilter. The filter is updated to dynamically set CORS headers based on a configurable list of allowed origins. Related configuration properties and injection mechanisms are added to support this new approach.

Changes

File(s) Change Summary
src/main/environment/common_ci.properties, src/main/environment/common_example.properties Added cors.allowed-origins property for CORS configuration.
All files under src/main/java/com/iemr/tm/controller/... (multiple controllers) Removed all @CrossOrigin annotations from classes and methods. Minor formatting adjustments in some files.
src/main/java/com/iemr/tm/utils/FilterConfig.java Injects allowedOrigins property and passes it to JwtUserIdValidationFilter. Sets filter order explicitly.
src/main/java/com/iemr/tm/utils/JwtUserIdValidationFilter.java Adds CORS handling based on allowed origins, updates constructor, removes @Component, adds origin matching.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Filter (JwtUserIdValidationFilter)
    participant Controller

    Client->>Filter: HTTP Request (with Origin header)
    alt OPTIONS request
        Filter-->>Client: 200 OK with CORS headers (if origin allowed)
    else Non-OPTIONS request
        Filter->>Filter: Validate Origin against allowedOrigins
        alt Origin allowed
            Filter->>Client: Add CORS headers
            Filter->>Controller: Forward request
            Controller-->>Filter: Response
            Filter-->>Client: Response with CORS headers
        else Origin not allowed
            Filter->>Client: No CORS headers, log warning
            Filter->>Controller: Forward request
            Controller-->>Filter: Response
            Filter-->>Client: Response
        end
    end
Loading

Suggested reviewers

  • ravishanigarapu

Poem

In the garden of code, CORS once grew wild,
Now a wise rabbit has trimmed and compiled.
No more annotations scattered about,
One filter to rule them, origins checked out.
With headers set smartly, the requests hop throughβ€”
Centralized, secure, and fresh as morning dew!
πŸ‡βœ¨

✨ Finishing Touches
  • πŸ“ Generate Docstrings

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.

❀️ Share
πŸͺ§ Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@sonarqubecloud
Copy link

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (18)
src/main/environment/common_ci.properties (1)

79-80: Introduce cors.allowed-origins configuration
Adds a dynamic list of allowed CORS origins. Ensure the filter handles missing or invalid values gracefully, and document the expected format (e.g., comma-separated list) in your README or config reference.

src/main/environment/common_example.properties (1)

77-78: Clarify wildcard usage for example CORS origins
The pattern http://localhost:* may not be recognized by all CORS matchers. Consider showing explicit host:port pairs or documenting supported wildcard semantics to avoid confusion.

src/main/java/com/iemr/tm/controller/login/IemrMmuLoginController.java (1)

28-30: Cross-origin import successfully removed – please verify global cleanup

The @CrossOrigin import disappeared here, which aligns with the new filter-based CORS approach.
To avoid stray annotations/imports elsewhere (which would compile but be ignored, causing silent config drift), a quick repo-wide check is worthwhile.

#!/bin/bash
# Find any remaining @CrossOrigin usages or imports
rg --line-number "@CrossOrigin" src/main/java || echo "βœ…  No @CrossOrigin annotations found"
rg --line-number "import .*CrossOrigin" src/main/java || echo "βœ…  No CrossOrigin imports found"
src/main/java/com/iemr/tm/controller/videoconsultationcontroller/VideoConsultationController.java (2)

96-100: Path overlap may cause ambiguous mapping

/call/{fromuserID}/{touserID} and /call/{fromuserID}/{touserID}/{type} are both GET endpoints.
Calling /call/1/2 matches the first mapping, but Spring will still consider the second pattern as a potential candidate (it differs only by an optional segment); under some Spring versions this logs an β€œAmbiguous mapping” warning.

Consider making the second mapping explicit, e.g.

-@GetMapping(value = "/call/{fromuserID}/{touserID}/{type}", …)
+@GetMapping(value = "/callWithType/{fromuserID}/{touserID}/{type}", …)

or merge the logic into one method with @RequestParam("type") if backwards-compatible.


151-154: Same potential ambiguity for /callvan/** endpoints

The two callvan mappings have the same pattern issue described above.
Refactor as suggested to avoid route-resolution warnings.

src/main/java/com/iemr/tm/controller/generalOPD/GeneralOPDController.java (1)

59-63: Delete commented-out autowiring block

Dead, commented code makes the file noisy and risks diverging from the real implementation. Safe to remove entirely.

-	// @Autowired
-	// public void setGeneralOPDServiceImpl(GeneralOPDServiceImpl
-	// generalOPDServiceImpl) {
-	// this.generalOPDService = generalOPDService;
-	// }
src/main/java/com/iemr/tm/controller/anc/AntenatalCareController.java (2)

124-128: Capture exception stacktrace for easier debugging

Only the message is logged; consider adding the throwable to keep the stacktrace:

-			logger.error("Error while saving doctor data:" + e.getMessage());
+			logger.error("Error while saving doctor data", e);

450-454: Same logging issue as above

Replicate the improved logging here too.

-			logger.error("Unable to modify data. " + e.getMessage());
+			logger.error("Unable to modify data", e);
src/main/java/com/iemr/tm/controller/foetalmonitor/FoetalMonitorController.java (1)

166-175: Consider removing the gigantic JSON string from the @Param annotation

The long in-line JSON sample clutters the annotation, adds CR/LF escape sequences, and hurts readability. A cleaner approach is to drop the @Param completely (Swagger/OpenAPI will already pick up the @RequestBody) or move the sample into a dedicated DTO / schema example.

- @Param("\r\n" + "{ ... very long sample ... }") @RequestBody String requestObj,
+ @RequestBody String requestObj,

Optional but will make the source far easier to scan.

src/main/java/com/iemr/tm/controller/common/main/WorklistController.java (1)

99-116: Minor: null-checks on mandatory @PathVariable integers are redundant

providerServiceMapID, serviceID, and vanID are primitives in the URL – Spring will fail to bind if they are absent, so the subsequent null checks (lines 107-115) are never hit.
Removing them would simplify the method.

src/main/java/com/iemr/tm/controller/nurse/vitals/AnthropometryVitalsController.java (2)

31-33: @Param is the wrong annotation for a REST payload

org.springframework.data.repository.query.Param is meant for Spring-Data repositories, not for MVC controllers. It adds no value here and is confusing.
Use only @RequestBody, or if you need to document the schema for OpenAPI use @io.swagger.v3.oas.annotations.media.Schema on the DTO instead.

- public String getBenHeightDetailsFrmNurse(
-         @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) {
+ public String getBenHeightDetailsFrmNurse(@RequestBody String comingRequest) {

35-36: Avoid logging raw request bodies

benRegID is personally-identifiable information. Dumping the entire JSON into application logs can violate audit / privacy requirements and inflate log size.
Log only a correlation ID or the parsed benRegID, not the full payload.

src/main/java/com/iemr/tm/utils/FilterConfig.java (2)

12-14: Fail fast when cors.allowed-origins is missing

If the property is absent or empty the filter silently blocks every origin, which is hard to diagnose.
Consider validating the property at startup and throwing an IllegalStateException, or supply a sensible default (e.g. "" meaning β€œno CORS allowed”).


20-24: allowedOrigins should be parsed once, not per request

JwtUserIdValidationFilter currently splits & builds a regex for every request. Move the parsing into the configuration class when you create the filter and pass a pre-compiled List<Pattern> (or even a Predicate<String>). This avoids garbage on every call and simplifies the filter.

src/main/java/com/iemr/tm/utils/JwtUserIdValidationFilter.java (3)

5-9: Remove unused @Component import

The annotation was deleted but the import lingers, producing an IDE/compile warning.

-import org.springframework.stereotype.Component;

39-53: Header name mismatch may confuse clients

The pre-flight response whitelists Jwttoken, whereas the runtime code expects JwtToken (capital β€œT”).
Although header names are case-insensitive, spelling differences trip developers. Add both variants to be explicit.

- response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, Jwttoken");
+ response.setHeader("Access-Control-Allow-Headers",
+     "Authorization, Content-Type, Accept, Jwttoken, JwtToken");

133-150: isOriginAllowed builds regexes on every request

Splitting, replacing, and .matches for every call is avoidable.
Cache the compiled Patterns once (e.g. in the constructor) and just iterate over them in O(allowedOrigins) instead of O(allowedOrigins Γ— regex build).

src/main/java/com/iemr/tm/controller/ncdscreening/NCDScreeningController.java (1)

28-28: Transactional annotation belongs in the service layer, not the controller.
Managing transactions in the controller breaks separation of concerns and couples web layer to persistence. Move @Transactional and its import to the service implementation where business logic resides.

πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between b58c191 and 0133608.

πŸ“’ Files selected for processing (29)
  • src/main/environment/common_ci.properties (1 hunks)
  • src/main/environment/common_example.properties (1 hunks)
  • src/main/java/com/iemr/tm/controller/anc/AntenatalCareController.java (4 hunks)
  • src/main/java/com/iemr/tm/controller/cancerscreening/CancerScreeningController.java (1 hunks)
  • src/main/java/com/iemr/tm/controller/common/main/WorklistController.java (2 hunks)
  • src/main/java/com/iemr/tm/controller/common/master/CommonMasterController.java (1 hunks)
  • src/main/java/com/iemr/tm/controller/covid19/CovidController.java (1 hunks)
  • src/main/java/com/iemr/tm/controller/dataSyncActivity/StartSyncActivity.java (1 hunks)
  • src/main/java/com/iemr/tm/controller/dataSyncLayerCentral/MMUDataSyncVanToServer.java (1 hunks)
  • src/main/java/com/iemr/tm/controller/foetalmonitor/FoetalMonitorController.java (8 hunks)
  • src/main/java/com/iemr/tm/controller/generalOPD/GeneralOPDController.java (2 hunks)
  • src/main/java/com/iemr/tm/controller/labtechnician/LabtechnicianController.java (4 hunks)
  • src/main/java/com/iemr/tm/controller/location/LocationController.java (2 hunks)
  • src/main/java/com/iemr/tm/controller/login/IemrMmuLoginController.java (1 hunks)
  • src/main/java/com/iemr/tm/controller/ncdCare/NCDCareController.java (1 hunks)
  • src/main/java/com/iemr/tm/controller/ncdscreening/NCDScreeningController.java (2 hunks)
  • src/main/java/com/iemr/tm/controller/nurse/vitals/AnthropometryVitalsController.java (2 hunks)
  • src/main/java/com/iemr/tm/controller/patientApp/master/PatientAppCommonMasterController.java (11 hunks)
  • src/main/java/com/iemr/tm/controller/pnc/PostnatalCareController.java (1 hunks)
  • src/main/java/com/iemr/tm/controller/quickBlox/QuickbloxController.java (2 hunks)
  • src/main/java/com/iemr/tm/controller/quickconsult/QuickConsultController.java (1 hunks)
  • src/main/java/com/iemr/tm/controller/registrar/main/RegistrarController.java (7 hunks)
  • src/main/java/com/iemr/tm/controller/report/CRMReportController.java (1 hunks)
  • src/main/java/com/iemr/tm/controller/snomedct/SnomedController.java (2 hunks)
  • src/main/java/com/iemr/tm/controller/teleconsultation/TeleConsultationController.java (1 hunks)
  • src/main/java/com/iemr/tm/controller/version/VersionController.java (2 hunks)
  • src/main/java/com/iemr/tm/controller/videoconsultationcontroller/VideoConsultationController.java (3 hunks)
  • src/main/java/com/iemr/tm/utils/FilterConfig.java (1 hunks)
  • src/main/java/com/iemr/tm/utils/JwtUserIdValidationFilter.java (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Package-test
  • GitHub Check: Analyze (java)
πŸ”‡ Additional comments (25)
src/main/java/com/iemr/tm/controller/ncdCare/NCDCareController.java (1)

31-32: Review import cleanup
This blank-line change reflects removal of controller-level CORS annotations and their imports. Please verify that no @CrossOrigin imports remain and clean up any unused imports.

src/main/java/com/iemr/tm/controller/covid19/CovidController.java (1)

31-32: Review import cleanup
Confirm that all @CrossOrigin imports have been removed following the shift to centralized CORS, and remove any leftover unused imports.

src/main/java/com/iemr/tm/controller/cancerscreening/CancerScreeningController.java (1)

29-29: Review import cleanup
Ensure no residual CORS-related imports or blank lines remain after migrating CORS handling into the filter layer.

src/main/java/com/iemr/tm/controller/common/master/CommonMasterController.java (1)

29-32: Same import removal here – double-check that every module compiles

Nothing functionally wrong, but do a full build after the annotation purge; IDEs sometimes leave unused import statements that fail CI. The verification script in the previous comment will catch leftovers.

src/main/java/com/iemr/tm/controller/videoconsultationcontroller/VideoConsultationController.java (1)

27-32: CORS import gone – good. Build still includes RequestMethod & friends

No action needed; import list is minimal and compiles.

src/main/java/com/iemr/tm/controller/registrar/main/RegistrarController.java (1)

301-305: Minor message tweak looks fine

Only the error string changed; no behavioural impact.

src/main/java/com/iemr/tm/controller/dataSyncActivity/StartSyncActivity.java (1)

28-36: Import housekeeping acknowledged

CORS import removed here as well; ensure the full build passes.

src/main/java/com/iemr/tm/controller/quickconsult/QuickConsultController.java (1)

29-29: Removed CrossOrigin import: centralize CORS handling
The @CrossOrigin import has been removed to delegate all CORS logic to the JwtUserIdValidationFilter. Ensure this filter is registered with highest precedence and correctly applies CORS headers (including preflight OPTIONS) for all QuickConsult endpoints.

src/main/java/com/iemr/tm/controller/labtechnician/LabtechnicianController.java (5)

27-27: Removed CrossOrigin import
The CrossOrigin annotation import was removed. CORS is now managed globally via the centralized filter.


50-50: Removed class-level @crossorigin
Class-level CORS annotation removed. Confirm that JwtUserIdValidationFilter covers requests before controller logic.


52-52: Removed @crossorigin on save endpoint
The explicit CORS annotation on saveLabTestResult has been dropped. Verify dynamic origin checks in the filter handle this path.


94-94: Removed @crossorigin on prescribed procedures endpoint
CORS annotation removed from /get/prescribedProceduresList. Ensure preflight and actual requests are correctly handled by the filter.


151-151: Removed @crossorigin on lab result endpoint
Dropped the @CrossOrigin from /get/labResultForVisitcode. Double-check that allowed origins configuration covers this route.

src/main/java/com/iemr/tm/controller/dataSyncLayerCentral/MMUDataSyncVanToServer.java (1)

27-27: Removed CrossOrigin import
Eliminated controller-level CORS import to centralize handling in the filter. Verify that config property cors.allowed-origins is injected into FilterConfig and applied here.

src/main/java/com/iemr/tm/controller/pnc/PostnatalCareController.java (1)

29-29: Removed CrossOrigin import
The CrossOrigin import was removed in favor of global filter-based CORS. Ensure that all PNC endpoints are now covered by JwtUserIdValidationFilter.

src/main/java/com/iemr/tm/controller/location/LocationController.java (2)

28-28: Removed CrossOrigin import
Dropped the CORS annotation import. Centralized filter must now handle all location endpoints.


43-43: Removed class-level @crossorigin
Removed the explicit @CrossOrigin on the controller. Confirm the filter logic correctly applies CORS headers for GET and POST routes here.

src/main/java/com/iemr/tm/controller/snomedct/SnomedController.java (1)

24-30: ```shell
#!/bin/bash

Show where Origin is read and CORS headers are set

echo "=== getHeader usage ==="
grep -F -n 'getHeader' src/main/java/com/iemr/tm/utils/JwtUserIdValidationFilter.java || true

echo
echo "=== File snippet 1–80 ==="
sed -n '1,80p' src/main/java/com/iemr/tm/utils/JwtUserIdValidationFilter.java


</details>
<details>
<summary>src/main/java/com/iemr/tm/controller/quickBlox/QuickbloxController.java (1)</summary>

`52-55`: **Pre-flight may bypass this handler because of `headers="Authorization"`**

All endpoint mappings under `/quickblox` still demand an `Authorization` header.  
Browsers do NOT include that header in the CORS pre-flight `OPTIONS` request, so Spring will not match the mapping and will fall back to `404` unless the filter short-circuits the request earlier.

Verify with an actual `OPTIONS` call from the front-end after this change.

</details>
<details>
<summary>src/main/java/com/iemr/tm/controller/version/VersionController.java (1)</summary>

`54-57`: **No issues with CORS removal here**

`/version` never required cross-site credentials, so moving the CORS logic to the global filter is risk-free.

</details>
<details>
<summary>src/main/java/com/iemr/tm/controller/foetalmonitor/FoetalMonitorController.java (1)</summary>

`77-78`: **Looks good – just a split line, no functional impact**  
No concerns with the wrapped call; readability is preserved.

</details>
<details>
<summary>src/main/java/com/iemr/tm/controller/patientApp/master/PatientAppCommonMasterController.java (1)</summary>

`62-68`: **LGTM – annotation wording change only**  
The updated summary string is clear and does not affect behaviour.

</details>
<details>
<summary>src/main/java/com/iemr/tm/controller/report/CRMReportController.java (1)</summary>

`30-35`: **Imports adjusted correctly after removing `@CrossOrigin`**  
Compilation should succeed; no unused imports introduced.

</details>
<details>
<summary>src/main/java/com/iemr/tm/controller/teleconsultation/TeleConsultationController.java (1)</summary>

`28-33`: **Import block update aligns with centralised CORS refactor**  
Nothing else changed – looks fine.

</details>
<details>
<summary>src/main/java/com/iemr/tm/utils/JwtUserIdValidationFilter.java (1)</summary>

`54-58`: **Pre-flight path returns 200 even for disallowed origins**  

When `origin` is not allowed you skip CORS headers but still return `200 OK` for `OPTIONS`.  
Browsers will still block the actual call, but you spend CPU validating JWTs later.  
Consider short-circuiting with `SC_FORBIDDEN` (403) when the origin is not on the allow-list to surface mis-configurations early.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

@vishwab1 vishwab1 requested review from drtechie and vanitha1822 June 17, 2025 16:19
@vishwab1 vishwab1 merged commit f7717ad into develop Jun 18, 2025
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants