Skip to content

Commit

Permalink
Updating to latest Spring boot, other libraries and JWT security
Browse files Browse the repository at this point in the history
  • Loading branch information
Taman committed Sep 2, 2024
1 parent defc243 commit f1c7a8a
Show file tree
Hide file tree
Showing 12 changed files with 73 additions and 90 deletions.
12 changes: 0 additions & 12 deletions .jpb/persistence-units.xml

This file was deleted.

2 changes: 1 addition & 1 deletion README.md

Large diffs are not rendered by default.

26 changes: 13 additions & 13 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.0</version>
<version>3.4.0-M1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<groupId>org.siriusxi.fa</groupId>
<artifactId>flight-advisor</artifactId>
<version>5.0</version>
<version>6.0</version>
<name>Flight Advisor API</name>
<description>Flight Advisor API Spring Boot based Application.</description>
<packaging>jar</packaging>
Expand All @@ -25,10 +25,10 @@
<email>[email protected]</email>
<roles>
<role>
Sr. Enterprise Architect
Solutions Architect
</role>
<role>
Lead Software Architect
Java Lead Software Architect
</role>
</roles>
</developer>
Expand Down Expand Up @@ -58,23 +58,23 @@
</licenses>

<properties>
<java.version>21</java.version>
<java.version>22</java.version>
<maven.compiler.release>${java.version}</maven.compiler.release>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<!-- Dependencies versions properties -->
<maven.surefire.plugin.version>3.0.0</maven.surefire.plugin.version>
<maven.failsafe.plugin.version>3.0.0</maven.failsafe.plugin.version>
<io.jsonwebtoken.version>0.11.5</io.jsonwebtoken.version>
<org.mapstruct.version>1.5.4.Final</org.mapstruct.version>
<org.springdoc.version>2.1.0</org.springdoc.version>
<opencsv.version>5.7.1</opencsv.version>
<maven.surefire.plugin.version>3.5.0</maven.surefire.plugin.version>
<maven.failsafe.plugin.version>3.5.0</maven.failsafe.plugin.version>
<io.jsonwebtoken.version>0.12.6</io.jsonwebtoken.version>
<org.mapstruct.version>1.6.0</org.mapstruct.version>
<org.springdoc.version>2.6.0</org.springdoc.version>
<opencsv.version>5.9</opencsv.version>
<hipster-core.version>1.0.1</hipster-core.version>
<datasource-proxy-sbs.version>1.8.1</datasource-proxy-sbs.version>
<commons-collections4.version>4.4</commons-collections4.version>
<datasource-proxy-sbs.version>1.9.1</datasource-proxy-sbs.version>
<commons-collections4.version>4.5.0-M2</commons-collections4.version>
</properties>

<dependencies>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.math.BigDecimal;
import java.util.List;

