Skip to content

Commit

Permalink
refactor : TokenStorage -> RefreshTokenStorage 엔티티 이름 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
seongjunnoh committed Nov 2, 2024
1 parent ebe40c9 commit 8eaab2e
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import space.space_spring.domain.authorization.jwt.model.TokenType;
import space.space_spring.domain.authorization.jwt.repository.JwtRepository;
import space.space_spring.domain.user.model.PostLoginDto;
import space.space_spring.entity.TokenStorage;
import space.space_spring.entity.RefreshTokenStorage;
import space.space_spring.entity.User;
import space.space_spring.exception.CustomException;
import space.space_spring.domain.authorization.jwt.model.JwtLoginProvider;
Expand Down Expand Up @@ -44,7 +44,7 @@ public PostLoginDto login(PostLoginDto.Request request) {
String refreshToken = jwtLoginProvider.generateToken(userByEmail.getUserId(), TokenType.REFRESH);

// TODO 4. refresh token db에 저장
TokenStorage tokenStorage = TokenStorage.builder()
RefreshTokenStorage tokenStorage = RefreshTokenStorage.builder()
.user(userByEmail)
.tokenValue(refreshToken)
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,19 @@
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import space.space_spring.entity.TokenStorage;
import space.space_spring.entity.RefreshTokenStorage;
import space.space_spring.entity.User;

import java.util.Optional;

@Repository
public interface JwtRepository extends JpaRepository<TokenStorage, Long> {
public interface JwtRepository extends JpaRepository<RefreshTokenStorage, Long> {

Optional<TokenStorage> findByUser(User user);
Optional<RefreshTokenStorage> findByUser(User user);

@Modifying
@Transactional
@Query("DELETE FROM TokenStorage t WHERE t.user = :user")
@Query("DELETE FROM RefreshTokenStorage t WHERE t.user = :user")
void deleteByUser(@Param("user") User user);

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import space.space_spring.domain.authorization.jwt.model.*;
import space.space_spring.domain.authorization.jwt.repository.JwtRepository;
import space.space_spring.domain.user.repository.UserRepository;
import space.space_spring.entity.TokenStorage;
import space.space_spring.entity.RefreshTokenStorage;
import space.space_spring.entity.User;
import space.space_spring.exception.CustomException;
import space.space_spring.exception.jwt.unauthorized.JwtExpiredTokenException;
Expand Down Expand Up @@ -49,7 +49,7 @@ private User getUserByAccessToken(String accessToken) {
}

private void validateRefreshToken(User user, String refreshToken) {
TokenStorage tokenStorage = jwtRepository.findByUser(user)
RefreshTokenStorage tokenStorage = jwtRepository.findByUser(user)
.orElseThrow(() ->
{
// db에서 row delete 하는 코드 추가
Expand All @@ -61,7 +61,7 @@ private void validateRefreshToken(User user, String refreshToken) {
if (jwtLoginProvider.isExpiredToken(refreshToken, TokenType.REFRESH)) {
// refresh token이 만료된 경우 -> 예외 발생 -> 유저의 재 로그인 유도
// db에서 row delete 하는 코드 추가
deleteTokenStorage(user);
deleteRefreshTokenStorage(user);

throw new JwtExpiredTokenException(EXPIRED_REFRESH_TOKEN);
}
Expand All @@ -70,19 +70,19 @@ private void validateRefreshToken(User user, String refreshToken) {
if (!tokenStorage.checkTokenValue(refreshToken)) {
// refresh token이 db에 존재하는 token 값과 일치하지 않는 경우 -> 유효하지 않은 refresh token이므로 예외 발생
// db에서 row delete 하는 코드 추가
deleteTokenStorage(user);
deleteRefreshTokenStorage(user);

throw new JwtUnauthorizedTokenException(TOKEN_MISMATCH);
}
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void deleteTokenStorage(User user) {
public void deleteRefreshTokenStorage(User user) {
jwtRepository.deleteByUser(user);
}

private TokenPairDTO updateTokenPair(User user) {
TokenStorage tokenStorage = jwtRepository.findByUser(user)
RefreshTokenStorage tokenStorage = jwtRepository.findByUser(user)
.orElseThrow(() -> new JwtUnauthorizedTokenException(TOKEN_MISMATCH));

// new access token, new refresh token 발급 받아서
Expand Down Expand Up @@ -111,7 +111,7 @@ public TokenPairDTO provideJwtToOAuthUser(User userByOAuthInfo) {

@Transactional
public void updateRefreshToken(User user, String refreshToken) {
TokenStorage tokenStorage = jwtRepository.findByUser(user)
RefreshTokenStorage tokenStorage = jwtRepository.findByUser(user)
.orElseThrow(() -> new JwtUnauthorizedTokenException(TOKEN_MISMATCH));

tokenStorage.updateTokenValue(refreshToken);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package space.space_spring.entity;

import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
Expand All @@ -10,7 +9,7 @@
@Table(name = "Token_Storage")
@Getter
@NoArgsConstructor
public class TokenStorage {
public class RefreshTokenStorage {

@Id @GeneratedValue
@Column(name = "token_storage_id")
Expand All @@ -32,13 +31,13 @@ public boolean checkTokenValue(String tokenValue) {
}

@Builder
private TokenStorage(User user, String tokenValue) {
private RefreshTokenStorage(User user, String tokenValue) {
this.user = user;
this.tokenValue = tokenValue;
}

public static TokenStorage create(User user, String tokenValue) {
return TokenStorage.builder()
public static RefreshTokenStorage create(User user, String tokenValue) {
return RefreshTokenStorage.builder()
.user(user)
.tokenValue(tokenValue)
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import space.space_spring.domain.authorization.jwt.model.JwtLoginTokenResolver;
import space.space_spring.domain.authorization.jwt.repository.JwtRepository;
import space.space_spring.domain.user.repository.UserRepository;
import space.space_spring.entity.TokenStorage;
import space.space_spring.entity.RefreshTokenStorage;
import space.space_spring.entity.User;
import space.space_spring.entity.enumStatus.UserSignupType;
import space.space_spring.exception.jwt.unauthorized.JwtExpiredTokenException;
Expand All @@ -40,7 +40,7 @@
"secret.jwt.refresh-expired-in=604800000"
})
@EnableJpaRepositories(basePackageClasses = {UserRepository.class, JwtRepository.class})
@EntityScan(basePackageClasses = {User.class, TokenStorage.class})
@EntityScan(basePackageClasses = {User.class, RefreshTokenStorage.class})
class JwtServiceTest {

@Autowired
Expand Down Expand Up @@ -80,7 +80,7 @@ void updateTokenPair1() throws Exception {
.signWith(SignatureAlgorithm.HS256, "refreshSecretKeyrefreshSecretKeyrefreshSecretKey")
.compact();

TokenStorage tokenStorage = TokenStorage.create(savedUser, refreshToken);
RefreshTokenStorage tokenStorage = RefreshTokenStorage.create(savedUser, refreshToken);
jwtRepository.save(tokenStorage);

MockHttpServletRequest request = new MockHttpServletRequest();
Expand All @@ -101,10 +101,10 @@ void updateTokenPair1() throws Exception {

assertThat(accessTokenClaims.get("userId", Long.class)).isEqualTo(userId);

TokenStorage updatedTokenStorage = jwtRepository.findByUser(savedUser)
.orElseThrow(() -> new Exception("TokenStorage not found"));
RefreshTokenStorage updatedRefreshTokenStorage = jwtRepository.findByUser(savedUser)
.orElseThrow(() -> new Exception("RefreshTokenStorage not found"));

assertThat(updatedTokenStorage.getTokenValue()).isEqualTo(newRefreshToken);
assertThat(updatedRefreshTokenStorage.getTokenValue()).isEqualTo(newRefreshToken);

System.out.println("old access token = " + accessToken);
System.out.println("new access token = " + newAccessToken);
Expand Down Expand Up @@ -133,7 +133,7 @@ void updateTokenPair2() throws Exception {
.signWith(SignatureAlgorithm.HS256, "refreshSecretKeyrefreshSecretKeyrefreshSecretKey")
.compact();

TokenStorage tokenStorage = TokenStorage.create(savedUser, refreshToken);
RefreshTokenStorage tokenStorage = RefreshTokenStorage.create(savedUser, refreshToken);
jwtRepository.save(tokenStorage);

MockHttpServletRequest request = new MockHttpServletRequest();
Expand All @@ -145,7 +145,7 @@ void updateTokenPair2() throws Exception {
.isInstanceOf(JwtExpiredTokenException.class)
.hasMessage("만료된 refresh token 입니다. 다시 로그인해야합니다.");

Optional<TokenStorage> byUser = jwtRepository.findByUser(user);
Optional<RefreshTokenStorage> byUser = jwtRepository.findByUser(user);
assertThat(byUser).isEmpty();
}

Expand All @@ -171,7 +171,7 @@ void updateTokenPair3() throws Exception {

String anotherRefreshToken = "anotherRefreshToken";

TokenStorage tokenStorage = TokenStorage.create(savedUser, anotherRefreshToken);
RefreshTokenStorage tokenStorage = RefreshTokenStorage.create(savedUser, anotherRefreshToken);
jwtRepository.save(tokenStorage);

MockHttpServletRequest request = new MockHttpServletRequest();
Expand All @@ -183,7 +183,7 @@ void updateTokenPair3() throws Exception {
.isInstanceOf(JwtUnauthorizedTokenException.class)
.hasMessage("저장된 refresh token 과 전달받은 refresh token 이 일치하지 않습니다. 다시 로그인해야합니다.");

Optional<TokenStorage> byUser = jwtRepository.findByUser(user);
Optional<RefreshTokenStorage> byUser = jwtRepository.findByUser(user);
assertThat(byUser).isEmpty();

System.out.println("refresh token = " + refreshToken);
Expand Down

0 comments on commit 8eaab2e

Please sign in to comment.