diff --git a/src/main/java/com/iemr/hwc/utils/JwtAuthenticationUtil.java b/src/main/java/com/iemr/hwc/utils/JwtAuthenticationUtil.java index f4579bfd..80908718 100644 --- a/src/main/java/com/iemr/hwc/utils/JwtAuthenticationUtil.java +++ b/src/main/java/com/iemr/hwc/utils/JwtAuthenticationUtil.java @@ -1,6 +1,7 @@ package com.iemr.hwc.utils; import java.util.Optional; +import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,6 +27,8 @@ public class JwtAuthenticationUtil { private JwtUtil jwtUtil; @Autowired private RedisTemplate redisTemplate; + @Autowired + private UserLoginRepo userLoginRepo; private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); public JwtAuthenticationUtil(CookieUtil cookieUtil, JwtUtil jwtUtil) { @@ -73,6 +76,10 @@ public boolean validateUserIdAndJwtToken(String jwtToken) throws IEMRException { // Check if user data is present in Redis Users user = getUserFromCache(userId); + if (user == null) { + // If not in Redis, fetch from DB and cache the result + user = fetchUserFromDB(userId); + } if (user == null) { throw new IEMRException("Invalid User ID."); } @@ -89,11 +96,31 @@ private Users getUserFromCache(String userId) { Users user = (Users) redisTemplate.opsForValue().get(redisKey); if (user == null) { - logger.warn("User not found in Redis."); + logger.warn("User not found in Redis. Will try to fetch from DB."); } else { logger.info("User fetched successfully from Redis."); } return user; // Returns null if not found } + + private Users fetchUserFromDB(String userId) { + // This method will only be called if the user is not found in Redis. + String redisKey = "user_" + userId; // Redis key format + + // Fetch user from DB + Users user = userLoginRepo.getUserByUserID(Long.parseLong(userId)); + + if (user != null) { + // Cache the user in Redis for future requests (cache for 30 minutes) + redisTemplate.opsForValue().set(redisKey, user, 30, TimeUnit.MINUTES); + + // Log that the user has been stored in Redis + logger.info("User stored in Redis with key: " + redisKey); + } else { + logger.warn("User not found for userId: " + userId); + } + + return user; + } }