-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathJwtAuthenticationUtil.java
More file actions
132 lines (104 loc) · 3.96 KB
/
JwtAuthenticationUtil.java
File metadata and controls
132 lines (104 loc) · 3.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package com.iemr.admin.utils;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import com.iemr.admin.data.user.M_User;
import com.iemr.admin.repository.user.UserLoginRepo;
import com.iemr.admin.utils.exception.IEMRException;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
@Component
public class JwtAuthenticationUtil {
@Autowired
private CookieUtil cookieUtil;
@Autowired
private JwtUtil jwtUtil;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private UserLoginRepo userLoginRepo;
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
public JwtAuthenticationUtil(CookieUtil cookieUtil, JwtUtil jwtUtil) {
this.cookieUtil = cookieUtil;
this.jwtUtil = jwtUtil;
}
public ResponseEntity<String> validateJwtToken(HttpServletRequest request) {
Optional<String> jwtTokenOpt = cookieUtil.getCookieValue(request, "Jwttoken");
if (jwtTokenOpt.isEmpty()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body("Error 401: Unauthorized - JWT Token is not set!");
}
String jwtToken = jwtTokenOpt.get();
// Validate the token
Claims claims = jwtUtil.validateToken(jwtToken);
if (claims == null) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Error 401: Unauthorized - Invalid JWT Token!");
}
// Extract username from token
String usernameFromToken = claims.getSubject();
if (usernameFromToken == null || usernameFromToken.isEmpty()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body("Error 401: Unauthorized - Username is missing!");
}
// Return the username if valid
return ResponseEntity.ok(usernameFromToken);
}
public boolean validateUserIdAndJwtToken(String jwtToken) throws IEMRException {
try {
// Validate JWT token and extract claims
Claims claims = jwtUtil.validateToken(jwtToken);
if (claims == null) {
throw new IEMRException("Invalid JWT token.");
}
String userId = claims.get("userId", String.class);
// Check if user data is present in Redis
M_User 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.");
}
return true; // Valid userId and JWT token
} catch (Exception e) {
logger.error("Validation failed: " + e.getMessage(), e);
throw new IEMRException("Validation error: " + e.getMessage(), e);
}
}
private M_User getUserFromCache(String userId) {
String redisKey = "user_" + userId; // The Redis key format
M_User user = (M_User) redisTemplate.opsForValue().get(redisKey);
if (user == null) {
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 M_User 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
M_User user = userLoginRepo.getUserByUserID(Long.parseLong(userId));
if (user != null) {
M_User userHash = new M_User();
userHash.setUserID(user.getUserID());
userHash.setUserName(user.getUserName());
// Cache the minimal user in Redis for future requests (cache for 30 minutes)
redisTemplate.opsForValue().set(redisKey, userHash, 30, TimeUnit.MINUTES);
// Log that the user has been stored in Redis
logger.info("User stored in Redis with key: " + redisKey);
return user;
} else {
logger.warn("User not found for userId: " + userId);
}
return null;
}
}