-
Notifications
You must be signed in to change notification settings - Fork 32
Cors configuration for admin api service #78
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 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 Changes
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
Poem
Note β‘οΈ AI Code Reviews for VS Code, Cursor, WindsurfCodeRabbit 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. β¨ 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: 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
/versionendpointI wasnβt able to locate any global or per-endpoint CORS configuration in the codebase (no
WebMvcConfigurer,CorsFilterbean or@CrossOriginon 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
WebConfigundercom.iemr.admin.config(or your existing config package)
β’ Verify that a browser request to/versionreturns anAccess-Control-Allow-Originheadersrc/main/java/com/iemr/admin/controller/createorder/CareStreamCreateOrderController.java (1)
71-71:β οΈ Potential issueCritical: 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 issueRemove 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 annotationsrc/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 annotationsrc/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 annotationsrc/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 annotationsrc/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@CrossOriginannotation was removed from thepatientIssuemethod to centralize CORS configuration. Please delete the now-unusedimport 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@CrossOriginannotations. Please remove the unusedimport 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@CrossOriginannotations were stripped here; the importimport 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@CrossOriginannotations were removed. The importimport 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
@CrossOriginimport 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
@CrossOriginimport 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
@CrossOriginimport 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
@CrossOriginimport 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@CrossOriginimport
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@CrossOriginimport
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@CrossOriginimport
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@CrossOriginimport
Since all@CrossOriginannotations 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
@CrossOriginimport 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
@CrossOriginimport 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
@CrossOriginimport 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
@CrossOriginimport 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
JwtUserIdValidationFilterand the newCorsConfigclass. 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
CorsConfigfor 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
@CrossOriginimport 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
π 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 addedcors.allowed-origins=http://localhost:*. SpringβsallowedOriginstypically requires explicit ports and doesnβt support wildcard ports; onlyallowedOriginPatternsdoes. Ensure yourCorsConfigusesallowedOriginPatterns(...)(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.javaLength of output: 2307
Centralized CORS configuration validated
Iβve confirmed that:
CorsConfigglobally maps all paths (/**) with the correct allowed origins, methods, headers, exposed headers, credentials flag, and max age.DynamicCorsFilteradditionally sets theAccess-Control-Allow-Originheader 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
/biologicalScreeningDeviceNo
@CrossOriginannotations were found in the entire codebase. Please verify that your global CORS configuration (e.g. in yourWebMvcConfigurer) includes this GET endpointβand any other GET paths such as/versionand/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@CrossOriginannotations removal confirmed
The removal of@CrossOriginannotations 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 thatCorsConfig.javaregisters CORS mappings (includingOPTIONSpreflight) 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.javaLength 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.javaLength of output: 336
Global CORS configuration verified
TheCorsConfig.javafile 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@CrossOriginannotations removal confirmed
The dropped@CrossOriginannotations 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@CrossOriginannotations 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@CrossOriginannotations removal confirmed
Dropping the@CrossOriginannotations 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-originsproperty propagation
This new property enables dynamic CORS origins. Ensure itβs mirrored inadmin_example.propertieswith 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.propertiesLength of output: 122
Verified
cors.allowed-originsin example file
Theadmin_example.propertiesincludescors.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@CrossOriginannotation has been removed from thecreateDrugStrangthendpoint in favor of the centralized CORS configuration provided byCorsConfig.src/main/java/com/iemr/admin/controller/parkingPlace/ParkingPlaceTalukMappingController.java (1)
50-50: Removed method-level CORS annotation
The per-method@CrossOriginhas 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@CrossOriginto centralized CORS viaCorsConfig.src/main/java/com/iemr/admin/controller/vanSpokeMapping/VanSpokeMappingController.java (1)
55-55: Removed method-level CORS annotation
@CrossOriginremoved 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@CrossOriginannotation 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
@CrossOriginannotations 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-originsNo 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
@CrossOriginannotations 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
@CrossOriginannotations 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
@CrossOriginannotations 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
@CrossOriginannotations 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
@CrossOriginannotation 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
@CrossOriginannotation fromLabModuleControlleris 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
@CrossOriginannotations 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 potentialNullPointerExceptionand 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 issueFix type mismatch in property injection.
The
@Valueannotation typically injects aString, but the field is declared asString[]. 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
isOriginAllowedmethod 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
JwtUserIdValidationFilterandDynamicCorsFilter. 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-* headerssrc/main/java/com/iemr/admin/controller/uptsu/FacilityController.java (4)
61-61: LGTM: Method-level @crossorigin annotation removal.The removal of the
@CrossOriginannotation from thesaveFacilityDatamethod is consistent with the centralized CORS configuration approach.
86-86: LGTM: Method-level @crossorigin annotation removal.The removal of the
@CrossOriginannotation from thesaveCdssDetailsmethod is consistent with the centralized CORS configuration approach.
106-106: LGTM: Method-level @crossorigin annotation removal.The removal of the
@CrossOriginannotation from thegetCdssDatamethod 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
@CrossOriginannotation 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 catLength 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(fromcors.allowed-origins) for all paths.
β’ DynamicCorsFilter.java applies the same property at filter time.
β’ Insrc/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@CrossOriginon FacilityController.
| private DrugtypeInter drugtypeInter; | ||
|
|
||
| @CrossOrigin() | ||
|
|
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
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/*propertiessettings.
π€ 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.
| 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; | ||
| } |
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
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:
- Remove CORS logic from this filter and rely on the global
CorsConfig - Remove the separate
DynamicCorsFilterand keep CORS handling here - 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(",")) |
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
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.
| .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.
| registry.addMapping("/**") | ||
| .allowedOriginPatterns(allowedOrigins.split(",")) | ||
| .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") | ||
| .allowedHeaders("*") | ||
| .exposedHeaders("Authorization", "Jwttoken") // Explicitly expose headers if needed | ||
| .allowCredentials(true) | ||
| .maxAge(3600) | ||
| ; | ||
| } |
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
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.



π 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
βΉοΈ 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
Refactor
Chores