Skip to content
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

jwt implementation changes #53

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
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
40 changes: 29 additions & 11 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>co.elastic.logging</groupId>
<artifactId>logback-ecs-encoder</artifactId>
<version>1.3.2</version>
<dependency>
<groupId>co.elastic.logging</groupId>
<artifactId>logback-ecs-encoder</artifactId>
<version>1.3.2</version>
</dependency>

<dependency>
Expand Down Expand Up @@ -189,17 +189,15 @@
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

<!--
https://mvnrepository.com/artifact/ca.uhn.hapi.fhir/hapi-fhir-structures-r4 -->
<!-- https://mvnrepository.com/artifact/ca.uhn.hapi.fhir/hapi-fhir-structures-r4 -->
<dependency>
<groupId>ca.uhn.hapi.fhir</groupId>
<artifactId>hapi-fhir-structures-r4</artifactId>
<version>7.0.2</version>
</dependency>


<!--
https://mvnrepository.com/artifact/ca.uhn.hapi.fhir/org.hl7.fhir.utilities -->
<!-- https://mvnrepository.com/artifact/ca.uhn.hapi.fhir/org.hl7.fhir.utilities -->
<dependency>
<groupId>ca.uhn.hapi.fhir</groupId>
<artifactId>org.hl7.fhir.utilities</artifactId>
Expand Down Expand Up @@ -235,6 +233,27 @@
<artifactId>json-path</artifactId>
<version>2.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-api -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.12.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-impl -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.12.6</version>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-jackson -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.12.6</version>
<scope>runtime</scope>
</dependency>


</dependencies>

Expand All @@ -250,7 +269,7 @@
<format>HTML</format>
<nvdApiServerId>nvd</nvdApiServerId>
</configuration>

</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
Expand Down Expand Up @@ -329,8 +348,7 @@
${target-properties} and
${source-properties}
</echo>
<concat destfile="${target-properties}"
append="yes"
<concat destfile="${target-properties}" append="yes"
force="yes">
<fileset file="${source-properties}">
</fileset>
Expand Down
3 changes: 2 additions & 1 deletion src/main/environment/common_ci.properties
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,5 @@ logging.level.com.iemr=DEBUG
logging.level.org.springframework=INFO

#ELK logging file name
[email protected]_API_LOGGING_FILE_NAME@
[email protected]_API_LOGGING_FILE_NAME@
[email protected]_SECRET_KEY@
1 change: 1 addition & 0 deletions src/main/environment/common_dev.properties
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,4 @@ logging.level.org.springframework.web=INFO
logging.level.org.hibernate=INFO
logging.level.com.iemr=DEBUG
logging.level.org.springframework=INFO
jwt.secret=
1 change: 1 addition & 0 deletions src/main/environment/common_example.properties
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,4 @@ logging.level.org.springframework.web=INFO
logging.level.org.hibernate=INFO
logging.level.com.iemr=DEBUG
logging.level.org.springframework=INFO
jwt.secret=
1 change: 1 addition & 0 deletions src/main/environment/common_test.properties
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,4 @@ logging.level.org.springframework.web=INFO
logging.level.org.hibernate=INFO
logging.level.com.iemr=DEBUG
logging.level.org.springframework=INFO
jwt.secret=
21 changes: 21 additions & 0 deletions src/main/java/com/wipro/fhir/FhirApiApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,32 @@
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.wipro.fhir.data.users.User;

@SpringBootApplication
public class FhirApiApplication {

public static void main(String[] args) {
SpringApplication.run(FhirApiApplication.class, args);
}

@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);

// Use StringRedisSerializer for keys (userId)
template.setKeySerializer(new StringRedisSerializer());

// Use Jackson2JsonRedisSerializer for values (Users objects)
Jackson2JsonRedisSerializer<User> serializer = new Jackson2JsonRedisSerializer<>(User.class);
template.setValueSerializer(serializer);

return template;
}
}
40 changes: 40 additions & 0 deletions src/main/java/com/wipro/fhir/config/RedisConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.wipro.fhir.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.session.data.redis.config.ConfigureRedisAction;

import com.wipro.fhir.data.users.User;

@Configuration
@EnableCaching
public class RedisConfig {

@Bean
public ConfigureRedisAction configureRedisAction() {
return ConfigureRedisAction.NO_OP;
}

@Bean
public RedisTemplate<String, User> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, User> template = new RedisTemplate<>();
template.setConnectionFactory(factory);

// Use StringRedisSerializer for keys (userId)
template.setKeySerializer(new StringRedisSerializer());

// Use Jackson2JsonRedisSerializer for values (Users objects)
Jackson2JsonRedisSerializer<User> serializer = new Jackson2JsonRedisSerializer<>(User.class);
template.setValueSerializer(serializer);

return template;
}

}


