Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
6 changes: 4 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,11 @@ dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-security-test'
testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.testcontainers:testcontainers-postgresql'
testImplementation 'org.springframework.boot:spring-boot-testcontainers'
testImplementation "org.testcontainers:testcontainers-minio"

testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
testRuntimeOnly 'com.h2database:h2'
testImplementation 'com.h2database:h2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,23 +46,23 @@ public ResponseEntity<?> login(@RequestBody LoginRequestDTO request, HttpServlet
new UsernamePasswordAuthenticationToken(request.email(), request.rawPassword())
);

var accessToken = jwtUtils.generateAccessToken(auth);
User user = (User) auth.getPrincipal();

var accessToken = jwtUtils.generateAccessToken(user);
Cookie jwtCookie = new Cookie("jwt", accessToken);
jwtCookie.setHttpOnly(true);
jwtCookie.setSecure(false);
jwtCookie.setPath("/");
jwtCookie.setMaxAge((int) settings.getRefreshTokenTtl().toSeconds());
response.addCookie(jwtCookie);

var refreshToken = jwtUtils.generateRefreshToken(auth);
var refreshToken = jwtUtils.generateRefreshToken(user);
Cookie refreshCookie = new Cookie("refresh_jwt", refreshToken);
refreshCookie.setPath("/");
refreshCookie.setHttpOnly(true);
refreshCookie.setMaxAge((int) settings.getRefreshTokenTtl().toSeconds());
refreshCookie.setSecure(false);
response.addCookie(refreshCookie);

User user = userService.getByEmail(request.email());
return ResponseEntity.ok(new LoginResponseDTO(user.getNickname()));
}

Expand Down Expand Up @@ -104,13 +104,8 @@ public ResponseEntity<?> refreshToken(HttpServletRequest request, HttpServletRes

User user = userService.getByEmail(email);

UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
user,
null,
user.getAuthorities()
);