import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
Expand All @@ -16,7 +17,7 @@ public record TripResponse(
@JsonProperty Distance distance) {

public record Price(
@JsonProperty double total,
@JsonProperty BigDecimal total,
@JsonProperty String currency) {
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/siriusxi/fa/domain/Role.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public class Role implements GrantedAuthority {
private String authority;

public Role(RolePK rolePK) {
setRolePK(rolePK);
this.setRolePK(rolePK);
this.authority = rolePK.getAuthority();
}

Expand Down
3 changes: 2 additions & 1 deletion src/main/java/org/siriusxi/fa/domain/Route.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import java.io.Serial;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Objects;

import static jakarta.persistence.FetchType.LAZY;
Expand Down Expand Up @@ -55,7 +56,7 @@ public class Route implements Serializable {
@Max(value = 99999)
@Min(value = 5)
@Column(precision = 6, scale = 3)
private double price;
private BigDecimal price;

@JoinColumn(name = "DESTINATION_AIRPORT_ID", referencedColumnName = "AIRPORT_ID")
@ManyToOne(fetch = LAZY)
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/org/siriusxi/fa/domain/vo/RouteView.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
package org.siriusxi.fa.domain.vo;

public record RouteView(String source, String destination, double price) {
import java.math.BigDecimal;

public record RouteView(String source, String destination, BigDecimal price) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.Keys;
import lombok.extern.log4j.Log4j2;
Expand All @@ -24,10 +23,10 @@

@Log4j2
public final class JwtTokenHelper {

private JwtTokenHelper() {
}

/**
* Generates a token fot the user.
*
Expand All @@ -37,18 +36,19 @@ private JwtTokenHelper() {
*/
public static String generateJwtToken(int id, String username) {
return Jwts
.builder()
.setId(String.valueOf(id))
.setSubject(format("%d,%s", id, username))
.setIssuer(JwtConfig.ISSUER)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(Date.from(ZonedDateTime.now()
.plusDays(JwtConfig.TOKEN_EXPIRY_DURATION)
.toInstant()))
.signWith(JwtConfig.key(), JwtConfig.SIGNATURE_ALGORITHM)
.compact();
.builder()
.id(String.valueOf(id))
.subject(format("%d,%s", id, username))
.audience().add("you").and()
.issuer(JwtConfig.ISSUER)
.issuedAt(new Date(System.currentTimeMillis()))
.expiration(Date.from(ZonedDateTime.now()
.plusDays(JwtConfig.TOKEN_EXPIRY_DURATION)
.toInstant()))
.signWith(JwtConfig.key())
.compact();
}

/**
* Extracts the User id claim from the JWT token
*
Expand All @@ -57,10 +57,10 @@ public static String generateJwtToken(int id, String username) {
*/
public static int getUserIdFrom(String jwtToken) {
return Integer.parseInt(getClaims(jwtToken)
.getSubject()
.split(",")[0]);
.getSubject()
.split(",")[0]);
}

/**
* Extracts the username claim from the JWT token
*
Expand All @@ -69,10 +69,10 @@ public static int getUserIdFrom(String jwtToken) {
*/
public static String getUsernameFrom(String jwtToken) {
return getClaims(jwtToken)
.getSubject()
.split(",")[1];
.getSubject()
.split(",")[1];
}

/**
* Extracts the expiration date claim from the JWT token
*
Expand All @@ -81,24 +81,23 @@ public static String getUsernameFrom(String jwtToken) {
*/
public static Date getTokenExpiration(String token) {
return getClaims(token)
.getExpiration();
.getExpiration();
}

/**
* Extracts the claims from the JWT token
*
* @param token - token to analyze
* @return the all claims contained in the token
*/
private static Claims getClaims(String token) {
return Jwts
.parserBuilder()
.setSigningKey(JwtConfig.key())
.build()
.parseClaimsJws(token.replace(JwtConfig.TOKEN_PREFIX, ""))
.getBody();
return Jwts.parser()
.verifyWith(JwtConfig.key())
.build()
.parseSignedClaims(token.replace(JwtConfig.TOKEN_PREFIX, ""))
.getPayload();
}

/**
* Extracts the claim from the JWT token
*
Expand All @@ -122,48 +121,33 @@ public static boolean validate(String token) {
}
return false;
}

/**
* Allows generating a real base64 encoded secret key.
*/
public static String getRealBase64EncodedSecret() {
return Base64.getEncoder().encodeToString(getRealSecret());
}

/**
* Allows generating a real secret key.
*/
public static byte[] getRealSecret() {
return Keys.secretKeyFor(JwtConfig.SIGNATURE_ALGORITHM).getEncoded();
}

public static String tokenPrefix(){
public static String tokenPrefix() {
return JwtConfig.TOKEN_PREFIX;
}

public static int refreshTokenExpiration(){
public static int refreshTokenExpiration() {
return JwtConfig.REFRESH_TOKEN_EXPIRATION;
}

/**
* jwt configurations.
* TODO add all config in application.yaml
*/
private static class JwtConfig {
static final SignatureAlgorithm SIGNATURE_ALGORITHM = SignatureAlgorithm.HS512;
// It should be kept encoded in an environment variable
static final String SECRET =
"""
5s2BCxpNxdI58mAaAllBr/psyu91aCusvXy+kew9ytxQ/zh\
RtvcZMxVAjmkq8pVkSMA81+9Y0D4W06qGre+hYg==""";
"""
5s2BCxpNxdI58mAaAllBr/psyu91aCusvXy+kew9ytxQ/zh\
RtvcZMxVAjmkq8pVkSMA81+9Y0D4W06qGre+hYg==""";
static final String TOKEN_PREFIX = "Bearer ";
static final String ISSUER = "siriusx.io";
static final String ISSUER = "tamanm.io";
static final int TOKEN_EXPIRY_DURATION = 7; // In days
static final int REFRESH_TOKEN_EXPIRATION = 14; // In days

private JwtConfig() {
}

static SecretKey key() {
return Keys.hmacShaKeyFor(Base64.getDecoder().decode(SECRET));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Set;
Expand All @@ -31,7 +32,7 @@ SELECT sum(price)
FROM Route
WHERE routePK IN (:routePKs)
""")
double getTripCost(Iterable<RoutePK> routePKs);
BigDecimal getTripCost(Iterable<RoutePK> routePKs);

List<Route> findAllByRoutePKIn(Collection<RoutePK> routePK);

Expand Down
5 changes: 3 additions & 2 deletions src/main/java/org/siriusxi/fa/service/TravelService.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
Expand Down Expand Up @@ -160,7 +161,7 @@ private double calculateDistance(Route route) {

private TripResponse newTripView(Airport src, Airport dest,
List<AirportResponse> through,
double cost, double distance) {
BigDecimal cost, double distance) {
return new TripResponse(
this.airportMapper.toTripView(src, 0), through,
this.airportMapper.toTripView(dest, 0),
Expand Down Expand Up @@ -203,7 +204,7 @@ private GraphBuilder<String, Double> buildGraph(GraphBuilder<String, Double> gra
graph
.connect(route.source())
.to(route.destination())
.withEdge(route.price()));
.withEdge(route.price().doubleValue()));
return graph;
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/siriusxi/fa/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public UserResponse create(CreateUserRequest request) {
// Update user to add authorities
this.repository.save(user);

System.out.println("Saved User: "+ user.toString());
System.out.println("Saved User: "+ user);

// Return user view
return this.userMapper.toView(user);
Expand Down
11 changes: 8 additions & 3 deletions src/main/resources/application.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,15 @@ spring:
open-in-view: false
hibernate:
ddl-auto: none
# The SQL dialect makes Hibernate generate better SQL for the chosen database
properties:
hibernate:
dialect: org.hibernate.dialect.H2Dialect
hibernate:
# The SQL dialect makes Hibernate generate better SQL for the chosen database
dialect: org.hibernate.dialect.H2Dialect
format_sql: true
use_sql_comments: true
# Generate statistics for Hibernate's performance monitoring
# This will provide additional information about your database usage.
# Uncomment the following line to generate statistics.
generate_statistics: true
# Switching on batch insert
# Take the time to group inserts by entity, creating larger batches.
Expand Down

0 comments on commit f1c7a8a

Please sign in to comment.