28 changes: 28 additions & 0 deletions src/main/java/com/wipro/fhir/data/users/User.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.wipro.fhir.data.users;

import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Data;

@Entity
@Table(name = "m_user")
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "UserID")
private Long userID;
@Column(name = "userName")
private String userName;
Comment on lines +22 to +25
Copy link
Contributor

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Standardize column naming convention and add constraints

The column naming is inconsistent (UserID vs userName). Also, the userName field lacks necessary constraints for a authentication-related field.

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
-@Column(name = "UserID")
+@Column(name = "user_id")
 private Long userID;
-@Column(name = "userName")
+@Column(name = "user_name", unique = true, nullable = false, length = 50)
+@Index(name = "idx_user_name")
 private String userName;

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +24 to +25
Copy link
Contributor

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Add validation and uniqueness constraints
Since this is user data that interfaces with authentication, consider adding constraints (e.g., @notblank, length limits) on userName. Also, a uniqueness constraint at the DB level can help avoid duplicate user names.

@Column(name = "Deleted", insertable = false, updatable = true)
private Boolean deleted;
}
60 changes: 31 additions & 29 deletions src/main/java/com/wipro/fhir/service/common/CommonServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
import com.wipro.fhir.data.patient_data_handler.PatientDemographicModel_NDHM_Patient_Profile;
import com.wipro.fhir.data.request_handler.PatientEligibleForResourceCreation;
import com.wipro.fhir.data.request_handler.ResourceRequestHandler;
import com.wipro.fhir.data.users.User;
import com.wipro.fhir.repo.common.PatientEligibleForResourceCreationRepo;
import com.wipro.fhir.repo.healthID.BenHealthIDMappingRepo;
import com.wipro.fhir.repo.mongo.amrit_resource.AMRIT_ResourceMongoRepo;
Expand Down Expand Up @@ -96,16 +97,16 @@ public class CommonServiceImpl implements CommonService {

@Value("${patient-search-page-size}")
private String patient_search_page_size;

@Value("${abhaMode}")
private String abhaMode;

private static String authKey;
private UUID uuid;

//public static String NDHM_AUTH_TOKEN;
//public static Long NDHM_TOKEN_EXP;
//public static String NDHM_OTP_TOKEN;
// public static String NDHM_AUTH_TOKEN;
// public static Long NDHM_TOKEN_EXP;
// public static String NDHM_OTP_TOKEN;

@Value("${clientID}")
private String clientID;
Expand All @@ -127,7 +128,6 @@ public class CommonServiceImpl implements CommonService {
private APIChannel aPIChannel;
@Autowired
private AMRIT_ResourceMongoRepo aMRIT_ResourceMongoRepo;


@Autowired
private PatientCareContextsMongoRepo patientCareContextsMongoRepo;
Expand All @@ -148,7 +148,7 @@ public class CommonServiceImpl implements CommonService {

@Autowired
private PatientDataGatewayService patientDataGatewayService;

@Autowired
private MongoTemplate mongoTemplate;

Expand All @@ -159,7 +159,7 @@ public class CommonServiceImpl implements CommonService {
private PatientDemographic patientDemographic;
@Autowired
private Common_NDHMService common_NDHMService;

@Autowired
private BenHealthIDMappingRepo benHealthIDMappingRepo;

Expand All @@ -168,7 +168,8 @@ public String processResourceOperation() throws FHIRException {
String response = null;
// list of patient eligible for resource creation
List<PatientEligibleForResourceCreation> pList = getPatientListForResourceEligible();
logger.info("No of records available to create FHIR in last 2 dagetPatientListForResourceEligibleys : " + pList.size());
logger.info("No of records available to create FHIR in last 2 dagetPatientListForResourceEligibleys : "
+ pList.size());
ResourceRequestHandler resourceRequestHandler;
for (PatientEligibleForResourceCreation p : pList) {

Expand Down Expand Up @@ -196,10 +197,11 @@ public String processResourceOperation() throws FHIRException {
if (patientDemographicOBJ.getPreferredPhoneNo() != null)
sendAbdmAdvSMS(patientDemographicOBJ.getPreferredPhoneNo());
else
throw new FHIRException("Advertisement sms could not be sent as beneficiary phone no not found");
}
else
throw new FHIRException("Beneficiary not found, benRegId = " +resourceRequestHandler.getBeneficiaryRegID());
throw new FHIRException(
"Advertisement sms could not be sent as beneficiary phone no not found");
} else
throw new FHIRException(
"Beneficiary not found, benRegId = " + resourceRequestHandler.getBeneficiaryRegID());

} catch (Exception e) {
logger.error(e.getMessage());
Expand Down Expand Up @@ -324,28 +326,28 @@ public int addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRes
// get benid
// if (benRegID != null)
// benID = benHealthIDMappingRepo.getBenID(benRegID);
// fetch abdm facility id
logger.info("********t_benvisistData fetch request pvisit data :" , pVisit);

// fetch abdm facility id
logger.info("********t_benvisistData fetch request pvisit data :", pVisit);

List<Object[]> res = benHealthIDMappingRepo.getAbdmFacilityAndlinkedDate(pVisit.getVisitCode());

// check care context record in mongo against beneficiaryID
ArrayList<CareContexts> ccList = new ArrayList<>();

CareContexts cc = new CareContexts();

logger.info("********t_benvisistData fetch response : {}", res);
cc.setReferenceNumber(pVisit.getVisitCode() != null ? pVisit.getVisitCode().toString() : null);
cc.setDisplay(pVisit.getVisitCategory() != null ? pVisit.getVisitCategory().toString() : null);
cc.setDisplay(pVisit.getVisitCategory() != null ? pVisit.getVisitCategory().toString() : null);
Object[] resData = null;
if (res.get(0) != null) {
resData = res.get(0);
cc.setAbdmFacilityId(resData[0] != null ? resData[0].toString() : null );
cc.setCareContextLinkedDate(resData[1] != null ? resData[1].toString() : null);
cc.setAbdmFacilityId(resData[0] != null ? resData[0].toString() : null);
cc.setCareContextLinkedDate(resData[1] != null ? resData[1].toString() : null);
}
logger.info("********data to be saved in mongo :" , cc);

logger.info("********data to be saved in mongo :", cc);
PatientCareContexts pcc;
PatientCareContexts resultSet;

Expand All @@ -357,7 +359,7 @@ public int addCareContextToMongo(PatientDemographic pDemo, PatientEligibleForRes
ccList.add(cc);
pcc.setCareContextsList(ccList);
resultSet = patientCareContextsMongoRepo.save(pcc);

} else {
pcc = new PatientCareContexts();
pcc.setCaseReferenceNumber(pDemo.getBeneficiaryID().toString());
Expand Down Expand Up @@ -423,15 +425,15 @@ public String ndhmUserAuthenticate() throws FHIRException {
JsonParser jsnParser = new JsonParser();
JsonElement jsnElmnt = jsnParser.parse(responseStrLogin);
jsnOBJ = jsnElmnt.getAsJsonObject();
//NDHM_AUTH_TOKEN = "Bearer" + " " + jsnOBJ.get("accessToken").getAsString();
// NDHM_AUTH_TOKEN = "Bearer" + " " + jsnOBJ.get("accessToken").getAsString();
Integer expiry = jsnOBJ.get("expiresIn").getAsInt();
double time = expiry / 60;
Date date = new Date();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
Calendar ndhmCalendar = Calendar.getInstance();
ndhmCalendar.setTime(sqlDate);
ndhmCalendar.add(Calendar.MINUTE, (int) time);

res = "success";
} else
res = "Error while accessing authenticate API";
Expand Down Expand Up @@ -477,7 +479,7 @@ public List<TempCollection> fetchTempResourceFromMongo(ResourceRequestHandler re
* @author SH20094090
* @return
*
* get the UUID and isoTimestamp for NDMH API's
* get the UUID and isoTimestamp for NDMH API's
*/
@Deprecated
@Override
Expand Down Expand Up @@ -541,7 +543,7 @@ public String getMongoNDHMResponse(String requestID) throws FHIRException {
* @param reqID
* @return
*
* hitting MongoDB
* hitting MongoDB
*/
@Deprecated
NDHMResponse getResponseMongo(String reqID) {
Expand Down Expand Up @@ -628,8 +630,8 @@ public void sendAbdmAdvSMS(String phone) throws FHIRException {
SMSNotify smsNotify = new SMSNotify(obj.getRequestId(), obj.getTimestamp(), notification);
String requestOBJ = new Gson().toJson(smsNotify);
logger.info("NDHM_FHIR Generate Notify SMS request Obj: " + requestOBJ);
if(abhaMode !=null && !(abhaMode.equalsIgnoreCase("abdm") || abhaMode.equalsIgnoreCase("sbx")))
abhaMode="sbx";
if (abhaMode != null && !(abhaMode.equalsIgnoreCase("abdm") || abhaMode.equalsIgnoreCase("sbx")))
abhaMode = "sbx";
HttpHeaders headers = common_NDHMService.getHeaders(ndhmAuthToken, abhaMode);
ResponseEntity<String> responseEntity = httpUtils.postWithResponseEntity(generateABDM_NotifySMS, requestOBJ,
headers);
Expand Down
Loading