var accessToken = jwtUtils.generateAccessToken(auth);
var accessToken = jwtUtils.generateAccessToken(user);
Cookie cookie = new Cookie("jwt", accessToken);
cookie.setHttpOnly(true);
cookie.setSecure(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import com.codzilla.backend.Authentication.JWTUtils.JWTUtils;

Expand All @@ -27,10 +28,12 @@ public JWTRequestFilter(JWTUtils jwtUtils) {
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
log.info("In filter.");
String token = null;
if (request.getCookies() != null) {
log.info("COOKIE: " + request.getCookies().toString());
for (var cookie : request.getCookies()) {
log.info("Cookie: " + cookie.getName());
if ("jwt".equals(cookie.getName())) {
Expand All @@ -45,14 +48,19 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
try {
String email = jwtUtils.getEmailFromToken(token);
List<String> roles = jwtUtils.getRolesFromToken(token);
log.info("{} has jwt. His roles: {}", email, roles);
UUID uuid = jwtUtils.getIdFromToken(token);
log.info(
"{} has jwt. His roles: {}",
email,
roles
);

List<SimpleGrantedAuthority> authorities = roles.stream()
.map(SimpleGrantedAuthority::new)
.toList();
.map(SimpleGrantedAuthority::new)
.toList();

User user = User.builder()
.email(email).build();
.email(email).id(uuid).build();
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
user,
null,
Expand All @@ -69,7 +77,10 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse

}

filterChain.doFilter(request, response);
filterChain.doFilter(
request,
response
);

}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.codzilla.backend.Authentication.JWTUtils;

import com.codzilla.backend.Authentication.config.AuthSettings;
import com.codzilla.backend.User.User;
import io.jsonwebtoken.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
Expand All @@ -9,6 +10,7 @@
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Component
Expand All @@ -21,27 +23,39 @@ public JWTUtils(AuthSettings settings) {
this.settings = settings;
}

public String generateAccessToken(Authentication authentication) {
List<String> roles = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.filter(role -> !role.equals("FACTOR_PASSWORD"))
.toList();
public String generateAccessToken(User user) {
List<String> roles = user.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.filter(role -> !Objects.equals(
role,
"FACTOR_PASSWORD"
))
.toList();

return Jwts.builder()
.subject(authentication.getName())
.claim("roles", roles)
.subject(user.getEmail())
.claim(
"roles",
roles
)
.claim(
"id",
user.getId()
)
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() + settings.getAccessTokenTtl().toMillis()))
.expiration(new Date(
System.currentTimeMillis() + settings.getAccessTokenTtl().toMillis()))
.signWith(secret)
.compact();
}

public String generateRefreshToken(Authentication authentication) {
public String generateRefreshToken(User user) {
return Jwts.builder()
.subject(authentication.getName())
.subject(user.getEmail())
.setId(UUID.randomUUID().toString())
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() + settings.getRefreshTokenTtl().toMillis()))
.expiration(new Date(
System.currentTimeMillis() + settings.getRefreshTokenTtl().toMillis()))
.signWith(secret)
.compact();
}
Expand All @@ -53,7 +67,10 @@ public List<String> getRolesFromToken(String token) {
.parseSignedClaims(token)
.getPayload();

return claims.get("roles", List.class);
return claims.get(
"roles",
List.class
);
}

public String getEmailFromToken(String token) {
Expand All @@ -65,6 +82,20 @@ public String getEmailFromToken(String token) {
.getSubject();
}

public UUID getIdFromToken(String token) {
Claims claims = Jwts.parser()
.verifyWith(secret)
.build()
.parseSignedClaims(token)
.getPayload();

String stringUUID = claims.get(
"id",
String.class
);
return UUID.fromString(stringUUID);
}

public boolean validateToken(String token) {
try {
Jwts.parser()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public SecurityFilterChain filterChain(HttpSecurity http, JWTRequestFilter filte
return http
.cors(cors -> cors.configurationSource(request -> {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("http://localhost:5173"));
config.setAllowedOriginPatterns(Arrays.asList("*"));
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(Arrays.asList("*"));
config.setAllowCredentials(true);
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/codzilla/backend/ExampleEndpoint.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ public class ExampleEndpoint {
public ResponseEntity<Map<String, String>> endpoint() {
return ResponseEntity.ok(Map.of("message", "info"));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.codzilla.backend.PreMatch.DraftSession;


import com.codzilla.backend.PreMatch.model.*;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;
import java.util.*;

@Entity
@Table(name = "lobby")
@Getter
@Setter
public class DraftSession {

@Id
@GeneratedValue(strategy = GenerationType.UUID)
@JdbcTypeCode(SqlTypes.UUID)
UUID id;

@JdbcTypeCode(SqlTypes.UUID)
private UUID firstUserId;

@JdbcTypeCode(SqlTypes.UUID)
private UUID secondUserId;

private Status status = Status.PICKING;

boolean isFirstUserMove;

@JdbcTypeCode(SqlTypes.JSON)
@Column(name = "remain_options", columnDefinition = "jsonb")
Map<Category, Set<String>> remainOptions = new HashMap<>();

public DraftSession() {
isFirstUserMove = true;
for (var category : Category.values()) {
remainOptions.put(category, new HashSet<>());
for (var option : category.getEnumClass().getEnumConstants()) {
remainOptions.get(category).add(option.name());
}
}
}


public DraftSession(UUID firstUserId, UUID secondUserId) {
this();
this.firstUserId = firstUserId;
this.secondUserId = secondUserId;
}

public enum Status {
PICKING,
FINISHED
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.codzilla.backend.PreMatch.DraftSession;

import jakarta.persistence.LockModeType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.Optional;
import java.util.UUID;

public interface DraftSessionRepository extends JpaRepository<DraftSession, UUID> {


@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select d from DraftSession d where d.id = :id")
Optional<DraftSession> findByIdWithLock(@Param("id") UUID id);
}
Loading
Loading