Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.iemr.common.identity</groupId>
<artifactId>identity-api</artifactId>
<version>3.4.0</version>
<version>3.6.0</version>

<packaging>war</packaging>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOriginPatterns(
allowedOrigins != null && !allowedOrigins.trim().isEmpty() ? Arrays.stream(allowedOrigins.split(","))
.map(String::trim).filter(s -> !s.isEmpty()).toArray(String[]::new) : new String[0])
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS").allowedHeaders("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedHeaders("Authorization", "Content-Type", "Accept", "Jwttoken",
"serverAuthorization", "ServerAuthorization", "serverauthorization", "Serverauthorization")
.exposedHeaders("Authorization", "Jwttoken").allowCredentials(true).maxAge(3600);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
Expand All @@ -44,11 +45,13 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSyntaxException;
import com.iemr.common.identity.dto.BenIdImportDTO;
import com.iemr.common.identity.dto.BeneficiariesDTO;
import com.iemr.common.identity.dto.BeneficiariesPartialDTO;
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/iemr/common/identity/domain/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@
import jakarta.persistence.Table;
import lombok.Data;
@Entity
@Table(name = "m_User")
@JsonIgnoreProperties(ignoreUnknown = true)
@Table(name = "m_User",schema = "db_iemr")
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public class BenIdImportDTO {
private BigInteger beneficiaryId;
private String createdBy;
private Timestamp createdDate;
private BigInteger vanID;

public BigInteger getBenRegId() {
return benRegId;
Expand Down Expand Up @@ -63,4 +64,11 @@ public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}

public void setVanID(BigInteger vanID) {
this.vanID = vanID;
}

public BigInteger getVanID() {
return vanID;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public interface BenIdImportMapper {
@Mapping(source = "beneficiaryId", target = "beneficiaryID")
@Mapping(source = "createdBy", target = "createdBy")
@Mapping(source = "createdDate", target = "createdDate")
@Mapping(source = "vanID", target = "vanID")
MBeneficiaryregidmapping benIdImportDTOToMBeneficiaryregidmapping(BenIdImportDTO dto);

ArrayList<MBeneficiaryregidmapping> benIdImportDTOToMBeneficiaryregidmappings(List<BenIdImportDTO> dto);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1130,6 +1130,37 @@ public BeneficiaryCreateResp createIdentity(IdentityDTO identity) {

logger.info("IdentityService.createIdentity - saving Contacts");
MBeneficiarycontact mContc = identityDTOToMBeneficiarycontact(identity);

if (mContc.getEmergencyContactNum() != null) {
mContc.setEmergencyContactNum(cleanPhoneNumber(mContc.getEmergencyContactNum()));
}

if (mContc.getPhoneNum1() != null) {
mContc.setPhoneNum1(cleanPhoneNumber(mContc.getPhoneNum1()));
}

if (mContc.getPhoneNum2() != null) {
mContc.setPhoneNum2(cleanPhoneNumber(mContc.getPhoneNum2()));
}
if (mContc.getPhoneNum3() != null) {
mContc.setPhoneNum3(cleanPhoneNumber(mContc.getPhoneNum3()));
}

if (mContc.getPhoneNum4() != null) {
mContc.setPhoneNum4(cleanPhoneNumber(mContc.getPhoneNum4()));
}
if (mContc.getPhoneNum5() != null) {
mContc.setPhoneNum5(cleanPhoneNumber(mContc.getPhoneNum5()));
}
if (mContc.getPreferredSMSPhoneNum() != null) {
mContc.setPreferredSMSPhoneNum(cleanPhoneNumber(mContc.getPreferredSMSPhoneNum()));
} if (mContc.getPreferredPhoneNum() != null) {
mContc.setPreferredPhoneNum(cleanPhoneNumber(mContc.getPreferredPhoneNum()));
}




// MBeneficiarycontact mContc =
// mapper.identityDTOToMBeneficiarycontact(identity);
if (mContc.getCreatedDate() == null) {
Expand Down Expand Up @@ -1302,7 +1333,22 @@ public BeneficiaryCreateResp createIdentity(IdentityDTO identity) {
logger.info("IdentityService.createIdentity - end. id = " + benMapping.getBenMapId());
return partialMapper.mBeneficiarymappingToBeneficiaryCreateResp(benMapping);
}

private String cleanPhoneNumber(String phoneNumber) {
if (phoneNumber == null || phoneNumber.trim().isEmpty()) {
return phoneNumber;
}

// Remove +91 prefix
String cleaned = phoneNumber.trim();
if (cleaned.startsWith("+91")) {
cleaned = cleaned.substring(3);
} else if (cleaned.startsWith("91") && cleaned.length() == 12) {
// Handle case where + is already removed but 91 remains
cleaned = cleaned.substring(2);
}

return cleaned.trim();
}
private MBeneficiarydetail convertIdentityDTOToMBeneficiarydetail(IdentityDTO dto) {
MBeneficiarydetail beneficiarydetail = new MBeneficiarydetail();
beneficiarydetail.setAreaId(dto.getAreaId());
Expand Down Expand Up @@ -1751,14 +1797,18 @@ public int importBenIdToLocalServer(List<BenIdImportDTO> benIdImportDTOList) {
+ " Provisioned, CreatedDate, CreatedBy, Reserved) VALUES (?,?,?,?,?,?) ";
logger.info("query : " + query);
for (MBeneficiaryregidmapping obj : mBeneficiaryregidmappingList) {
objArr = new Object[6];
logger.info("inside for check->",obj);

logger.info("In for loop of importBenIdToLocalServer"+obj.getVanID());
Comment on lines +1800 to +1802
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Fix malformed logger statements.

Lines 1800 and 1802 have syntax errors in the logger calls:

  • Line 1800: logger.info("inside for check->",obj); - comma should be + for concatenation
  • Line 1802: logger.info("In for loop of importBenIdToLocalServer"+obj.getVanID()); - missing space before concatenation

These will cause compilation errors or unexpected log output.

🔧 Fix logger syntax
-				logger.info("inside for check->",obj);
+				logger.info("inside for check-> {}", obj);

-				logger.info("In for loop of importBenIdToLocalServer"+obj.getVanID());
+				logger.info("In for loop of importBenIdToLocalServer: {}", obj.getVanID());
🤖 Prompt for AI Agents
In @src/main/java/com/iemr/common/identity/service/IdentityService.java around
lines 1800 - 1802, The logger calls are malformed: replace the comma usage and
missing spacing by concatenating strings properly; update the call using the
logger instance (logger.info) where the first call currently reads
logger.info("inside for check->",obj) to concatenate the object (or its
toString) to the message, and adjust the second call inside
importBenIdToLocalServer that currently does logger.info("In for loop of
importBenIdToLocalServer"+obj.getVanID()) to include a separating space before
the concatenated obj.getVanID(); ensure both use a single string argument (or
use parameterized logging if available) and reference the same logger and
obj.getVanID() symbols when making the fix.

objArr = new Object[7];

objArr[0] = obj.getBenRegId();
objArr[1] = obj.getBeneficiaryID();
objArr[2] = false;
objArr[3] = obj.getCreatedDate();
objArr[4] = obj.getCreatedBy();
objArr[5] = false;
objArr[6] = obj.getVanID();

dataList.add(objArr);
logger.info("regid :" + obj.getBenRegId() + " - benid :" + obj.getBeneficiaryID());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,34 +97,58 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo
}
}

/**
* Handles CORS headers by validating the origin and setting appropriate
* headers.
* AMM-1927: Only sets CORS headers if the origin is from an allowed domain.
*
* @param request The HTTP request
* @param response The HTTP response
*/
private void handleCorsHeaders(HttpServletRequest request, HttpServletResponse response) {
String origin = request.getHeader("Origin");

logger.debug("Incoming Origin: {}", origin);
logger.debug("Allowed Origins Configured: {}", allowedOrigins);

if (origin != null && isOriginAllowed(origin)) {
// Only set CORS headers if the origin is allowed
if (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, Jwttoken");
response.setHeader("Vary", "Origin");
response.setHeader("Access-Control-Allow-Credentials", "true");

logger.debug("CORS headers set for allowed origin: {}", origin);
} else {
logger.warn("Origin [{}] is NOT allowed. CORS headers NOT added.", origin);
}

}

/**
* Validates if the request origin is in the allowed origins list.
* AMM-1927: Aligns with Admin-API implementation for consistent origin
* validation.
*
* @param origin The Origin header value from the HTTP request
* @return true if the origin is allowed, false otherwise
*/
private boolean isOriginAllowed(String origin) {
if (origin == null || allowedOrigins == null || allowedOrigins.trim().isEmpty()) {
logger.warn("No allowed origins configured or origin is null");
// Null or empty origin is not allowed
if (origin == null || origin.isEmpty()) {
logger.debug("Origin is null or empty");
return false;
}

// Check if allowed origins are configured
if (allowedOrigins == null || allowedOrigins.trim().isEmpty()) {
logger.warn("No allowed origins configured");
return false;
}

return Arrays.stream(allowedOrigins.split(",")).map(String::trim).anyMatch(pattern -> {
String regex = pattern.replace(".", "\\.").replace("*", ".*").replace("http://localhost:.*",
"http://localhost:\\d+"); // special case for wildcard port
String regex = pattern.replace(".", "\\.").replace("*", ".*");

boolean matched = origin.matches(regex);
return matched;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,14 @@
package com.iemr.common.identity.utils.http;


import java.util.Arrays;

import javax.ws.rs.core.MediaType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
Expand All @@ -42,6 +45,9 @@ public class HTTPRequestInterceptor implements HandlerInterceptor {

Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

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

private SessionObject sessionObject;

@Autowired
Expand Down Expand Up @@ -84,8 +90,13 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons
response.getOutputStream().print(output.toString());
response.setContentType(MediaType.APPLICATION_JSON);
response.setContentLength(output.toString().length());
response.setHeader("Access-Control-Allow-Origin", "*");
status = false;
String origin = request.getHeader("Origin");
if (origin != null && isOriginAllowed(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Credentials", "true");
} else if (origin != null) {
logger.warn("CORS headers NOT added for error response | Unauthorized origin: {}", origin);
} status = false;
Comment on lines +93 to +99
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fix formatting: missing newline before statement.

Line 99 has } status = false; which appears to be a formatting issue. The closing brace and the statement should be on separate lines for better readability.

🔧 Proposed formatting fix
				} else if (origin != null) {
					logger.warn("CORS headers NOT added for error response | Unauthorized origin: {}", origin);
-				}				status = false;
+				}
+				status = false;
📝 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
String origin = request.getHeader("Origin");
if (origin != null && isOriginAllowed(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Credentials", "true");
} else if (origin != null) {
logger.warn("CORS headers NOT added for error response | Unauthorized origin: {}", origin);
} status = false;
String origin = request.getHeader("Origin");
if (origin != null && isOriginAllowed(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Credentials", "true");
} else if (origin != null) {
logger.warn("CORS headers NOT added for error response | Unauthorized origin: {}", origin);
}
status = false;
🤖 Prompt for AI Agents
In
@src/main/java/com/iemr/common/identity/utils/http/HTTPRequestInterceptor.java
around lines 93 - 99, In HTTPRequestInterceptor (the Origin header handling
block), the closing brace and the subsequent statement are merged (`}				status
= false;`); separate them by placing `status = false;` on its own properly
indented line immediately after the closing brace of the Origin-handling if/else
so the block reads with the brace on its own line followed by `status = false;`.

}
}
return status;
Expand Down Expand Up @@ -115,4 +126,19 @@ public void afterCompletion(HttpServletRequest request, HttpServletResponse resp
throws Exception {
logger.debug("In afterCompletion Request Completed");
}

private boolean isOriginAllowed(String origin) {
if (origin == null || allowedOrigins == null || allowedOrigins.trim().isEmpty()) {
return false;
}

return Arrays.stream(allowedOrigins.split(","))
.map(String::trim)
.anyMatch(pattern -> {
String regex = pattern
.replace(".", "\\.")
.replace("*", ".*");
return origin.matches(regex);
});
}
}
Loading