Skip to content

Conversation

@vishwab1
Copy link
Member

@vishwab1 vishwab1 commented May 23, 2025

πŸ“‹ Description

JIRA ID: AMM 593

Please provide a summary of the change and the motivation behind it. Include relevant context and details.
Added cors orign method to restrict from the browsers

βœ… 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

    • Introduced dynamic CORS (Cross-Origin Resource Sharing) configuration, allowing administrators to specify allowed origins via environment or properties files.
    • CORS headers are now applied globally, supporting dynamic origin matching and handling of preflight OPTIONS requests.
  • Refactor

    • Centralized CORS management by removing all method-level and class-level CORS annotations from controllers.
  • Chores

    • Updated configuration files to include new CORS-related properties.

@coderabbitai
Copy link

coderabbitai bot commented May 23, 2025

Walkthrough

This update centralizes and enhances CORS (Cross-Origin Resource Sharing) configuration for the application. It introduces a global CORS configuration class and a dynamic filter, removes all @CrossOrigin annotations from controller methods, and adds new properties for allowed origins in configuration files. Filters and related utilities are updated to support dynamic, pattern-based CORS handling.

Changes

File(s) Change Summary
src/main/environment/admin_ci.properties, src/main/environment/admin_example.properties Added new property cors.allowed-origins to enable dynamic specification of allowed CORS origins via environment variable or static value.
src/main/java/com/iemr/admin/config/CorsConfig.java Introduced new global CORS configuration class implementing WebMvcConfigurer, reading allowed origins from configuration and applying CORS settings (methods, headers, credentials, preflight cache) to all endpoints.
src/main/java/com/iemr/admin/utils/DynamicCorsFilter.java Added a new filter component that dynamically sets CORS headers based on allowed origins from configuration, handling preflight OPTIONS requests and matching origins with support for patterns.
src/main/java/com/iemr/admin/utils/FilterConfig.java Updated to inject cors.allowed-origins property and pass it to JwtUserIdValidationFilter constructor, enabling dynamic CORS handling in JWT validation filter.
src/main/java/com/iemr/admin/utils/JwtUserIdValidationFilter.java Modified constructor to accept allowed origins; updated filter logic to set CORS headers only for allowed origins, handle OPTIONS requests directly, and added pattern-based origin matching.
All controller files under src/main/java/com/iemr/admin/controller/** Removed all @CrossOrigin() annotations from controller methods and classes, consolidating CORS configuration to global and filter-based approaches. No changes to method signatures, logic, or exported entities. Minor formatting changes in a few controllers.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Filter (DynamicCorsFilter/JwtUserIdValidationFilter)
    participant Controller

    Client->>Filter: HTTP Request (with Origin header)
    alt OPTIONS (preflight)
        Filter->>Filter: Check if Origin is allowed
        alt Origin allowed
            Filter-->>Client: Respond 200 OK with CORS headers
        else Origin not allowed
            Filter-->>Client: Respond 403/No CORS headers
        end
    else Other HTTP methods
        Filter->>Filter: Check if Origin is allowed
        alt Origin allowed
            Filter->>Controller: Forward request with CORS headers
            Controller-->>Filter: Response
            Filter-->>Client: Response with CORS headers
        else Origin not allowed
            Filter->>Controller: Forward request without CORS headers
            Controller-->>Filter: Response
            Filter-->>Client: Response (no CORS headers)
        end
    end
Loading

Poem

In the warren of code, CORS once ran wild,
Each controller adorned, annotations compiled.
Now, with a hop, configuration’s in placeβ€”
A single spring filter, a tidier space!
Origins allowed, by pattern or name,
Bunnies rejoice: CORS is never the same!
πŸ‡βœ¨

Note

⚑️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.

✨ 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

@vishwab1 vishwab1 changed the title Cors Cors configuration for admin api service May 23, 2025
Copy link

@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: 4

πŸ”­ Outside diff range comments (3)
src/main/java/com/iemr/admin/controller/version/VersionController.java (1)

47-60: πŸ’‘ Verification agent

🧩 Analysis chain

Verify CORS handling for GET endpoint.

This GET endpoint for version information is particularly important to test with the new centralized CORS configuration, as it's likely to be accessed directly by browsers and doesn't require Authorization headers.


🏁 Script executed:

#!/bin/bash
# Verify version endpoint is accessible and returns proper CORS headers
echo "Checking version endpoint CORS configuration..."

# Look for any special handling of GET endpoints in CORS config
rg -A 10 -B 5 "GET\|version" src/main/java/com/iemr/admin/config/ || echo "No config directory found"

# Check if version endpoint has any special CORS requirements
rg -A 5 -B 5 "/version" 

Length of output: 13728


Ensure CORS is explicitly enabled for the /version endpoint

I wasn’t able to locate any global or per-endpoint CORS configuration in the codebase (no WebMvcConfigurer, CorsFilter bean or @CrossOrigin on the controller). Without it, browsers will block cross-origin GET requests to this endpoint.

Please add or update your CORS configuration, for example:

// src/main/java/com/iemr/admin/config/WebConfig.java
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/version")
                .allowedOrigins("*")      // or restrict to specific origins
                .allowedMethods("GET");
    }
}

β€’ Create WebConfig under com.iemr.admin.config (or your existing config package)
β€’ Verify that a browser request to /version returns an Access-Control-Allow-Origin header

src/main/java/com/iemr/admin/controller/createorder/CareStreamCreateOrderController.java (1)

71-71: ⚠️ Potential issue

Critical: Externalize hardcoded IP addresses.

The controller contains hardcoded IP addresses (192.168.1.199, 192.168.1.101) which pose security and configuration management risks.

Move these IP addresses to application configuration:

+@Value("${carestream.server.primary.host:192.168.1.199}")
+private String primaryServerHost;
+
+@Value("${carestream.server.primary.port:1235}")
+private int primaryServerPort;
+
+@Value("${carestream.server.secondary.host:192.168.1.101}")
+private String secondaryServerHost;

Then update the socket connections:

-Socket socket = new Socket("192.168.1.199", 1235);
+Socket socket = new Socket(primaryServerHost, primaryServerPort);

This allows for environment-specific configuration and improves security by avoiding hardcoded network addresses in source code.

Also applies to: 140-140, 196-196

src/main/java/com/iemr/admin/utils/JwtUserIdValidationFilter.java (1)

122-127: ⚠️ Potential issue

Remove duplicate error response code.

Lines 125-126 duplicate the exact same error response that was already sent on lines 122-123.

         logger.warn("No valid authentication token found");
         response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: Invalid or missing token");
-
-        logger.warn("No valid authentication token found");
-        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: Invalid or missing token");
♻️ Duplicate comments (19)
src/main/java/com/iemr/admin/controller/drugstrength/DrugStrength.java (3)

79-79: Duplicate removal of method-level CORS annotation


106-106: Duplicate removal of method-level CORS annotation


138-138: Duplicate removal of method-level CORS annotation

src/main/java/com/iemr/admin/controller/parkingPlace/ParkingPlaceTalukMappingController.java (6)

72-72: Duplicate removal of method-level CORS annotation


100-100: Duplicate removal of method-level CORS annotation


124-124: Duplicate removal of method-level CORS annotation


145-145: Duplicate removal of method-level CORS annotation


166-166: Duplicate removal of method-level CORS annotation


192-192: Duplicate removal of method-level CORS annotation

src/main/java/com/iemr/admin/controller/nodalConfig/NodalConfigController.java (2)

77-77: Duplicate removal of method-level CORS annotation


97-97: Duplicate removal of method-level CORS annotation

src/main/java/com/iemr/admin/controller/vanSpokeMapping/VanSpokeMappingController.java (2)

76-76: Duplicate removal of method-level CORS annotation


96-96: Duplicate removal of method-level CORS annotation

src/main/java/com/iemr/admin/controller/itemfacilitymapping/MItemFacilityMappingController.java (6)

114-114: Duplicate removal of method-level CORS annotation


149-149: Duplicate removal of method-level CORS annotation


180-180: Duplicate removal of method-level CORS annotation


208-208: Duplicate removal of method-level CORS annotation


236-236: Duplicate removal of method-level CORS annotation


260-260: Duplicate removal of method-level CORS annotation

🧹 Nitpick comments (24)
src/main/java/com/iemr/admin/controller/stockExit/StockExitController.java (1)

44-44: Remove unused CORS import
The @CrossOrigin annotation was removed from the patientIssue method to centralize CORS configuration. Please delete the now-unused

import org.springframework.web.bind.annotation.CrossOrigin;

at line 25 to clean up imports and avoid compiler warnings.

src/main/java/com/iemr/admin/controller/facilitytype/FacilitytypeController.java (1)

52-52: Clean up unused CORS import after annotation removal
Blank lines at these locations correspond to removed @CrossOrigin annotations. Please remove the unused

import org.springframework.web.bind.annotation.CrossOrigin;

at line 31 to keep the import list tidy.

Also applies to: 79-79, 106-106, 138-138, 169-169

src/main/java/com/iemr/admin/controller/questionnaire/QuestionnaireController.java (1)

47-47: Remove leftover CORS import
Method‐level @CrossOrigin annotations were stripped here; the import

import org.springframework.web.bind.annotation.CrossOrigin;

at line 27 is now unused. Please delete it to avoid warnings.

Also applies to: 67-67, 85-85, 103-103

src/main/java/com/iemr/admin/controller/supplier/SupplierMasterController.java (1)

52-52: Delete unused CORS import
These blank lines mark where @CrossOrigin annotations were removed. The import

import org.springframework.web.bind.annotation.CrossOrigin;

at line 31 should be removed to clean up unused code.

Also applies to: 73-73, 91-91, 129-129, 152-152

src/main/java/com/iemr/admin/controller/calibration/CalibrationController.java (2)

27-27: Remove unused import.

The @CrossOrigin import is no longer needed since all method-level CORS annotations have been removed in favor of centralized configuration.

-import org.springframework.web.bind.annotation.CrossOrigin;

55-55: Clean up blank lines left from annotation removal.

Consider removing the blank lines that were left behind after removing the @CrossOrigin() annotations to improve code readability.

-	
 	@Operation(summary = "Create calibration strip")

Also applies to: 88-88, 116-116, 144-144

src/main/java/com/iemr/admin/controller/telemedicine/TeleMedicineController.java (3)

29-29: Remove unused import.

The @CrossOrigin import is no longer needed since all method-level CORS annotations have been removed.

-import org.springframework.web.bind.annotation.CrossOrigin;

53-53: Clean up blank lines from annotation removal.

Remove the blank lines left behind after removing the @CrossOrigin() annotations.

Also applies to: 77-77, 101-101, 126-126, 151-151


127-149: Consider renaming duplicate method names.

Both methods at lines 130 and 155 are named saveUserSpecialization. The second method appears to handle activation/deactivation logic and should be renamed for clarity.

-public String saveUserSpecialization(@RequestBody UserSpecializationMapping userSpecializationMapping) {
+public String activateDeactivateUserSpecialization(@RequestBody UserSpecializationMapping userSpecializationMapping) {

Also applies to: 152-177

src/main/java/com/iemr/admin/controller/version/VersionController.java (2)

31-31: Remove unused import.

The @CrossOrigin import is no longer needed.

-import org.springframework.web.bind.annotation.CrossOrigin;

46-46: Clean up blank line.

Remove the blank line left from the annotation removal.

src/main/java/com/iemr/admin/controller/labmodule/SmartDiagnosticsController.java (2)

30-30: Remove unused import.

The @CrossOrigin import is no longer needed since method-level CORS annotations have been removed.

-import org.springframework.web.bind.annotation.CrossOrigin;

50-50: Clean up blank lines.

Remove the blank lines left behind from annotation removal.

Also applies to: 70-70

src/main/java/com/iemr/admin/controller/stockEntry/StockEntryController.java (1)

29-29: Remove unused @CrossOrigin import
The import at line 29 is no longer used after removing method-level annotations; please remove it to keep imports clean.

src/main/java/com/iemr/admin/controller/pharmacologicalcategory/PharmacologicalCategoryController.java (1)

31-31: Remove unused @CrossOrigin import
After removing method-level annotations, the import at line 31 is no longer needed; please delete it.

src/main/java/com/iemr/admin/controller/manufacturer/ManufacturerController.java (1)

31-31: Remove unused @CrossOrigin import
The import at line 31 is now unused following annotation removals; please remove it.

src/main/java/com/iemr/admin/controller/emailconfig/EmailConfigController.java (1)

32-32: Remove unused @CrossOrigin import
Since all @CrossOrigin annotations have been removed, the import at line 32 should be cleaned up.

src/main/java/com/iemr/admin/controller/zonemaster/ZoneMasterController.java (1)

28-28: Remove unused import.

The @CrossOrigin import is no longer used after removing the annotations from controller methods.

-import org.springframework.web.bind.annotation.CrossOrigin;
src/main/java/com/iemr/admin/controller/vanServicePointMapping/VanServicePointMappingController.java (1)

27-27: Remove unused import.

The @CrossOrigin import is no longer needed after removing the annotations.

-import org.springframework.web.bind.annotation.CrossOrigin;
src/main/java/com/iemr/admin/controller/store/StoreController.java (1)

31-31: Remove unused import.

The @CrossOrigin import is no longer used after removing all annotations.

-import org.springframework.web.bind.annotation.CrossOrigin;
src/main/java/com/iemr/admin/controller/createorder/CareStreamCreateOrderController.java (1)

32-32: Remove unused import.

The @CrossOrigin import is no longer needed.

-import org.springframework.web.bind.annotation.CrossOrigin;
src/main/java/com/iemr/admin/utils/DynamicCorsFilter.java (2)

26-29: Add missing CORS headers for completeness.

The current implementation only sets Access-Control-Allow-Origin. Consider adding other essential CORS headers for consistency with the JWT filter implementation.

         String origin = request.getHeader("Origin");
-        if (origin != null && Arrays.asList(allowedOrigins).contains(origin)) {
+        if (origin != null && isOriginAllowed(origin)) {
             response.setHeader("Access-Control-Allow-Origin", origin);
+            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
+            response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, Jwttoken");
+            response.setHeader("Access-Control-Allow-Credentials", "true");
         }

14-37: Consider architectural redundancy with multiple CORS handlers.

This filter duplicates CORS functionality already implemented in JwtUserIdValidationFilter and the new CorsConfig class. Having multiple CORS handlers can lead to conflicts and maintenance issues.

Consider consolidating CORS handling into a single approach:

  • Option 1: Use only the global CorsConfig for most cases
  • Option 2: Use this filter for specific dynamic cases and remove CORS logic from JWT filter
  • Option 3: Remove this filter and enhance the existing JWT filter

Which approach aligns better with your architecture goals?

src/main/java/com/iemr/admin/controller/uptsu/FacilityController.java (1)

28-28: Remove unused import for @crossorigin.

The @CrossOrigin import is no longer needed since all annotations have been removed from this controller.

-import org.springframework.web.bind.annotation.CrossOrigin;
πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between fd2c377 and 71d8402.

πŸ“’ Files selected for processing (46)
  • src/main/environment/admin_ci.properties (1 hunks)
  • src/main/environment/admin_example.properties (1 hunks)
  • src/main/java/com/iemr/admin/config/CorsConfig.java (1 hunks)
  • src/main/java/com/iemr/admin/controller/blocking/BlockingController.java (0 hunks)
  • src/main/java/com/iemr/admin/controller/calibration/CalibrationController.java (4 hunks)
  • src/main/java/com/iemr/admin/controller/createorder/CareStreamCreateOrderController.java (3 hunks)
  • src/main/java/com/iemr/admin/controller/drugstrength/DrugStrength.java (4 hunks)
  • src/main/java/com/iemr/admin/controller/drugtype/DrugtypeController.java (4 hunks)
  • src/main/java/com/iemr/admin/controller/emailconfig/EmailConfigController.java (3 hunks)
  • src/main/java/com/iemr/admin/controller/employeemaster/EmployeeMasterController.java (2 hunks)
  • src/main/java/com/iemr/admin/controller/employeemaster/EmployeeSignatureController.java (3 hunks)
  • src/main/java/com/iemr/admin/controller/facilitytype/FacilitytypeController.java (5 hunks)
  • src/main/java/com/iemr/admin/controller/foetalmonitormaster/FoetalMonitorController.java (14 hunks)
  • src/main/java/com/iemr/admin/controller/item/ItemController.java (0 hunks)
  • src/main/java/com/iemr/admin/controller/itemfacilitymapping/MItemFacilityMappingController.java (7 hunks)
  • src/main/java/com/iemr/admin/controller/labmodule/LabModuleController.java (2 hunks)
  • src/main/java/com/iemr/admin/controller/labmodule/SmartDiagnosticsController.java (2 hunks)
  • src/main/java/com/iemr/admin/controller/locationmaster/LocationMasterController.java (0 hunks)
  • src/main/java/com/iemr/admin/controller/manufacturer/ManufacturerController.java (5 hunks)
  • src/main/java/com/iemr/admin/controller/nodalConfig/NodalConfigController.java (3 hunks)
  • src/main/java/com/iemr/admin/controller/parkingPlace/ParkingPlaceController.java (0 hunks)
  • src/main/java/com/iemr/admin/controller/parkingPlace/ParkingPlaceTalukMappingController.java (7 hunks)
  • src/main/java/com/iemr/admin/controller/pharmacologicalcategory/PharmacologicalCategoryController.java (5 hunks)
  • src/main/java/com/iemr/admin/controller/provideronboard/ProviderOnBoardController.java (0 hunks)
  • src/main/java/com/iemr/admin/controller/questionnaire/QuestionnaireController.java (4 hunks)
  • src/main/java/com/iemr/admin/controller/rolemaster/RoleMasterController.java (0 hunks)
  • src/main/java/com/iemr/admin/controller/servicePoint/ServicePointController.java (0 hunks)
  • src/main/java/com/iemr/admin/controller/snomedMapping/SnomedMappingController.java (0 hunks)
  • src/main/java/com/iemr/admin/controller/stockEntry/StockEntryController.java (3 hunks)
  • src/main/java/com/iemr/admin/controller/stockExit/StockExitController.java (1 hunks)
  • src/main/java/com/iemr/admin/controller/store/StoreController.java (10 hunks)
  • src/main/java/com/iemr/admin/controller/supplier/SupplierMasterController.java (5 hunks)
  • src/main/java/com/iemr/admin/controller/telemedicine/TeleMedicineController.java (5 hunks)
  • src/main/java/com/iemr/admin/controller/telemedicine/VideoConsultationController.java (6 hunks)
  • src/main/java/com/iemr/admin/controller/uom/UomController.java (5 hunks)
  • src/main/java/com/iemr/admin/controller/uptsu/FacilityController.java (4 hunks)
  • src/main/java/com/iemr/admin/controller/userParkingPlaceMap/UserParkingPlaceMapController.java (0 hunks)
  • src/main/java/com/iemr/admin/controller/vanMaster/VanMasterController.java (1 hunks)
  • src/main/java/com/iemr/admin/controller/vanServicePointMapping/VanServicePointMappingController.java (4 hunks)
  • src/main/java/com/iemr/admin/controller/vanSpokeMapping/VanSpokeMappingController.java (3 hunks)
  • src/main/java/com/iemr/admin/controller/version/VersionController.java (1 hunks)
  • src/main/java/com/iemr/admin/controller/villageMaster/VillageMasterController.java (0 hunks)
  • src/main/java/com/iemr/admin/controller/zonemaster/ZoneMasterController.java (9 hunks)
  • src/main/java/com/iemr/admin/utils/DynamicCorsFilter.java (1 hunks)
  • src/main/java/com/iemr/admin/utils/FilterConfig.java (1 hunks)
  • src/main/java/com/iemr/admin/utils/JwtUserIdValidationFilter.java (3 hunks)
πŸ’€ Files with no reviewable changes (10)
  • src/main/java/com/iemr/admin/controller/villageMaster/VillageMasterController.java
  • src/main/java/com/iemr/admin/controller/blocking/BlockingController.java
  • src/main/java/com/iemr/admin/controller/servicePoint/ServicePointController.java
  • src/main/java/com/iemr/admin/controller/parkingPlace/ParkingPlaceController.java
  • src/main/java/com/iemr/admin/controller/userParkingPlaceMap/UserParkingPlaceMapController.java
  • src/main/java/com/iemr/admin/controller/item/ItemController.java
  • src/main/java/com/iemr/admin/controller/rolemaster/RoleMasterController.java
  • src/main/java/com/iemr/admin/controller/provideronboard/ProviderOnBoardController.java
  • src/main/java/com/iemr/admin/controller/locationmaster/LocationMasterController.java
  • src/main/java/com/iemr/admin/controller/snomedMapping/SnomedMappingController.java
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/main/java/com/iemr/admin/utils/JwtUserIdValidationFilter.java (2)
src/main/java/com/iemr/admin/utils/JwtAuthenticationUtil.java (1)
  • Component (21-126)
src/main/java/com/iemr/admin/utils/JwtUtil.java (1)
  • Component (15-63)
src/main/java/com/iemr/admin/config/CorsConfig.java (1)
src/main/java/com/iemr/admin/utils/FilterConfig.java (1)
  • Configuration (8-26)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)
πŸ”‡ Additional comments (48)
src/main/environment/admin_example.properties (1)

27-27: Verify wildcard port support in CORS origins
You’ve added cors.allowed-origins=http://localhost:*. Spring’s allowedOrigins typically requires explicit ports and doesn’t support wildcard ports; only allowedOriginPatterns does. Ensure your CorsConfig uses allowedOriginPatterns(...) (or adjust the property name) to accept this pattern.

src/main/java/com/iemr/admin/controller/calibration/CalibrationController.java (1)

55-82:

Details

βœ… Verification successful

Verify centralized CORS configuration handles all endpoints.

The removal of method-level @CrossOrigin() annotations is a good architectural improvement. Please ensure that the centralized CORS configuration properly handles all these endpoints, especially since they require Authorization headers.

Also applies to: 88-110, 116-142, 144-170


🏁 Script executed:

#!/bin/bash
# Verify that centralized CORS configuration exists and handles these endpoints
echo "Checking for centralized CORS configuration..."

# Look for CorsConfig class
fd -t f -e java CorsConfig

# Look for CORS-related filter classes
fd -t f -e java | xargs rg -l "Cors.*Filter"

# Check for CORS properties in configuration files
fd -t f -e properties | xargs rg -l "cors"

# Verify CORS headers are still being set for these endpoints
rg -A 5 -B 5 "Access-Control-Allow-Origin"

Length of output: 2871


🏁 Script executed:

#!/bin/bash
# Display CorsConfig to verify global CORS mappings
sed -n '1,200p' src/main/java/com/iemr/admin/config/CorsConfig.java

# Display DynamicCorsFilter to confirm allowed origins, methods, headers, and registration
sed -n '1,200p' src/main/java/com/iemr/admin/utils/DynamicCorsFilter.java

Length of output: 2307


Centralized CORS configuration validated

I’ve confirmed that:

  • CorsConfig globally maps all paths (/**) with the correct allowed origins, methods, headers, exposed headers, credentials flag, and max age.
  • DynamicCorsFilter additionally sets the Access-Control-Allow-Origin header per request and correctly handles preflight (OPTIONS) requests.

No further action is needed hereβ€”the centralized CORS setup covers all your authenticated endpoints.

src/main/java/com/iemr/admin/controller/telemedicine/TeleMedicineController.java (1)

53-75: CORS configuration migration looks good.

The removal of method-level @CrossOrigin() annotations aligns well with the centralized CORS approach mentioned in the PR objectives.

Also applies to: 77-99, 101-124, 126-149, 151-177

src/main/java/com/iemr/admin/controller/labmodule/SmartDiagnosticsController.java (2)

51-68: CORS migration completed successfully.

The removal of @CrossOrigin() annotations from these diagnostic endpoints aligns with the centralized CORS configuration approach.

Also applies to: 71-88


94-97:

Details

❓ Verification inconclusive

Verify CORS consistency for GET endpoint.

The getBiologicalScreeningDeviceUrl() method is a GET endpoint that may also need CORS handling. Ensure the centralized configuration covers all endpoint types consistently.


🏁 Script executed:

#!/bin/bash
# Check if this GET endpoint had @CrossOrigin annotation before
echo "Checking for CORS consistency across all endpoints..."

# Look for any remaining @CrossOrigin annotations in the codebase
rg -n "@CrossOrigin" src/main/java/

# Check if there are different CORS requirements for different HTTP methods
rg -A 3 -B 3 "RequestMethod\.(GET|POST|PUT|DELETE)"

Length of output: 66163


Confirm CORS coverage for GET /biologicalScreeningDevice

No @CrossOrigin annotations were found in the entire codebase. Please verify that your global CORS configuration (e.g. in your WebMvcConfigurer) includes this GET endpointβ€”and any other GET paths such as /version and /getCdssData/{psmId}β€”to allow cross-origin requests where required.

β€’ File: src/main/java/com/iemr/admin/controller/labmodule/SmartDiagnosticsController.java
Lines 94–97 (getBiologicalScreeningDeviceUrl)

src/main/java/com/iemr/admin/controller/stockEntry/StockEntryController.java (2)

52-52: Method-level @CrossOrigin annotations removal confirmed
The removal of @CrossOrigin annotations from these methods aligns with the centralized CORS configuration. No further changes are needed within these methods.

Also applies to: 70-70, 94-94


45-118:

Details

βœ… Verification successful

Verify global CORS configuration coverage
With method-level CORS annotations removed, confirm that CorsConfig.java registers CORS mappings (including OPTIONS preflight) for these endpoints.

Run:


🏁 Script executed:

#!/bin/bash
# Check global CORS mappings and allowed methods in CorsConfig
grep -R "addMapping" -n src/main/java/com/iemr/admin/config/CorsConfig.java
grep -R "addAllowedMethods" -n src/main/java/com/iemr/admin/config/CorsConfig.java

Length of output: 196


To ensure OPTIONS (preflight) and other HTTP methods are covered, let’s check for the chained CORS settings:


🏁 Script executed:

#!/bin/bash
# Verify allowed methods and origins in CorsConfig
grep -R "allowedMethods" -n src/main/java/com/iemr/admin/config/CorsConfig.java
grep -R "allowedOrigins" -n src/main/java/com/iemr/admin/config/CorsConfig.java

Length of output: 336


Global CORS configuration verified
The CorsConfig.java file registers a catch-all mapping ("/**") with .allowedMethods("GET","POST","PUT","DELETE","OPTIONS") and appropriate origin patternsβ€”so all controller endpoints (including /physicalStockEntry, /getItemBatchForStoreID, /allocateStockFromItemID/{facilityID}) are covered for preflight and actual requests. No further changes needed.

src/main/java/com/iemr/admin/controller/pharmacologicalcategory/PharmacologicalCategoryController.java (1)

52-52: Method-level @CrossOrigin annotations removal confirmed
The dropped @CrossOrigin annotations across these methods correctly delegate CORS handling to the global configuration.

Also applies to: 82-82, 111-111, 144-144, 178-178

src/main/java/com/iemr/admin/controller/manufacturer/ManufacturerController.java (1)

51-51: Method-level @CrossOrigin annotations removal confirmed
The removal of these annotations aligns with centralized CORS management and requires no additional adjustments here.

Also applies to: 79-79, 107-107, 147-147, 179-179

src/main/java/com/iemr/admin/controller/emailconfig/EmailConfigController.java (1)

55-55: Method-level @CrossOrigin annotations removal confirmed
Dropping the @CrossOrigin annotations above each endpoint is correct, as CORS is now managed globally.

Also applies to: 76-76, 96-96

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

27-27:

Details

βœ… Verification successful

Confirm cors.allowed-origins property propagation
This new property enables dynamic CORS origins. Ensure it’s mirrored in admin_example.properties with a sample value so environments and new contributors have guidance.

Run:


🏁 Script executed:

#!/bin/bash
# Verify example properties include cors.allowed-origins
grep -R "cors.allowed-origins" -n src/main/environment/admin_example.properties

Length of output: 122


Verified cors.allowed-origins in example file
The admin_example.properties includes cors.allowed-origins=http://localhost:* on line 27. No further action needed.

src/main/java/com/iemr/admin/controller/drugstrength/DrugStrength.java (1)

51-51: Removed method-level CORS annotation
The @CrossOrigin annotation has been removed from the createDrugStrangth endpoint in favor of the centralized CORS configuration provided by CorsConfig.

src/main/java/com/iemr/admin/controller/parkingPlace/ParkingPlaceTalukMappingController.java (1)

50-50: Removed method-level CORS annotation
The per-method @CrossOrigin has been stripped from this endpoint; global CORS policies now apply.

src/main/java/com/iemr/admin/controller/nodalConfig/NodalConfigController.java (1)

56-56: Removed method-level CORS annotation
Switched from method-level @CrossOrigin to centralized CORS via CorsConfig.

src/main/java/com/iemr/admin/controller/vanSpokeMapping/VanSpokeMappingController.java (1)

55-55: Removed method-level CORS annotation
@CrossOrigin removed from the save endpoint; global configuration now governs CORS.

src/main/java/com/iemr/admin/controller/itemfacilitymapping/MItemFacilityMappingController.java (1)

56-56: Removed method-level CORS annotation
The per-method @CrossOrigin annotation has been dropped in favor of global CORS setup.

src/main/java/com/iemr/admin/controller/zonemaster/ZoneMasterController.java (1)

54-296:

Details

βœ… Verification successful

Verify centralized CORS configuration handles all endpoints.

The systematic removal of @CrossOrigin annotations aligns well with the CORS centralization refactoring. This approach improves maintainability by centralizing CORS policies.

Please verify that the new centralized CORS configuration properly handles all endpoints in this controller:


🏁 Script executed:

#!/bin/bash
# Description: Verify that centralized CORS configuration exists and covers these endpoints

# Check if CorsConfig class exists and is properly configured
fd -e java -x grep -l "CorsConfig" {} \;

# Check for CORS-related properties in configuration files
fd -e properties -x grep -l "cors.allowed-origins" {} \;

# Verify DynamicCorsFilter implementation
fd -e java -x grep -l "DynamicCorsFilter" {} \;

Length of output: 359


Centralized CORS configuration is in place

We’ve verified that the global CORS setup covers all controller endpoints without requiring individual @crossorigin annotations:

β€’ src/main/java/com/iemr/admin/config/CorsConfig.java – defines application-wide CORS mappings
β€’ src/main/java/com/iemr/admin/utils/DynamicCorsFilter.java – applies CORS rules at runtime
β€’ src/main/environment/admin_ci.properties & admin_example.properties – specify cors.allowed-origins

No further changes needed; endpoints like /save/zone, /get/zones, etc., will be handled by the centralized configuration.

src/main/java/com/iemr/admin/controller/vanServicePointMapping/VanServicePointMappingController.java (1)

53-173: CORS centralization implemented correctly.

The removal of @CrossOrigin annotations from all controller methods is consistent with the centralized CORS configuration approach. This improves code maintainability and provides better control over CORS policies.

src/main/java/com/iemr/admin/controller/store/StoreController.java (1)

55-324: Excellent systematic CORS refactoring.

All @CrossOrigin annotations have been consistently removed from the 10 controller methods. This systematic approach to CORS centralization will improve maintainability and provide unified CORS policy management.

src/main/java/com/iemr/admin/controller/createorder/CareStreamCreateOrderController.java (1)

52-232: CORS refactoring implemented consistently.

The removal of @CrossOrigin annotations follows the same pattern as other controllers in this refactoring.

🧰 Tools
πŸͺ› ast-grep (0.38.1)

[info] 70-70: "Detected use of a Java socket that is not encrypted. As a result, the
traffic could be read by an attacker intercepting the network traffic. Use
an SSLSocket created by 'SSLSocketFactory' or 'SSLServerSocketFactory'
instead."
Context: new Socket("192.168.1.199", 1235)
Note: [CWE-319] Cleartext Transmission of Sensitive Information [REFERENCES]
- https://owasp.org/Top10/A02_2021-Cryptographic_Failures

(unencrypted-socket-java)


[info] 100-100: "Detected use of a Java socket that is not encrypted. As a result, the
traffic could be read by an attacker intercepting the network traffic. Use
an SSLSocket created by 'SSLSocketFactory' or 'SSLServerSocketFactory'
instead."
Context: new Socket(ip, port)
Note: [CWE-319] Cleartext Transmission of Sensitive Information [REFERENCES]
- https://owasp.org/Top10/A02_2021-Cryptographic_Failures

(unencrypted-socket-java)


[info] 139-139: "Detected use of a Java socket that is not encrypted. As a result, the
traffic could be read by an attacker intercepting the network traffic. Use
an SSLSocket created by 'SSLSocketFactory' or 'SSLServerSocketFactory'
instead."
Context: new Socket("192.168.1.101", 1235)
Note: [CWE-319] Cleartext Transmission of Sensitive Information [REFERENCES]
- https://owasp.org/Top10/A02_2021-Cryptographic_Failures

(unencrypted-socket-java)


[info] 195-195: "Detected use of a Java socket that is not encrypted. As a result, the
traffic could be read by an attacker intercepting the network traffic. Use
an SSLSocket created by 'SSLSocketFactory' or 'SSLServerSocketFactory'
instead."
Context: new Socket("192.168.1.101", 1235)
Note: [CWE-319] Cleartext Transmission of Sensitive Information [REFERENCES]
- https://owasp.org/Top10/A02_2021-Cryptographic_Failures

(unencrypted-socket-java)

src/main/java/com/iemr/admin/controller/drugtype/DrugtypeController.java (3)

78-78: Consistent removal of method-level CORS annotations.

The removal aligns with the centralized CORS configuration strategy.


105-105: Consistent removal of method-level CORS annotations.

The removal aligns with the centralized CORS configuration strategy.


140-140: Consistent removal of method-level CORS annotations.

The removal aligns with the centralized CORS configuration strategy.

src/main/java/com/iemr/admin/controller/telemedicine/VideoConsultationController.java (6)

55-55: Consistent CORS annotation removal across video consultation endpoints.

The systematic removal of @CrossOrigin annotations from all methods in this controller follows the same centralized CORS configuration pattern.


81-81: Consistent CORS annotation removal.

Method-level CORS configuration successfully migrated to global configuration.


107-107: Consistent CORS annotation removal.

Method-level CORS configuration successfully migrated to global configuration.


132-132: Consistent CORS annotation removal.

Method-level CORS configuration successfully migrated to global configuration.


158-158: Consistent CORS annotation removal.

Method-level CORS configuration successfully migrated to global configuration.


183-183: Consistent CORS annotation removal.

Method-level CORS configuration successfully migrated to global configuration.

src/main/java/com/iemr/admin/controller/employeemaster/EmployeeSignatureController.java (3)

61-61: CORS annotation removal for file upload endpoint.

The removal of @CrossOrigin annotation from the file upload method is consistent with the centralized configuration approach.

Since this controller handles sensitive file operations (upload/download), please ensure the global CORS configuration properly handles:

  • File upload requests with proper content types
  • File download responses with appropriate headers
  • Preflight OPTIONS requests for file operations

86-86: CORS annotation removal for file download endpoint.

Consistent with the centralized CORS configuration strategy.


113-113: CORS annotation removal for file existence check endpoint.

Consistent with the centralized CORS configuration strategy.

src/main/java/com/iemr/admin/controller/labmodule/LabModuleController.java (2)

49-49: Class-level CORS annotation removed successfully.

The removal of the class-level @CrossOrigin annotation from LabModuleController is consistent with migrating to centralized CORS configuration. This controller previously had class-wide CORS settings that are now handled globally.


72-72: Method-level CORS annotation removed.

Consistent removal of method-level CORS configuration in favor of global settings.

src/main/java/com/iemr/admin/controller/vanMaster/VanMasterController.java (1)

222-222: LGTM: CORS centralization completed successfully.

The removal of method-level @CrossOrigin annotations in favor of centralized CORS configuration is a good architectural improvement. This approach provides better maintainability and configurability of CORS policies across the application.

src/main/java/com/iemr/admin/controller/employeemaster/EmployeeMasterController.java (2)

1796-1799: Good defensive programming practice.

The null check for getIsSanjeevani() before setting the value prevents potential NullPointerException and is a good defensive programming practice, especially when dealing with user input data.


1855-1857: Consistent null checking pattern.

The consistent application of null checks for getIsSanjeevani() throughout the method ensures robust error handling and prevents potential runtime exceptions.

src/main/java/com/iemr/admin/controller/foetalmonitormaster/FoetalMonitorController.java (2)

113-114: Improved code readability.

The formatting improvement breaks the long method call across multiple lines, enhancing code readability without changing functionality.


172-173: Consistent formatting improvements.

The consistent application of improved formatting for InputMapper.gson().fromJson() calls throughout the file enhances readability and maintainability of the code.

Also applies to: 192-193, 220-221, 242-243, 270-271, 304-305, 331-332, 359-360

src/main/java/com/iemr/admin/controller/uom/UomController.java (1)

51-51: Minor formatting improvements.

The spacing adjustments improve code consistency and readability without affecting functionality.

Also applies to: 79-79, 105-105, 138-138, 167-167

src/main/java/com/iemr/admin/utils/FilterConfig.java (1)

6-6: LGTM! Clean integration of CORS configuration.

The property injection and constructor parameter passing follow Spring best practices and integrate well with the existing filter registration.

Also applies to: 11-12, 19-20

src/main/java/com/iemr/admin/utils/DynamicCorsFilter.java (1)

17-18: ⚠️ Potential issue

Fix type mismatch in property injection.

The @Value annotation typically injects a String, but the field is declared as String[]. This will likely cause a type conversion error at runtime.

Apply this fix:

-    @Value("${cors.allowed-origins}")
-    private String[] allowedOrigins;
+    @Value("${cors.allowed-origins}")
+    private String allowedOrigins;

Then update the contains check:

-        if (origin != null && Arrays.asList(allowedOrigins).contains(origin)) {
+        if (origin != null && Arrays.asList(allowedOrigins.split(",")).contains(origin.trim())) {

Likely an incorrect or invalid review comment.

src/main/java/com/iemr/admin/utils/JwtUserIdValidationFilter.java (1)

134-143: LGTM! Well-implemented origin pattern matching.

The isOriginAllowed method correctly handles:

  • Null safety checks
  • Comma-separated origin splitting
  • Wildcard pattern matching with proper regex escaping

The implementation is robust and handles edge cases appropriately.

src/main/java/com/iemr/admin/config/CorsConfig.java (1)

8-25:

Details

❓ Verification inconclusive

Verify integration with existing CORS components.

This global CORS configuration will interact with the CORS logic in JwtUserIdValidationFilter and DynamicCorsFilter. Multiple CORS handlers can lead to conflicts or unexpected behavior.

Test the CORS behavior to ensure the multiple CORS configurations work together correctly:


🏁 Script executed:

#!/bin/bash
# Search for all CORS-related configurations to understand the complete setup
echo "=== Finding all CORS configurations ==="
rg -A 5 -B 2 "Access-Control-Allow-Origin"

echo "=== Finding CORS filter registrations ==="
rg -A 10 "FilterRegistrationBean.*Cors|DynamicCorsFilter"

echo "=== Finding WebMvcConfigurer implementations ==="
ast-grep --pattern 'class $_ implements WebMvcConfigurer'

Length of output: 3290


Confirm and consolidate CORS configuration

We currently have:

  • A global CORS config in src/main/java/com/iemr/admin/config/CorsConfig.java (implements WebMvcConfigurer)
  • Per-request CORS header logic in src/main/java/com/iemr/admin/utils/JwtUserIdValidationFilter.java
  • A DynamicCorsFilter class in src/main/java/com/iemr/admin/utils/DynamicCorsFilter.java, but no registration (e.g., @component or FilterRegistrationBean) was found

Multiple CORS handlers can clash or overwrite each other. Please:

β€’ Verify whether DynamicCorsFilter is actually registered in the filter chain (or remove it if unused)
β€’ If you need per-request logic, consider consolidating all CORS header settings in one place (either the global config or a single filter)
β€’ Test end-to-end CORS behavior (OPTIONS/preflight, exposed headers, credentials, etc.) across your allowed–origins list to ensure only the intended handler is setting the Access-Control-Allow-* headers

src/main/java/com/iemr/admin/controller/uptsu/FacilityController.java (4)

61-61: LGTM: Method-level @crossorigin annotation removal.

The removal of the @CrossOrigin annotation from the saveFacilityData method is consistent with the centralized CORS configuration approach.


86-86: LGTM: Method-level @crossorigin annotation removal.

The removal of the @CrossOrigin annotation from the saveCdssDetails method is consistent with the centralized CORS configuration approach.


106-106: LGTM: Method-level @crossorigin annotation removal.

The removal of the @CrossOrigin annotation from the getCdssData method is consistent with the centralized CORS configuration approach.


52-52:

Details

❓ Verification inconclusive

LGTM: Class-level @crossorigin annotation removal.

The removal of the class-level @CrossOrigin annotation aligns with the centralized CORS configuration approach described in the AI summary.

Please verify that the centralized CORS configuration is properly implemented and covers the same origins that were previously allowed by this annotation:


🏁 Script executed:

#!/bin/bash
# Description: Verify that centralized CORS configuration exists and is properly configured

# Check if CorsConfig.java exists and contains proper configuration
fd -t f "CorsConfig.java" | xargs cat

# Check for CORS-related properties in configuration files
fd -t f -e properties | xargs grep -l "cors"

# Verify DynamicCorsFilter implementation
fd -t f "DynamicCorsFilter.java" | xargs cat

Length of output: 2380


🏁 Script executed:

#!/bin/bash
# Description: Verify that the cors.allowed-origins property is defined with the expected values
fd -t f -e properties src/main/environment | xargs grep -n "cors.allowed-origins"

Length of output: 467


🏁 Script executed:

#!/bin/bash
# Re-verify cors.allowed-origins definition in environment properties
find src/main/environment -type f -name '*.properties' -exec grep -Hn 'cors.allowed-origins' {} +

Length of output: 276


Verify that runtime CORS origins match the previous controller-level settings

We’ve confirmed the centralized CORS setup:

β€’ CorsConfig.java registers allowedOrigins (from cors.allowed-origins) for all paths.
β€’ DynamicCorsFilter.java applies the same property at filter time.
β€’ In src/main/environment:

  • admin_ci.properties: cors.allowed-origins=@CORS_ALLOWED_ORIGINS@
  • admin_example.properties: cors.allowed-origins=http://localhost:*

Please ensure that in your CI/production environments the @CORS_ALLOWED_ORIGINS@ value (or corresponding env var) exactly includes every origin that was previously permitted by @CrossOrigin on FacilityController.

private DrugtypeInter drugtypeInter;

@CrossOrigin()

Copy link

Choose a reason for hiding this comment

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

πŸ’‘ Verification agent

🧩 Analysis chain

LGTM! Centralized CORS configuration improves maintainability.

The systematic removal of @CrossOrigin annotations from controller methods is part of a good architectural refactoring that centralizes CORS configuration management.

Please verify that the new global CORS configuration properly handles all endpoints that previously had @CrossOrigin annotations:


🏁 Script executed:

#!/bin/bash
# Description: Verify that global CORS configuration covers all endpoints and that no @CrossOrigin annotations remain

# Check for any remaining @CrossOrigin annotations in controllers
echo "Checking for remaining @CrossOrigin annotations:"
rg -A 2 -B 2 "@CrossOrigin" --type java

# Verify the global CORS configuration exists
echo "Checking for global CORS configuration:"
fd -e java | xargs rg -l "CorsConfig\|addCorsMappings\|WebMvcConfigurer" 

# Check for CORS-related properties
echo "Checking for CORS properties:"
fd -e properties | xargs rg "cors\."

Length of output: 589


Missing Global CORS Configuration Detected

While removing the @CrossOrigin annotations from your controller methods centralizes CORS management, there’s no evidence of a global CORS config class in the codebase. The grep for CorsConfig, addCorsMappings, or WebMvcConfigurer returned no results, so those cors.allowed-origins properties won’t be applied.

Please add or verify a Spring @Configuration classβ€”e.g.:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
  @Value("${cors.allowed-origins}")
  private String[] allowedOrigins;

  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOrigins(allowedOrigins)
            .allowedMethods("*")
            .allowedHeaders("*");
  }
}
  • Ensure this class is picked up by component scanning.
  • Confirm it loads your src/main/environment/*properties settings.
πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/admin/controller/drugtype/DrugtypeController.java
around line 51, the review notes the removal of @CrossOrigin annotations but
missing a global CORS configuration class. To fix this, create a new Spring
@Configuration class implementing WebMvcConfigurer, define allowed origins from
properties using @Value, and override addCorsMappings to apply CORS settings
globally to all endpoints. Ensure this configuration class is in a package
scanned by Spring and that it correctly loads the cors.allowed-origins property
from your environment files.

Comment on lines +44 to +56
String origin = request.getHeader("Origin");
if (origin != null && isOriginAllowed(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, Jwttoken");
response.setHeader("Access-Control-Allow-Credentials", "true");
}

if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
logger.info("OPTIONS request - skipping JWT validation");
response.setStatus(HttpServletResponse.SC_OK);
return;
}
Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Consider separating CORS and JWT validation concerns.

Adding CORS handling to a JWT validation filter mixes two distinct responsibilities. This creates maintenance complexity and duplicates CORS logic already present in DynamicCorsFilter and CorsConfig.

Consider one of these approaches:

  1. Remove CORS logic from this filter and rely on the global CorsConfig
  2. Remove the separate DynamicCorsFilter and keep CORS handling here
  3. Create a dedicated CORS filter that runs before JWT validation

The current approach with multiple CORS handlers may cause conflicts or inconsistent behavior.

πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/admin/utils/JwtUserIdValidationFilter.java around
lines 44 to 56, the code mixes CORS handling with JWT validation, which violates
separation of concerns and risks conflicts with existing CORS filters. To fix
this, remove the CORS-related code from this JWT validation filter and rely
solely on the global CORS configuration (CorsConfig) or a dedicated CORS filter
to handle CORS headers and preflight requests. This will keep JWT validation
focused and avoid duplicate or conflicting CORS logic.

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns(allowedOrigins.split(","))
Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Add null safety for configuration property.

The code directly calls split(",") on allowedOrigins without checking if it's null or empty, which could cause a NullPointerException.

-        .allowedOriginPatterns(allowedOrigins.split(","))
+        .allowedOriginPatterns(allowedOrigins != null ? allowedOrigins.split(",") : new String[0])
πŸ“ 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
.allowedOriginPatterns(allowedOrigins.split(","))
.allowedOriginPatterns(allowedOrigins != null ? allowedOrigins.split(",") : new String[0])
πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/admin/config/CorsConfig.java at line 17, the code
calls split(",") on allowedOrigins without checking for null or empty, risking a
NullPointerException. Add a null and empty check for allowedOrigins before
calling split, and provide a safe default (such as an empty array) if
allowedOrigins is null or empty to ensure null safety.

Comment on lines +16 to +24
registry.addMapping("/**")
.allowedOriginPatterns(allowedOrigins.split(","))
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("Authorization", "Jwttoken") // Explicitly expose headers if needed
.allowCredentials(true)
.maxAge(3600)
;
}
Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Consider more restrictive header allowlist for security.

Using allowedHeaders("*") permits all headers, which could potentially expose sensitive information or allow malicious requests.

Consider specifying only the headers your application actually needs:

         registry.addMapping("/**")
         .allowedOriginPatterns(allowedOrigins.split(","))
                 .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
-                .allowedHeaders("*")
+                .allowedHeaders("Authorization", "Content-Type", "Accept", "Jwttoken", "X-Requested-With")
                 .exposedHeaders("Authorization", "Jwttoken") // Explicitly expose headers if needed
                 .allowCredentials(true)
                 .maxAge(3600)
         ;
πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/admin/config/CorsConfig.java around lines 16 to 24,
the CORS configuration currently allows all headers with allowedHeaders("*"),
which can pose security risks. Replace the wildcard with a specific list of
headers that your application requires, such as "Authorization", "Content-Type",
and any other necessary headers, to restrict access and improve security.

@vishwab1 vishwab1 closed this Jun 17, 2025
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