Skip to content

Commit

Permalink
Merge pull request #101 from OnAndOff-UMC/refactor/#100
Browse files Browse the repository at this point in the history
[Refactor]: UserContext 수정 및 적용
  • Loading branch information
wu-seong authored Mar 5, 2024
2 parents 968d7c9 + 7e0b2d8 commit ccdfe0c
Show file tree
Hide file tree
Showing 16 changed files with 78 additions and 60 deletions.
12 changes: 5 additions & 7 deletions src/main/java/com/onnoff/onnoff/auth/UserContext.java
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
package com.onnoff.onnoff.auth;

import com.onnoff.onnoff.domain.user.User;

public class UserContext {
private static final ThreadLocal<User> authenticatedUser = new ThreadLocal<>();
private static final ThreadLocal<Long> authenticatedUser = new ThreadLocal<>();

public static void setUser(User user){
authenticatedUser.set(user);
public static void setUserId(Long userId){
authenticatedUser.set(userId);
}
public static User getUser(){
public static Long getUserId(){
return authenticatedUser.get();
}
public static void clearUser(){
public static void clearUserId(){
authenticatedUser.remove();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
@RequiredArgsConstructor
public class FilterConfig {
private final TokenProvider tokenProvider;
private final UserService userService;
private final JwtUtil jwtUtil;

@Bean
Expand All @@ -23,6 +22,6 @@ public JwtAuthFilter jwtAuthFilter() {

@Bean
public UserInterceptor userInterceptor() {
return new UserInterceptor(userService, jwtUtil);
return new UserInterceptor(jwtUtil);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ public ApiResponse<UserResponseDTO.LoginDTO> validateServerToken(@RequestBody Jw
@Operation(summary = "UserContext Test API",description = "jwt 토큰 검증 성공 시 유저 객체 저장한 거 조회 가능한지 테스트")
@GetMapping("/test")
public ResponseEntity<String> testAfterGetToken(){
log.info("authenticatedUser = {}", UserContext.getUser()); // 테스트 성공
log.info("authenticatedUser = {}", UserContext.getUserId()); // 테스트 성공
return ResponseEntity.ok("");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
@Slf4j
@RequiredArgsConstructor
public class UserInterceptor implements HandlerInterceptor {
private final UserService userService;
private final JwtUtil jwtUtil;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Expand All @@ -28,11 +27,10 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons
}
try{
// 얻은 아이디로 유저 조회하기
String userId = jwtUtil.getUserId(accessToken);
User user = userService.getUser(Long.valueOf(userId));
Long userId = Long.valueOf(jwtUtil.getUserId(accessToken));

// 조회한 유저 ThreadLocal에 저장하기
UserContext.setUser(user);
// 조회한 유저id ThreadLocal에 저장하기
UserContext.setUserId(userId);
return true;
}
catch (IllegalArgumentException exception){
Expand All @@ -46,6 +44,6 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 요청 작업 끝나면 ThreadLocal 자원 해제
UserContext.clearUser();
UserContext.clearUserId();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import com.onnoff.onnoff.auth.service.tokenValidator.SocialTokenValidator;
import com.onnoff.onnoff.domain.user.User;
import com.onnoff.onnoff.domain.user.enums.SocialType;
import com.onnoff.onnoff.domain.user.service.UserService;
import io.jsonwebtoken.Jwts;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -35,9 +36,9 @@
public class AppleLoginService implements LoginService{
private final AppleAuthClient appleAuthClient;
private final SocialTokenValidator validator;
@Value("${apple.key.id}")
@Value("${apple.key.id}")
private String kid;
@Value("${apple.key.path}")
@Value(" ${apple.key.path}")
private String keyPath;
@Value("${apple.client-id}")
private String clientId;
Expand Down Expand Up @@ -83,22 +84,6 @@ private String createClientSecret() {
throw new RuntimeException(e);
}
}
public String getAccessTokenByRfToken(String code) {
// client secret 만들기
String clientSecret = createClientSecret();
// refreshToken 가져오기
User user = UserContext.getUser();
String appleRefreshToken = user.getAppleRefreshToken();
// 요청
MultiValueMap<String, String> urlEncoded = TokenRequest.builder()
.clientId(clientId)
.clientSecret(clientSecret)
.refreshToken(appleRefreshToken)
.grantType("refresh_token")
.build().toUrlEncoded();
TokenResponse response = appleAuthClient.getToken(urlEncoded);
return null;
}
private PrivateKey getPrivateKey() throws IOException {
String privateKey = new String(Files.readAllBytes(Paths.get(keyPath) ) );
log.info("privateKey = {}", privateKey);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import com.onnoff.onnoff.domain.off.feed.entity.Feed;
import com.onnoff.onnoff.domain.off.feed.repository.FeedRepository;
import com.onnoff.onnoff.domain.user.User;
import com.onnoff.onnoff.domain.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -20,18 +21,21 @@
public class FeedServiceImpl implements FeedService {

private final FeedRepository feedRepository;
private final UserService userService;

@Override
@Transactional
public Feed addFeed(FeedRequestDTO.AddFeedDTO request) {
User user = UserContext.getUser();
Long userId = UserContext.getUserId();
User user = userService.getUser(userId);
return feedRepository.save(FeedConverter.toFeed(request, user));
}

@Override
@Transactional(readOnly = true)
public List<Feed> getFeed(LocalDate date) {
User user = UserContext.getUser();
Long userId = UserContext.getUserId();
User user = userService.getUser(userId);
return feedRepository.findAllByUserAndDateOrderByCreatedAtAsc(user, date);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import com.onnoff.onnoff.domain.off.feedImage.entity.FeedImage;
import com.onnoff.onnoff.domain.off.feedImage.repository.FeedImageRepository;
import com.onnoff.onnoff.domain.user.User;
import com.onnoff.onnoff.domain.user.repository.UserRepository;
import com.onnoff.onnoff.domain.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
Expand All @@ -38,11 +38,13 @@ public class FeedImageServiceImpl implements FeedImageService {

private final AmazonS3Client amazonS3Client;
private final FeedImageRepository feedImageRepository;
private final UserService userService;

@Override
@Transactional
public FeedImageResponseDTO.FeedImageDTO uploadFeedImage(MultipartFile multipartFile) {
User user = UserContext.getUser();
Long userId = UserContext.getUserId();
User user = userService.getUser(userId);

FeedImage feedImage = FeedImage.builder()
.user(user)
Expand All @@ -57,7 +59,8 @@ public FeedImageResponseDTO.FeedImageDTO uploadFeedImage(MultipartFile multipart
@Override
@Transactional(readOnly = true)
public List<FeedImageResponseDTO.FeedImageDTO> getFeedImage() {
User user = UserContext.getUser();
Long userId = UserContext.getUserId();
User user = userService.getUser(userId);
List<FeedImage> feedImageList = feedImageRepository.findByUserOrderByCreatedAtAsc(user);

return feedImageList.stream()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import com.onnoff.onnoff.domain.off.memoir.repository.MemoirQuestionRepository;
import com.onnoff.onnoff.domain.off.memoir.repository.MemoirRepository;
import com.onnoff.onnoff.domain.user.User;
import com.onnoff.onnoff.domain.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
Expand All @@ -22,7 +23,6 @@
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
Expand All @@ -32,11 +32,13 @@ public class MemoirServiceImpl implements MemoirService {
private final MemoirAnswerRepository memoirAnswerRepository;
private final MemoirQuestionRepository memoirQuestionRepository;
private final EmoticonRepository emoticonRepository;
private final UserService userService;

@Override
@Transactional
public Memoir writeMemoir(MemoirRequestDTO.MemoirWriteDTO request) {
User user = UserContext.getUser();
Long userId = UserContext.getUserId();
User user = userService.getUser(userId);

if (memoirRepository.findByUserAndDate(user, request.getDate()).isPresent()) {
throw new MemoirHandler(ErrorStatus.MEMOIR_EXIST);
Expand Down Expand Up @@ -75,21 +77,24 @@ public Memoir writeMemoir(MemoirRequestDTO.MemoirWriteDTO request) {
@Override
@Transactional(readOnly = true)
public Memoir getMemoirPreview(LocalDate date) {
User user = UserContext.getUser();
Long userId = UserContext.getUserId();
User user = userService.getUser(userId);
return memoirRepository.findByUserAndDate(user, date).orElse(null);
}

@Override
@Transactional(readOnly = true)
public Memoir getMemoir(LocalDate date) {
User user = UserContext.getUser();
Long userId = UserContext.getUserId();
User user = userService.getUser(userId);
return memoirRepository.findByUserAndDate(user, date).orElseThrow(() -> new MemoirHandler(ErrorStatus.MEMOIR_NOT_FOUND));
}

@Override
@Transactional(readOnly = true)
public Page<Memoir> getBookmarkedMemoir(Integer pageNumber) {
User user = UserContext.getUser();
Long userId = UserContext.getUserId();
User user = userService.getUser(userId);
return memoirRepository.findByUserAndIsBookmarkedOrderByDateDesc(user, true, PageRequest.of(pageNumber, 10));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import com.onnoff.onnoff.domain.on.resolution.entity.Resolution;
import com.onnoff.onnoff.domain.on.resolution.repository.ResolutionRepository;
import com.onnoff.onnoff.domain.user.User;
import com.onnoff.onnoff.domain.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -21,18 +22,20 @@
@RequiredArgsConstructor
public class ResolutionServiceImpl implements ResolutionService{
private final ResolutionRepository resolutionRepository;
private final UserService userService;

@Override
public List<Resolution> getAll(LocalDate date){
User user = UserContext.getUser();

Long userId = UserContext.getUserId();
User user = userService.getUser(userId);
return resolutionRepository.findAllByUserAndDateOrderByOrder(user, date).stream().toList();
}

@Override
@Transactional
public Resolution addResolution(ResolutionRequest.AddResolutionDTO request){
User user = UserContext.getUser();
Long userId = UserContext.getUserId();
User user = userService.getUser(userId);

Long order = resolutionRepository.countByUserAndDate(user, request.getDate());

Expand Down Expand Up @@ -63,7 +66,8 @@ public void deleteResolution(LocalDate date, Long resolutionId){
.orElseThrow(() -> new ResolutionHandler(ErrorStatus.RESOLUTION_NOT_FOUND));

//해당 resolution 아래 객체들 순서 당겨주기
User user = UserContext.getUser();
Long userId = UserContext.getUserId();
User user = userService.getUser(userId);
List<Resolution> resolutionList = resolutionRepository.findAllByUserAndDateOrderByOrder(user, date).stream().toList();

for(Resolution resolution : resolutionList){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import com.onnoff.onnoff.domain.on.worklog.entity.Worklog;
import com.onnoff.onnoff.domain.on.worklog.repository.WorklogRepository;
import com.onnoff.onnoff.domain.user.User;
import com.onnoff.onnoff.domain.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -22,12 +23,14 @@
public class OnServiceImpl implements OnService{
private final ResolutionRepository resolutionRepository;
private final WorklogRepository worklogRepository;
private final UserService userService;

@Override
public OnResponse.OnViewDTO getOn(LocalDate date){
LocalDate localDate = Objects.requireNonNullElseGet(date, LocalDate::now);

User user = UserContext.getUser();
Long userId = UserContext.getUserId();
User user = userService.getUser(userId);

List<Resolution> resolutionList = resolutionRepository.findAllByUserAndDateOrderByOrder(user, localDate);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import com.onnoff.onnoff.domain.on.worklog.entity.Worklog;
import com.onnoff.onnoff.domain.on.worklog.repository.WorklogRepository;
import com.onnoff.onnoff.domain.user.User;
import com.onnoff.onnoff.domain.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -20,19 +21,22 @@
@RequiredArgsConstructor
public class WorklogServiceImpl implements WorklogService{
private final WorklogRepository worklogRepository;
private final UserService userService;

@Override
@Transactional
public List<Worklog> getWorklog(LocalDate date){
User user = UserContext.getUser();
Long userId = UserContext.getUserId();
User user = userService.getUser(userId);

return worklogRepository.findAllByUserAndDateOrderByCreatedAt(user, date);
}

@Override
@Transactional
public Worklog addWorklog(WorklogRequest.AddWorklogDTO request){
User user = UserContext.getUser();
Long userId = UserContext.getUserId();
User user = userService.getUser(userId);

Worklog worklog = WorklogConverter.toAddWorklog(request);
worklog.setUser(user);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.onnoff.onnoff.domain.push.entity.PushNotificationSetting;
import com.onnoff.onnoff.domain.push.repository.PushNotificationSettingRepository;
import com.onnoff.onnoff.domain.user.User;
import com.onnoff.onnoff.domain.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -17,10 +18,12 @@
@RequiredArgsConstructor
public class PushNotificationSettingService {
public final PushNotificationSettingRepository pushNotificationSettingRepository;
private final UserService userService;

@Transactional
public PushNotificationSettingResponseDTO setPushNotification(PushNotificationSettingRequestDTO pushNotificationSettingRequestDTO) {
User user = UserContext.getUser();
Long userId = UserContext.getUserId();
User user = userService.getUser(userId);
PushNotificationSetting pushNotificationSetting = pushNotificationSettingRepository.findByUser(user)
.orElseGet(() -> PushNotificationConverter.toPushNotificationSetting(pushNotificationSettingRequestDTO, user));
if (pushNotificationSetting.getId() != null) {
Expand All @@ -34,7 +37,8 @@ public PushNotificationSettingResponseDTO setPushNotification(PushNotificationSe

@Transactional(readOnly = true)
public PushNotificationSettingResponseDTO getPushNotification() {
User user = UserContext.getUser();
Long userId = UserContext.getUserId();
User user = userService.getUser(userId);
Optional<PushNotificationSetting> pushNotificationSetting = pushNotificationSettingRepository.findByUser(user);
if (pushNotificationSetting.isPresent()) {
return PushNotificationConverter.toPushNotificationResponseDTO(pushNotificationSetting.get());
Expand Down
Loading

0 comments on commit ccdfe0c

Please sign in to comment.