Skip to content

Commit

Permalink
Formatting and dependency upgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
IN40068837 authored and IN40068837 committed Dec 5, 2024
1 parent fbe6878 commit 54236e3
Show file tree
Hide file tree
Showing 6 changed files with 241 additions and 271 deletions.
48 changes: 20 additions & 28 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,21 @@
<org.mapstruct.version>1.2.0.Final</org.mapstruct.version>
</properties>
<dependencies>
<!--
https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>3.2.2</version>
</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>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<version>3.2.2</version>
</dependency>-->
<!--<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId>
<version>3.2.2</version> </dependency> -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
Expand Down Expand Up @@ -101,8 +97,7 @@
<version>8.2.0</version>
</dependency>

<!--
https://mvnrepository.com/artifact/jakarta.persistence/jakarta.persistence-api -->
<!-- https://mvnrepository.com/artifact/jakarta.persistence/jakarta.persistence-api -->
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
Expand Down Expand Up @@ -169,15 +164,14 @@
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.5</version>
<!-- <exclusions>-->
<!-- <exclusion>-->
<!-- <groupId>org.apache.commons</groupId>-->
<!-- <artifactId>commons-compress</artifactId>-->
<!-- </exclusion>-->
<!-- </exclusions>-->
<!-- <exclusions> -->
<!-- <exclusion> -->
<!-- <groupId>org.apache.commons</groupId> -->
<!-- <artifactId>commons-compress</artifactId> -->
<!-- </exclusion> -->
<!-- </exclusions> -->
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
Expand Down Expand Up @@ -219,8 +213,7 @@
<artifactId>jackson-datatype-joda</artifactId>
<version>2.17.0</version>
</dependency>
<!--
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
Expand All @@ -236,20 +229,20 @@
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
<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.11.5</version>
<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.11.5</version>
<version>0.12.6</version>
<scope>runtime</scope>
</dependency>
</dependencies>
Expand Down Expand Up @@ -335,8 +328,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
56 changes: 26 additions & 30 deletions src/main/java/com/iemr/ecd/utils/mapper/CookieUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,34 +12,30 @@
@Service
public class CookieUtil {

public Optional<String> getCookieValue(HttpServletRequest request, String cookieName) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookieName.equals(cookie.getName())) {
return Optional.of(cookie.getValue());
}
}
}
return Optional.empty();
}

public void addJwtTokenToCookie(String Jwttoken, HttpServletResponse response) {
// Create a new cookie with the JWT token
Cookie cookie = new Cookie("Jwttoken", Jwttoken);
cookie.setHttpOnly(true); // Prevent JavaScript access for security
cookie.setSecure(true); // Ensure the cookie is sent only over HTTPS
cookie.setMaxAge(60 * 60 * 24); // 1 day expiration time
cookie.setPath("/"); // Make the cookie available for the entire application
response.addCookie(cookie); // Add the cookie to the response
}

public String getJwtTokenFromCookie(HttpServletRequest request) {
return Arrays.stream(request.getCookies())
.filter(cookie -> "Jwttoken".equals(cookie.getName()))
.map(Cookie::getValue)
.findFirst()
.orElse(null);
}
public Optional<String> getCookieValue(HttpServletRequest request, String cookieName) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookieName.equals(cookie.getName())) {
return Optional.of(cookie.getValue());
}
}
}
return Optional.empty();
}

public void addJwtTokenToCookie(String Jwttoken, HttpServletResponse response) {
// Create a new cookie with the JWT token
Cookie cookie = new Cookie("Jwttoken", Jwttoken);
cookie.setHttpOnly(true); // Prevent JavaScript access for security
cookie.setSecure(true); // Ensure the cookie is sent only over HTTPS
cookie.setMaxAge(60 * 60 * 24); // 1 day expiration time
cookie.setPath("/"); // Make the cookie available for the entire application
response.addCookie(cookie); // Add the cookie to the response
}

public String getJwtTokenFromCookie(HttpServletRequest request) {
return Arrays.stream(request.getCookies()).filter(cookie -> "Jwttoken".equals(cookie.getName()))
.map(Cookie::getValue).findFirst().orElse(null);
}
}

16 changes: 8 additions & 8 deletions src/main/java/com/iemr/ecd/utils/mapper/FilterConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class FilterConfig {

@Bean
public FilterRegistrationBean<JwtUserIdValidationFilter> jwtUserIdValidationFilter(JwtAuthenticationUtil jwtAuthenticationUtil) {
FilterRegistrationBean<JwtUserIdValidationFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new JwtUserIdValidationFilter(jwtAuthenticationUtil));
registrationBean.addUrlPatterns("/*"); // Apply filter to all API endpoints
return registrationBean;
}
public FilterRegistrationBean<JwtUserIdValidationFilter> jwtUserIdValidationFilter(
JwtAuthenticationUtil jwtAuthenticationUtil) {
FilterRegistrationBean<JwtUserIdValidationFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new JwtUserIdValidationFilter(jwtAuthenticationUtil));
registrationBean.addUrlPatterns("/*"); // Apply filter to all API endpoints
return registrationBean;
}

}
139 changes: 69 additions & 70 deletions src/main/java/com/iemr/ecd/utils/mapper/JwtAuthenticationUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,74 +19,73 @@
@Component
public class JwtAuthenticationUtil {

@Autowired
private final CookieUtil cookieUtil;
@Autowired
private final JwtUtil jwtUtil;
@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 Exception {
try {
// Validate JWT token and extract claims
Claims claims = jwtUtil.validateToken(jwtToken);

if (claims == null) {
throw new ECDException("Invalid JWT token.");
}

String userId = claims.get("userId", String.class);
String tokenUsername = jwtUtil.extractUsername(jwtToken);

// Fetch user based on userId from the database or cache
Users user = userLoginRepo.getUserByUserID(Long.parseLong(userId));
if (user == null) {
throw new ECDException("Invalid User ID.");
}

// Check if the token's username matches the user retrieved by userId
if (!user.getUserName().equalsIgnoreCase(tokenUsername)) {
throw new ECDException("JWT token and User ID mismatch.");
}

return true; // Valid userId and JWT token
} catch (Exception e) {
logger.error("Validation failed: " + e.getMessage(), e);
throw new Exception("Validation error: " + e.getMessage(), e);
}
}
@Autowired
private final CookieUtil cookieUtil;
@Autowired
private final JwtUtil jwtUtil;
@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 Exception {
try {
// Validate JWT token and extract claims
Claims claims = jwtUtil.validateToken(jwtToken);

if (claims == null) {
throw new ECDException("Invalid JWT token.");
}

String userId = claims.get("userId", String.class);
String tokenUsername = jwtUtil.extractUsername(jwtToken);

// Fetch user based on userId from the database or cache
Users user = userLoginRepo.getUserByUserID(Long.parseLong(userId));
if (user == null) {
throw new ECDException("Invalid User ID.");
}

// Check if the token's username matches the user retrieved by userId
if (!user.getUserName().equalsIgnoreCase(tokenUsername)) {
throw new ECDException("JWT token and User ID mismatch.");
}

return true; // Valid userId and JWT token
} catch (Exception e) {
logger.error("Validation failed: " + e.getMessage(), e);
throw new Exception("Validation error: " + e.getMessage(), e);
}
}
}

Loading

0 comments on commit 54236e3

Please sign in to comment.