Skip to content

Commit

Permalink
Merge pull request #57 from dnwls16071/refactor-user
Browse files Browse the repository at this point in the history
Refactor user
  • Loading branch information
dnwls16071 authored Dec 29, 2024
2 parents f05a5f5 + f256eb7 commit f088f28
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 80 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@
import com.example.aniwhere.application.auth.jwt.dto.CreateTokenCommand;
import com.example.aniwhere.global.error.exception.TokenException;
import com.example.aniwhere.service.redis.RedisService;
import com.example.aniwhere.domain.token.RefreshToken;
import com.example.aniwhere.domain.user.Role;
import com.example.aniwhere.domain.user.User;
import com.example.aniwhere.repository.token.RefreshTokenRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import com.auth0.jwt.JWT;
Expand All @@ -32,15 +30,13 @@ public class TokenProvider {

private final JwtProperties jwtProperties;
private final RedisService redisService;
private final RefreshTokenRepository refreshTokenRepository;

private final Algorithm algorithm;
private final JWTVerifier jwtVerifier;

public TokenProvider(JwtProperties jwtProperties, RedisService redisService, RefreshTokenRepository refreshTokenRepository) {
public TokenProvider(JwtProperties jwtProperties, RedisService redisService) {
this.jwtProperties = jwtProperties;
this.redisService = redisService;
this.refreshTokenRepository = refreshTokenRepository;
this.algorithm = Algorithm.HMAC512(jwtProperties.getSecretKey());
this.jwtVerifier = JWT.require(algorithm)
.withIssuer(jwtProperties.getIssuer())
Expand Down Expand Up @@ -71,13 +67,7 @@ public String generateRefreshToken(final CreateTokenCommand command, final User
.withClaim(ROLE, command.role().getValue())
.sign(algorithm);

redisService.saveRefreshToken(user.getEmail(), refreshToken);

RefreshToken refreshTokenEntity = refreshTokenRepository.findByUserId(user.getId())
.map(entity -> entity.update(refreshToken))
.orElse(new RefreshToken(user.getId(), refreshToken));
refreshTokenRepository.save(refreshTokenEntity);

redisService.saveRefreshToken(user.getId(), refreshToken);
return refreshToken;
}

Expand Down
42 changes: 21 additions & 21 deletions src/main/java/com/example/aniwhere/domain/token/RefreshToken.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,24 @@
import lombok.Getter;
import lombok.NoArgsConstructor;

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class RefreshToken extends Common {

@Column(name = "user_id", nullable = false, unique = true)
private Long userId;

@Column(name = "refresh_token", nullable = false)
private String refreshToken;

public RefreshToken(Long userId, String refreshToken) {
this.userId = userId;
this.refreshToken = refreshToken;
}

public RefreshToken update(String newRefreshToken) {
this.refreshToken = newRefreshToken;
return this;
}
}
//@Entity
//@Getter
//@NoArgsConstructor(access = AccessLevel.PROTECTED)
//public class RefreshToken extends Common {
//
// @Column(name = "user_id", nullable = false, unique = true)
// private Long userId;
//
// @Column(name = "refresh_token", nullable = false)
// private String refreshToken;
//
// public RefreshToken(Long userId, String refreshToken) {
// this.userId = userId;
// this.refreshToken = refreshToken;
// }
//
// public RefreshToken update(String newRefreshToken) {
// this.refreshToken = newRefreshToken;
// return this;
// }
//}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package com.example.aniwhere.repository.token;

import com.example.aniwhere.domain.token.RefreshToken;
import org.springframework.data.jpa.repository.JpaRepository;
//import com.example.aniwhere.domain.token.RefreshToken;
//import org.springframework.data.jpa.repository.JpaRepository;
//
//import java.util.Optional;

import java.util.Optional;

public interface RefreshTokenRepository extends JpaRepository<RefreshToken, Long> {
Optional<RefreshToken> findByUserId(Long userId);
}
//public interface RefreshTokenRepository extends JpaRepository<RefreshToken, Long> {
// Optional<RefreshToken> findByUserId(Long userId);
//}
38 changes: 20 additions & 18 deletions src/main/java/com/example/aniwhere/service/redis/RedisService.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,39 +16,41 @@ public class RedisService {
private final RedisTemplate<String, String> redisTemplate;
private final ValueOperations<String, String> operations;

private static final String REFRESH_TOKEN_PREFIX = "RT:";
private static final String OAUTH_ACCESS_PREFIX = "OAT:";
private static final String OAUTH_REFRESH_PREFIX = "ORT:";
private static final String BLACKLIST_ACCESS_PREFIX = "BAL:";
private static final String BLACKLIST_REFRESH_PREFIX = "BRL";
private static final String CODE_PREFIX = "CODE:";

public RedisService(JwtProperties jwtProperties, RedisTemplate<String, String> redisTemplate) {
this.jwtProperties = jwtProperties;
this.redisTemplate = redisTemplate;
this.operations = redisTemplate.opsForValue();
}

public void saveRefreshToken(String email, String token) {
operations.set(email, token, Duration.ofSeconds(jwtProperties.getRefresh_token_expiration_time()));
}

public boolean deleteRefreshToken(String email) {
Boolean result = redisTemplate.delete(email);
return Boolean.TRUE.equals(result);
public void saveRefreshToken(Long userId, String token) {
operations.set(REFRESH_TOKEN_PREFIX + userId, token, Duration.ofSeconds(jwtProperties.getRefresh_token_expiration_time()));
}

public String getRefreshToken(String email) {
return operations.get(email);
public String getRefreshToken(String userId) {
return operations.get(REFRESH_TOKEN_PREFIX + userId);
}

public String getOAuthAccessToken(String email) {
return operations.get(email);
return operations.get(OAUTH_ACCESS_PREFIX + email);
}

public String getOAuthRefreshToken(String email) {
return operations.get(email);
return operations.get(OAUTH_REFRESH_PREFIX + email);
}

public void saveOAuthAccessToken(String email, String token) {
operations.set("OAT:" + email, token, Duration.ofSeconds(jwtProperties.getAccess_token_expiration_time()));
operations.set(OAUTH_ACCESS_PREFIX + email, token, Duration.ofSeconds(jwtProperties.getAccess_token_expiration_time()));
}

public void saveOAuthRefreshToken(String email, String token) {
operations.set("ORT:" + email, token, Duration.ofSeconds(jwtProperties.getRefresh_token_expiration_time()));
operations.set(OAUTH_REFRESH_PREFIX + email, token, Duration.ofSeconds(jwtProperties.getRefresh_token_expiration_time()));
}

public void deleteOAuthToken(String email) {
Expand All @@ -57,23 +59,23 @@ public void deleteOAuthToken(String email) {

public void saveCode(String key, String value, Duration duration) {
redisTemplate.opsForValue()
.set(key, value, duration);
.set(CODE_PREFIX + key, value, duration);
}

public void deleteCode(String key) {
redisTemplate.delete(key);
redisTemplate.delete(CODE_PREFIX + key);
}

public String getCode(String key) {
return redisTemplate.opsForValue()
.get(key);
.get(CODE_PREFIX + key);
}

public void saveBlackListAccessToken(String email, String token) {
operations.set(email, token, Duration.ofSeconds(jwtProperties.getAccess_token_expiration_time()));
operations.set(BLACKLIST_ACCESS_PREFIX + email, token, Duration.ofSeconds(jwtProperties.getAccess_token_expiration_time()));
}

public void saveBlackListRefreshToken(String email, String token) {
operations.set(email, token, Duration.ofSeconds(jwtProperties.getRefresh_token_expiration_time()));
operations.set(BLACKLIST_REFRESH_PREFIX + email, token, Duration.ofSeconds(jwtProperties.getRefresh_token_expiration_time()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,10 @@
import com.example.aniwhere.application.auth.jwt.dto.Claims;
import com.example.aniwhere.application.auth.jwt.dto.CreateTokenCommand;
import com.example.aniwhere.service.redis.RedisService;
import com.example.aniwhere.domain.token.RefreshToken;
import com.example.aniwhere.domain.user.User;
import com.example.aniwhere.global.error.exception.UserException;
import com.example.aniwhere.global.error.exception.TokenException;
import com.example.aniwhere.application.auth.jwt.provider.TokenProvider;
import com.example.aniwhere.repository.token.RefreshTokenRepository;
import com.example.aniwhere.repository.user.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -29,7 +27,6 @@ public class TokenService {
private final CookieConfig cookieConfig;
private final RedisService redisService;
private final UserRepository userRepository;
private final RefreshTokenRepository refreshTokenRepository;

@Transactional
public ResponseCookie createNewAccessToken(String refreshToken) {
Expand All @@ -43,30 +40,13 @@ public ResponseCookie createNewAccessToken(String refreshToken) {
return cookieConfig.createAccessTokenCookie("access_token", newAccessToken);
}

return handleCacheMiss(claims.userId());
throw new TokenException(NOT_FOUND_REFRESH_TOKEN);
} catch (TokenException e) {
log.error("Refresh token validation failed", e);
throw new TokenException(INVALID_TOKEN);
}
}


private ResponseCookie handleCacheMiss(Long userId) {
User user = getUserByUserId(userId);

RefreshToken dbRefreshToken = refreshTokenRepository.findByUserId(userId)
.orElseThrow(() -> new TokenException(NOT_FOUND_REFRESH_TOKEN));

try {
tokenProvider.validateToken(dbRefreshToken.getRefreshToken());
} catch (TokenException e) {
throw new TokenException(INVALID_REFRESH_TOKEN);
}

String newAccessToken = generateAccessToken(user);
return cookieConfig.createAccessTokenCookie("access_token", newAccessToken);
}

private User getUserByUserId(Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new UserException(NOT_FOUND_USER));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public UserSignInResult signIn(UserSignInRequest request) {
}

JwtToken jwtToken = generateTokens(user);
redisService.saveRefreshToken(user.getEmail(), jwtToken.refreshToken());
redisService.saveRefreshToken(user.getId(), jwtToken.refreshToken());
ResponseCookie accessTokenCookie = cookieConfig.createAccessTokenCookie("access_token", jwtToken.accessToken());
ResponseCookie refreshTokenCookie = cookieConfig.createRefreshTokenCookie("refresh_token", jwtToken.refreshToken());

Expand Down

0 comments on commit f088f28

Please sign in to comment.