From 3e6474e1edcc89b29fac984a3efc056ac3ce38d9 Mon Sep 17 00:00:00 2001 From: hyeangjun Date: Thu, 18 Jul 2024 23:11:53 +0900 Subject: [PATCH 1/2] =?UTF-8?q?[Refactor,Feat]=20convention=20=EB=A7=9E?= =?UTF-8?q?=EC=B6=94=EA=B8=B0,=20RefreshToken=20=EC=B6=94=EA=B0=80=20-=20#?= =?UTF-8?q?110?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 4 ++ .../profilePhoto/domain/QProfilePhoto.java | 4 +- .../me/snaptime/user/domain/QUser.java | 4 +- .../album/service/impl/AlbumServiceImpl.java | 6 +- .../me/snaptime/exception/ExceptionCode.java | 1 + .../impl/FriendPagingRepositoryImpl.java | 12 ++-- .../service/impl/FriendServiceImpl.java | 4 +- .../java/me/snaptime/jwt/JwtProvider.java | 36 +++++++++++- .../profile/controller/ProfileController.java | 20 +++---- .../profile/dto/res/UserProfileResDto.java | 2 +- .../profile/repository/ProfileRepository.java | 2 +- .../impl/ProfileRepositoryImpl.java | 32 +++++------ .../profile/service/ProfileService.java | 4 +- .../service/impl/ProfileServiceImpl.java | 14 ++--- .../profilePhoto/domain/ProfilePhoto.java | 2 +- .../dto/res/ProfilePhotoResDto.java | 4 +- .../repository/ProfilePhotoRepository.java | 2 +- .../service/impl/ProfilePhotoServiceImpl.java | 2 +- .../java/me/snaptime/redis/RedisConfig.java | 43 ++++++++++++++ .../java/me/snaptime/redis/RefreshToken.java | 21 +++++++ .../redis/RefreshTokenRepository.java | 9 +++ .../impl/ChildReplyPagingRepositoryImpl.java | 6 +- .../impl/ParentReplyPagingRepositoryImpl.java | 4 +- .../reply/service/impl/ReplyServiceImpl.java | 4 +- .../impl/SnapPagingRepositoryImpl.java | 8 +-- .../service/impl/SnapPagingServiceImpl.java | 2 +- .../snap/service/impl/SnapServiceImpl.java | 10 ++-- .../user/controller/UserController.java | 21 +++++-- .../java/me/snaptime/user/domain/User.java | 2 +- .../snaptime/user/dto/res/SignInResDto.java | 3 +- .../me/snaptime/user/dto/res/UserResDto.java | 4 +- .../me/snaptime/user/service/SignService.java | 8 ++- .../me/snaptime/user/service/UserService.java | 2 +- .../user/service/impl/SignServiceImpl.java | 57 ++++++++++++++----- .../user/service/impl/UserServiceImpl.java | 16 +++--- .../controller/SnapPagingControllerTest.java | 3 + .../service/SnapPagingServiceImplTest.java | 6 +- .../controller/FriendControllerTest.java | 4 ++ .../controller/ReplyControllerTest.java | 4 ++ .../social/service/FriendServiceImplTest.java | 14 ++--- .../user/controller/UserControllerTest.java | 8 ++- .../user/service/ProfilePhotoServiceTest.java | 2 +- .../user/service/UserServiceTest.java | 34 +++++++---- 43 files changed, 316 insertions(+), 134 deletions(-) create mode 100644 src/main/java/me/snaptime/redis/RedisConfig.java create mode 100644 src/main/java/me/snaptime/redis/RefreshToken.java create mode 100644 src/main/java/me/snaptime/redis/RefreshTokenRepository.java diff --git a/build.gradle b/build.gradle index 5d7e7a7d..e96ff848 100644 --- a/build.gradle +++ b/build.gradle @@ -56,6 +56,10 @@ dependencies { // Jsoup implementation 'org.jsoup:jsoup:1.17.2' + //redis + implementation 'org.springframework.boot:spring-boot-starter-data-redis' + + } tasks.named('test') { diff --git a/src/main/generated/me/snaptime/profilePhoto/domain/QProfilePhoto.java b/src/main/generated/me/snaptime/profilePhoto/domain/QProfilePhoto.java index 9f4f5dcf..3d6ac0f6 100644 --- a/src/main/generated/me/snaptime/profilePhoto/domain/QProfilePhoto.java +++ b/src/main/generated/me/snaptime/profilePhoto/domain/QProfilePhoto.java @@ -27,11 +27,11 @@ public class QProfilePhoto extends EntityPathBase { //inherited public final DateTimePath createdDate = _super.createdDate; - public final NumberPath id = createNumber("id", Long.class); - //inherited public final DateTimePath lastModifiedDate = _super.lastModifiedDate; + public final NumberPath profilePhotoId = createNumber("profilePhotoId", Long.class); + public final StringPath profilePhotoName = createString("profilePhotoName"); public final StringPath profilePhotoPath = createString("profilePhotoPath"); diff --git a/src/main/generated/me/snaptime/user/domain/QUser.java b/src/main/generated/me/snaptime/user/domain/QUser.java index 53955b97..ce70c863 100644 --- a/src/main/generated/me/snaptime/user/domain/QUser.java +++ b/src/main/generated/me/snaptime/user/domain/QUser.java @@ -31,8 +31,6 @@ public class QUser extends EntityPathBase { public final StringPath email = createString("email"); - public final NumberPath id = createNumber("id", Long.class); - //inherited public final DateTimePath lastModifiedDate = _super.lastModifiedDate; @@ -46,6 +44,8 @@ public class QUser extends EntityPathBase { public final ListPath roles = this.createList("roles", String.class, StringPath.class, PathInits.DIRECT2); + public final NumberPath userId = createNumber("userId", Long.class); + public QUser(String variable) { this(User.class, forVariable(variable), INITS); } diff --git a/src/main/java/me/snaptime/album/service/impl/AlbumServiceImpl.java b/src/main/java/me/snaptime/album/service/impl/AlbumServiceImpl.java index ad515781..cc931efd 100644 --- a/src/main/java/me/snaptime/album/service/impl/AlbumServiceImpl.java +++ b/src/main/java/me/snaptime/album/service/impl/AlbumServiceImpl.java @@ -74,7 +74,7 @@ public FindAlbumResDto findAlbum(String uId, Long album_id) { FindSnapResDto.entityToResDto( snap, urlComponent.makePhotoURL(snap.getFileName(), false), - urlComponent.makeProfileURL(snap.getUser().getProfilePhoto().getId()) + urlComponent.makeProfileURL(snap.getUser().getProfilePhoto().getProfilePhotoId()) ) ) .collect(Collectors.toList())) @@ -90,7 +90,7 @@ public FindAlbumResDto findAlbum(String uId, Long album_id) { FindSnapResDto.entityToResDto( snap, urlComponent.makePhotoURL(snap.getFileName(), snap.isPrivate()), - urlComponent.makeProfileURL(snap.getUser().getProfilePhoto().getId()) + urlComponent.makeProfileURL(snap.getUser().getProfilePhoto().getProfilePhotoId()) ) ) .collect(Collectors.toList())) @@ -169,7 +169,7 @@ public void removeAlbum(String uId, Long album_id) { @Override public void isUserHavePermission(User user, Long album_id) { Album foundAlbum = albumRepository.findById(album_id).orElseThrow(() -> new CustomException(ExceptionCode.ALBUM_NOT_EXIST)); - if(!(Objects.equals(foundAlbum.getUser().getId(), user.getId()))){ + if(!(Objects.equals(foundAlbum.getUser().getUserId(), user.getUserId()))){ throw new CustomException(ExceptionCode.ALBUM_USER_NOT_MATCH); } } diff --git a/src/main/java/me/snaptime/exception/ExceptionCode.java b/src/main/java/me/snaptime/exception/ExceptionCode.java index 8df08bc5..e72f65a4 100644 --- a/src/main/java/me/snaptime/exception/ExceptionCode.java +++ b/src/main/java/me/snaptime/exception/ExceptionCode.java @@ -70,6 +70,7 @@ public enum ExceptionCode { TOKEN_UNAUTHENTICATED(HttpStatus.UNAUTHORIZED, "인증되지 않은 토큰입니다."), TOKEN_INVALID_FORMAT(HttpStatus.UNAUTHORIZED, "잘못된 형식의 토큰입니다."), TOKEN_NOT_FOUND(HttpStatus.BAD_REQUEST, "토큰이 비었거나 null입니다"), + INVALID_REFRESH_TOKEN(HttpStatus.UNAUTHORIZED,"리프레시 토큰이 유효하지 않습니다"), // Jsoup Action URL_HAVING_PROBLEM(HttpStatus.BAD_REQUEST, "문제가 있는 URL입니다."); diff --git a/src/main/java/me/snaptime/friend/repository/impl/FriendPagingRepositoryImpl.java b/src/main/java/me/snaptime/friend/repository/impl/FriendPagingRepositoryImpl.java index 4df04ea4..ac8f6a40 100644 --- a/src/main/java/me/snaptime/friend/repository/impl/FriendPagingRepositoryImpl.java +++ b/src/main/java/me/snaptime/friend/repository/impl/FriendPagingRepositoryImpl.java @@ -33,7 +33,7 @@ public List findFriendList(User targetUser, FriendSearchType searchType, Pageable pageable= PageRequest.of((int) (pageNum-1),20); List result = jpaQueryFactory.select( - user.loginId, user.profilePhoto.id, user.name, friend.friendId + user.loginId, user.profilePhoto.profilePhotoId, user.name, friend.friendId ) .from(friend) .join(user).on(getJoinBuilder(searchType)) @@ -50,7 +50,7 @@ public List findFriendList(User targetUser, FriendSearchType searchType, } private OrderSpecifier createOrderSpecifier() { - return new OrderSpecifier(Order.ASC, user.id); + return new OrderSpecifier(Order.ASC, user.userId); } // WHERE절을 동적으로 만들기 위한 메소드 @@ -58,10 +58,10 @@ private BooleanBuilder getWhereBuilder(User targetUser, FriendSearchType friendS BooleanBuilder builder = new BooleanBuilder(); if(friendSearchType == FriendSearchType.FOLLOWING){ - builder.and(friend.sender.id.eq(targetUser.getId())); + builder.and(friend.sender.userId.eq(targetUser.getUserId())); } else{ - builder.and(friend.receiver.id.eq(targetUser.getId())); + builder.and(friend.receiver.userId.eq(targetUser.getUserId())); } if(searchKeyword !=null){ @@ -75,10 +75,10 @@ private BooleanBuilder getWhereBuilder(User targetUser, FriendSearchType friendS private BooleanBuilder getJoinBuilder(FriendSearchType friendSearchType){ BooleanBuilder builder = new BooleanBuilder(); if(friendSearchType == FriendSearchType.FOLLOWING){ - return builder.and(friend.receiver.id.eq(user.id)); + return builder.and(friend.receiver.userId.eq(user.userId)); } else{ - return builder.and(friend.sender.id.eq(user.id)); + return builder.and(friend.sender.userId.eq(user.userId)); } } } diff --git a/src/main/java/me/snaptime/friend/service/impl/FriendServiceImpl.java b/src/main/java/me/snaptime/friend/service/impl/FriendServiceImpl.java index fce0c3be..f1572212 100644 --- a/src/main/java/me/snaptime/friend/service/impl/FriendServiceImpl.java +++ b/src/main/java/me/snaptime/friend/service/impl/FriendServiceImpl.java @@ -50,7 +50,7 @@ public void sendFollow(String senderLoginId, String receiverLoginId){ throw new CustomException(ExceptionCode.ALREADY_FOLLOW); // 자기자신에게 팔로우요청을 했다면 - if (receiver.getId() == sender.getId()) + if (receiver.getUserId() == sender.getUserId()) throw new CustomException(ExceptionCode.SELF_FRIEND_REQ); friendRepository.save(Friend.builder() @@ -111,7 +111,7 @@ public FindFriendResDto findFriendList(String reqLoginId, String targetLoginId, List friendInfoList = result.stream().map(entity -> { boolean isMyFriend = checkIsFollow(reqUser ,findUserByLoginId(entity.get(user.loginId))); - String profilePhotoURL = urlComponent.makeProfileURL(entity.get(user.profilePhoto.id)); + String profilePhotoURL = urlComponent.makeProfileURL(entity.get(user.profilePhoto.profilePhotoId)); return FriendInfo.toDto(entity,profilePhotoURL,isMyFriend); }).collect(Collectors.toList()); diff --git a/src/main/java/me/snaptime/jwt/JwtProvider.java b/src/main/java/me/snaptime/jwt/JwtProvider.java index c9947e81..2d25f08c 100644 --- a/src/main/java/me/snaptime/jwt/JwtProvider.java +++ b/src/main/java/me/snaptime/jwt/JwtProvider.java @@ -6,6 +6,7 @@ import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; @@ -24,7 +25,11 @@ public class JwtProvider { private Key secretKey; - private Long accessTokenValidTime= 1000L * 60 * 60*24; + @Value("${accessTokenValidTime}") + private Long accessTokenValidTime; + + @Value("${refreshTokenValidTime}") + private Long refreshTokenValidTime; @PostConstruct protected void init(){ @@ -33,10 +38,11 @@ protected void init(){ log.info("[init] JwtTokenProvider 내 secretKey 초기화 완료"); } - public String createAccessToken(String loginId, List roles){ + public String createAccessToken(Long userId, String loginId, List roles){ log.info("[createAccessToken] 엑세스 토큰 생성 시작"); Claims claims = Jwts.claims().setSubject(loginId); + claims.put("userId",userId); claims.put("type","access"); claims.put("roles",roles); Date now = new Date(); @@ -51,6 +57,32 @@ public String createAccessToken(String loginId, List roles){ return token; } + public String createRefreshToken(Long id, String loginId, List roles){ + log.info("[createRefreshToken] 리프레시 토큰 생성 시작"); + + Claims claims = Jwts.claims().setSubject(loginId); + claims.put("userId", id); + claims.put("type", "refresh"); + claims.put("roles", roles); + Date now = new Date(); + String token = Jwts.builder() + .setClaims(claims) + .setIssuedAt(now) + .setExpiration(new Date(now.getTime() + refreshTokenValidTime)) + .signWith(secretKey) + .compact(); + + log.info("[createAccessToken] 엑세스 토큰 생성 완료"); + return token; + } + + public Long getUserId(String token) { + log.info("[getUserId] 토큰 기반 회원 구별 정보 추출"); + Long userId = Long.valueOf(Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().get("userId").toString()); + log.info("[getUserId] 토큰 기반 회원 구별 정보 추출 완료, userId : {}", userId); + return userId; + } + // 필터에서 인증 성공 후, SecurityContextHolder 에 저장할 Authentication 을 생성 //UsernamePasswordAuthenticationToken 클래스를 사용 public Authentication getAuthentication(String token){ diff --git a/src/main/java/me/snaptime/profile/controller/ProfileController.java b/src/main/java/me/snaptime/profile/controller/ProfileController.java index 1ce0a8fd..763dead9 100644 --- a/src/main/java/me/snaptime/profile/controller/ProfileController.java +++ b/src/main/java/me/snaptime/profile/controller/ProfileController.java @@ -38,29 +38,30 @@ public class ProfileController { @Operation(summary = "유저 앨범, 스냅 조회", description = "유저의 앨범들과, 각 앨범의 스냅들을 조회합니다." + "
자신의 프로필 조회 -> 앨범 당 private, public 관계 없이 최근 snap 2개 리턴" + "
다른 사람의 프로필 조회 -> snap이 전부 private이거나 없는 경우 앨범 리턴 x 그리고 private 인 snap 리턴 x") - @Parameter(name = "loginId", description = "앨범과 사진들을 가져오기 위한 loginId", required = true) + @Parameter(name = "targetLoginId", description = "앨범과 사진들을 가져오기 위한 loginId", required = true) @GetMapping("/album-snap") public ResponseEntity>> getAlbumSnap(@AuthenticationPrincipal UserDetails principal, - @RequestParam("loginId") + @RequestParam("targetLoginId") @NotBlank(message = "로그인 아이디 입력은 필수입니다.") String targetLoginId){ - String yourLoginId = principal.getUsername(); - List albumSnapResDtoList = profileService.getAlbumSnap(yourLoginId, targetLoginId); + String reqLoginId = principal.getUsername(); + List albumSnapResDtos = profileService.getAlbumSnap(reqLoginId, targetLoginId); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "유저 앨범과 스냅 조회를 성공적으로 완료하였습니다.", - albumSnapResDtoList + albumSnapResDtos )); } @Operation(summary = "유저 이름, 프로필 사진 조회", description = "유저의 이름과, 프로필 사진을 조회합니다." + "
유저 번호, 유저 이름, 프로필 사진 url 리턴(토큰 없이 url 접근 가능)" + "
토큰이 없어도 해당 Api 엔드포인트를 요청할 수 있습니다.") - @Parameter(name = "loginId", description = "이름과 프로필 사진을 가져오기 위한 loginId", required = true) + @Parameter(name = "targetLoginId", description = "이름과 프로필 사진을 가져오기 위한 loginId", required = true) @GetMapping("/profile") public ResponseEntity> getUserProfile(@AuthenticationPrincipal UserDetails principal, - @RequestParam("loginId") - @NotBlank(message = "로그인 아이디 입력은 필수입니다.") String loginId){ - UserProfileResDto userProfileResDto = profileService.getUserProfile(principal.getUsername(),loginId); + @RequestParam("targetLoginId") + @NotBlank(message = "로그인 아이디 입력은 필수입니다.") String targetLoginId){ + String reqLoginId = principal.getUsername(); + UserProfileResDto userProfileResDto = profileService.getUserProfile(reqLoginId, targetLoginId); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "유저 이름과, 프로필 사진 조회를 성공적으로 완료하였습니다.", @@ -87,7 +88,6 @@ public ResponseEntity> getProfileCnt(@Reques @GetMapping("/tag-snap") public ResponseEntity>> getTagSnap(@RequestParam("loginId") @NotBlank(message = "로그인 아이디 입력은 필수입니다.") String loginId){ - List profileTagSnapResDto = profileService.getTagSnap(loginId); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( diff --git a/src/main/java/me/snaptime/profile/dto/res/UserProfileResDto.java b/src/main/java/me/snaptime/profile/dto/res/UserProfileResDto.java index 07dc35d4..27bac698 100644 --- a/src/main/java/me/snaptime/profile/dto/res/UserProfileResDto.java +++ b/src/main/java/me/snaptime/profile/dto/res/UserProfileResDto.java @@ -13,7 +13,7 @@ public record UserProfileResDto( public static UserProfileResDto toDto(User user, String profileURL , Boolean isFollow) { return UserProfileResDto.builder() - .userId(user.getId()) + .userId(user.getUserId()) .userName(user.getName()) .profileURL(profileURL) .isFollow(isFollow) diff --git a/src/main/java/me/snaptime/profile/repository/ProfileRepository.java b/src/main/java/me/snaptime/profile/repository/ProfileRepository.java index b76bc76a..39407e2b 100644 --- a/src/main/java/me/snaptime/profile/repository/ProfileRepository.java +++ b/src/main/java/me/snaptime/profile/repository/ProfileRepository.java @@ -9,5 +9,5 @@ public interface ProfileRepository{ List findAlbumSnap(User targetUser, Boolean checkPermission); - List findTagSnap(User reqUser); + List findTagSnap(User targetUser); } diff --git a/src/main/java/me/snaptime/profile/repository/impl/ProfileRepositoryImpl.java b/src/main/java/me/snaptime/profile/repository/impl/ProfileRepositoryImpl.java index cfcd1225..0247addf 100644 --- a/src/main/java/me/snaptime/profile/repository/impl/ProfileRepositoryImpl.java +++ b/src/main/java/me/snaptime/profile/repository/impl/ProfileRepositoryImpl.java @@ -34,23 +34,22 @@ public class ProfileRepositoryImpl implements ProfileRepository { //snap에 isPrivate이 존재한다, 내가 조회 -> 전부 리턴 | 남이 조회 -> isPrivate= True 인 snap 제외 @Override public List findAlbumSnap(User targetUser, Boolean checkPermission) { - List albumList = jpaQueryFactory + List albums = jpaQueryFactory .select(album.id, album.name).distinct() .from(user) - .join(album).on(user.id.eq(album.user.id)) - .where(user.id.eq(targetUser.getId())) + .join(album).on(user.userId.eq(album.user.userId)) + .where(user.userId.eq(targetUser.getUserId())) .fetch(); Map albumMap = new HashMap<>(); - albumList.forEach(tuple ->{ + albums.forEach(tuple ->{ Long albumId = tuple.get(album.id); String albumName = tuple.get(album.name); albumMap.put(albumId,albumName); }); - List albumSnapResDtoList = new ArrayList<>(); - + List albumSnapResDtos = new ArrayList<>(); //snap이 없어도 album은 존재할 수 있기 때문에 album 수 만큼 반복한다. for (Long albumId : albumMap.keySet()) { @@ -64,7 +63,7 @@ public List findAlbumSnap(User targetUser, Boolean checkPermiss .fetch(); //stream 사용하는 걸로 수정 - List snapUrlList = albumSnapTwo.stream() + List snapUrls = albumSnapTwo.stream() .map(tuple -> { String fileName = tuple.get(snap.fileName); Boolean isPrivate = tuple.get(snap.isPrivate); @@ -73,33 +72,33 @@ public List findAlbumSnap(User targetUser, Boolean checkPermiss .toList(); //다른 사람의 프로필 검색 일 때, snap이 없거나, private이면 앨범도 private - if(!checkPermission && snapUrlList.isEmpty()){ + if(!checkPermission && snapUrls.isEmpty()){ continue; } String albumName = albumMap.get(albumId); - albumSnapResDtoList.add(AlbumSnapResDto.builder() + albumSnapResDtos.add(AlbumSnapResDto.builder() .albumId(albumId) .albumName(albumName) - .snapUrlList(snapUrlList) + .snapUrlList(snapUrls) .build()); } - return albumSnapResDtoList; + return albumSnapResDtos; } @Override - public List findTagSnap(User reqUser) { - List tagSnapList = jpaQueryFactory + public List findTagSnap(User targetUser) { + List tagSnaps = jpaQueryFactory .select(snap.id,snap.user.loginId, snap.fileName, snap.isPrivate, snap.createdDate).distinct() .from(snap) .join(snapTag).on(snapTag.snap.id.eq(snap.id)) - .where(snapTag.tagUser.loginId.eq(reqUser.getLoginId())) + .where(snapTag.tagUser.loginId.eq(targetUser.getLoginId())) .orderBy(snap.createdDate.desc()) .fetch(); - List tagSnapUrlList = tagSnapList.stream() + List tagSnapUrls = tagSnaps.stream() .map(tuple -> { return ProfileTagSnapResDto.builder() .taggedSnapId(tuple.get(snap.id)) @@ -109,7 +108,7 @@ public List findTagSnap(User reqUser) { }) .toList(); - return tagSnapUrlList; + return tagSnapUrls; } // 자신이 자신의 profile을 조회할 때, 자신이 다른사람의 profile을 조회할 때를 구별하기 위함. @@ -125,7 +124,6 @@ private BooleanBuilder whereBuilder(Long albumId, Boolean checkPermission){ builder.and(snap.isPrivate.isFalse()); builder.and(snap.fileName.isNotNull()); } - return builder; } } diff --git a/src/main/java/me/snaptime/profile/service/ProfileService.java b/src/main/java/me/snaptime/profile/service/ProfileService.java index e73bb175..cfd921e7 100644 --- a/src/main/java/me/snaptime/profile/service/ProfileService.java +++ b/src/main/java/me/snaptime/profile/service/ProfileService.java @@ -9,9 +9,9 @@ public interface ProfileService { /* 호출자의 loginId, 피호출자의 loginId를 통해 피호출자의 album과 snap을 조회 */ - public List getAlbumSnap(String ownLoginId, String targetLoginId); + public List getAlbumSnap(String reqLoginId, String targetLoginId); /* loginId에 해당하는 User의 profile 사진을 조회 */ - public UserProfileResDto getUserProfile(String ownLoginId, String targetLoginId); + public UserProfileResDto getUserProfile(String reqLoginId, String targetLoginId); /* loginId에 해당하는 User의 스냅, 팔로우, 팔로워 수 리턴 */ public ProfileCntResDto getUserProfileCnt(String loginId); /* loginId에 해당하는 User가 Tag된 snap들을 조회합니다 */ diff --git a/src/main/java/me/snaptime/profile/service/impl/ProfileServiceImpl.java b/src/main/java/me/snaptime/profile/service/impl/ProfileServiceImpl.java index b5453d26..f4dfd1b1 100644 --- a/src/main/java/me/snaptime/profile/service/impl/ProfileServiceImpl.java +++ b/src/main/java/me/snaptime/profile/service/impl/ProfileServiceImpl.java @@ -34,25 +34,25 @@ public class ProfileServiceImpl implements ProfileService { @Override @Transactional(readOnly = true) - public List getAlbumSnap(String ownLoginId, String targetLoginId) { + public List getAlbumSnap(String reqLoginId, String targetLoginId) { User targetUser = userRepository.findByLoginId(targetLoginId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); - return profileRepository.findAlbumSnap(targetUser, ownLoginId.equals(targetLoginId)); + return profileRepository.findAlbumSnap(targetUser, reqLoginId.equals(targetLoginId)); } @Override @Transactional(readOnly = true) - public UserProfileResDto getUserProfile(String ownLoginId, String targetLoginId) { + public UserProfileResDto getUserProfile(String reqLoginId, String targetLoginId) { Boolean isFollow = null; User targetUser = userRepository.findByLoginId(targetLoginId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); - if(!ownLoginId.equals(targetLoginId)){ - User ownUser = userRepository.findByLoginId(ownLoginId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); - isFollow = friendService.checkIsFollow(ownUser,targetUser); + if(!reqLoginId.equals(targetLoginId)){ + User reqUser = userRepository.findByLoginId(reqLoginId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + isFollow = friendService.checkIsFollow(reqUser, targetUser); } - String profileURL = urlComponent.makeProfileURL(targetUser.getProfilePhoto().getId()); + String profileURL = urlComponent.makeProfileURL(targetUser.getProfilePhoto().getProfilePhotoId()); return UserProfileResDto.toDto(targetUser, profileURL, isFollow); } diff --git a/src/main/java/me/snaptime/profilePhoto/domain/ProfilePhoto.java b/src/main/java/me/snaptime/profilePhoto/domain/ProfilePhoto.java index 1cf4ad1d..00ff2e39 100644 --- a/src/main/java/me/snaptime/profilePhoto/domain/ProfilePhoto.java +++ b/src/main/java/me/snaptime/profilePhoto/domain/ProfilePhoto.java @@ -17,7 +17,7 @@ public class ProfilePhoto extends BaseTimeEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "profile_photo_id") - private Long id; + private Long profilePhotoId; @Column(name = "profile_photo_path",nullable = false) private String profilePhotoPath; diff --git a/src/main/java/me/snaptime/profilePhoto/dto/res/ProfilePhotoResDto.java b/src/main/java/me/snaptime/profilePhoto/dto/res/ProfilePhotoResDto.java index 7ce334d3..c2fecdc6 100644 --- a/src/main/java/me/snaptime/profilePhoto/dto/res/ProfilePhotoResDto.java +++ b/src/main/java/me/snaptime/profilePhoto/dto/res/ProfilePhotoResDto.java @@ -5,13 +5,13 @@ @Builder public record ProfilePhotoResDto( - Long id, + Long profilePhotoId, String profilePhotoName, String profilePhotoPath ){ public static ProfilePhotoResDto toDto(ProfilePhoto profilePhoto){ return ProfilePhotoResDto.builder() - .id(profilePhoto.getId()) + .profilePhotoId(profilePhoto.getProfilePhotoId()) .profilePhotoName(profilePhoto.getProfilePhotoName()) .profilePhotoPath(profilePhoto.getProfilePhotoPath()) .build(); diff --git a/src/main/java/me/snaptime/profilePhoto/repository/ProfilePhotoRepository.java b/src/main/java/me/snaptime/profilePhoto/repository/ProfilePhotoRepository.java index ba881ff7..83ea5098 100644 --- a/src/main/java/me/snaptime/profilePhoto/repository/ProfilePhotoRepository.java +++ b/src/main/java/me/snaptime/profilePhoto/repository/ProfilePhotoRepository.java @@ -9,6 +9,6 @@ @Repository public interface ProfilePhotoRepository extends JpaRepository{ - Optional findProfilePhotoByUser(User user); + Optional findProfilePhotoByUser(User reqUser); } diff --git a/src/main/java/me/snaptime/profilePhoto/service/impl/ProfilePhotoServiceImpl.java b/src/main/java/me/snaptime/profilePhoto/service/impl/ProfilePhotoServiceImpl.java index 97873f89..6cc6ef52 100644 --- a/src/main/java/me/snaptime/profilePhoto/service/impl/ProfilePhotoServiceImpl.java +++ b/src/main/java/me/snaptime/profilePhoto/service/impl/ProfilePhotoServiceImpl.java @@ -74,7 +74,7 @@ public byte[] downloadPhotoFromFileSystem(Long profilePhotoId){ @Transactional public ProfilePhotoResDto updatePhotoFromFileSystem(String loginId, MultipartFile updateFile) throws Exception{ User updateUser = userRepository.findByLoginId(loginId).orElseThrow(()-> new CustomException(ExceptionCode.USER_NOT_EXIST)); - ProfilePhoto profilePhoto = profilePhotoRepository.findById(updateUser.getProfilePhoto().getId()).orElseThrow(()-> new CustomException(ExceptionCode.PROFILE_PHOTO_NOT_FOUND)); + ProfilePhoto profilePhoto = profilePhotoRepository.findById(updateUser.getProfilePhoto().getProfilePhotoId()).orElseThrow(()-> new CustomException(ExceptionCode.PROFILE_PHOTO_NOT_FOUND)); String updateFileName = ProfilePhotoNameGenerator.generatorProfilePhotoName(updateFile.getOriginalFilename()); String updateFilePath = FOLDER_PATH + updateFileName; diff --git a/src/main/java/me/snaptime/redis/RedisConfig.java b/src/main/java/me/snaptime/redis/RedisConfig.java new file mode 100644 index 00000000..b8c023fb --- /dev/null +++ b/src/main/java/me/snaptime/redis/RedisConfig.java @@ -0,0 +1,43 @@ +package me.snaptime.redis; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +@Configuration +public class RedisConfig { + + @Value("${spring.data.redis.host}") + private String host; + + @Value("${spring.data.redis.port}") + private int port; + + @Bean + public RedisConnectionFactory redisConnectionFactory(){ + RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(host, port); + return new LettuceConnectionFactory(config); + } + + @Bean + public RedisTemplate redisTemplate(){ + RedisTemplate redisTemplate = new RedisTemplate<>(); + redisTemplate.setConnectionFactory(redisConnectionFactory()); + redisTemplate.setKeySerializer(new StringRedisSerializer()); + + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new JavaTimeModule()); + Jackson2JsonRedisSerializer valueSerializer = new Jackson2JsonRedisSerializer<>(mapper, Object.class); + redisTemplate.setValueSerializer(valueSerializer); + + return redisTemplate; + } +} diff --git a/src/main/java/me/snaptime/redis/RefreshToken.java b/src/main/java/me/snaptime/redis/RefreshToken.java new file mode 100644 index 00000000..9b1ada8b --- /dev/null +++ b/src/main/java/me/snaptime/redis/RefreshToken.java @@ -0,0 +1,21 @@ +package me.snaptime.redis; + +import jakarta.persistence.Id; +import lombok.Getter; +import org.springframework.data.redis.core.RedisHash; +import org.springframework.data.redis.core.index.Indexed; + +@Getter +@RedisHash(value = "refreshToken", timeToLive = 86400) +public class RefreshToken { + private String refreshToken; + + @Id + @Indexed + private Long id; + + public RefreshToken(Long id, String refreshToken){ + this.refreshToken = refreshToken; + this.id = id; + } +} diff --git a/src/main/java/me/snaptime/redis/RefreshTokenRepository.java b/src/main/java/me/snaptime/redis/RefreshTokenRepository.java new file mode 100644 index 00000000..c739e38e --- /dev/null +++ b/src/main/java/me/snaptime/redis/RefreshTokenRepository.java @@ -0,0 +1,9 @@ +package me.snaptime.redis; + +import org.springframework.data.repository.CrudRepository; + +import java.util.Optional; + +public interface RefreshTokenRepository extends CrudRepository { + Optional findById(Long userId); +} diff --git a/src/main/java/me/snaptime/reply/repository/impl/ChildReplyPagingRepositoryImpl.java b/src/main/java/me/snaptime/reply/repository/impl/ChildReplyPagingRepositoryImpl.java index b90f8731..4734222b 100644 --- a/src/main/java/me/snaptime/reply/repository/impl/ChildReplyPagingRepositoryImpl.java +++ b/src/main/java/me/snaptime/reply/repository/impl/ChildReplyPagingRepositoryImpl.java @@ -33,11 +33,11 @@ public List findReplyList(Long parentReplyId, Long pageNum) { List result = jpaQueryFactory.select( childReply.childReplyId,childReply.content,childReply.parentReply.parentReplyId, writerUser.name,writerUser.loginId,tagUser.name,tagUser.loginId, - writerUser.profilePhoto.id, childReply.lastModifiedDate + writerUser.profilePhoto.profilePhotoId, childReply.lastModifiedDate ) .from(childReply) - .leftJoin(tagUser).on(childReply.replyTagUser.id.eq(tagUser.id)) - .join(writerUser).on(childReply.user.id.eq(writerUser.id)) + .leftJoin(tagUser).on(childReply.replyTagUser.userId.eq(tagUser.userId)) + .join(writerUser).on(childReply.user.userId.eq(writerUser.userId)) .where(childReply.parentReply.parentReplyId.eq(parentReplyId)) .orderBy(createOrderSpecifier()) .offset(pageable.getOffset()) diff --git a/src/main/java/me/snaptime/reply/repository/impl/ParentReplyPagingRepositoryImpl.java b/src/main/java/me/snaptime/reply/repository/impl/ParentReplyPagingRepositoryImpl.java index 1f82377c..f7b29765 100644 --- a/src/main/java/me/snaptime/reply/repository/impl/ParentReplyPagingRepositoryImpl.java +++ b/src/main/java/me/snaptime/reply/repository/impl/ParentReplyPagingRepositoryImpl.java @@ -29,11 +29,11 @@ public List findReplyList(Long snapId,Long pageNum) { Pageable pageable= PageRequest.of((int) (pageNum-1),20); List result = jpaQueryFactory.select( - user.loginId,user.profilePhoto.id,user.name, + user.loginId,user.profilePhoto.profilePhotoId,user.name, parentReply.content,parentReply.parentReplyId,parentReply.lastModifiedDate ) .from(parentReply) - .join(user).on(parentReply.user.id.eq(user.id)) + .join(user).on(parentReply.user.userId.eq(user.userId)) .where(parentReply.snap.id.eq(snapId)) .orderBy(createOrderSpecifier()) .offset(pageable.getOffset()) diff --git a/src/main/java/me/snaptime/reply/service/impl/ReplyServiceImpl.java b/src/main/java/me/snaptime/reply/service/impl/ReplyServiceImpl.java index 2a74d754..3e608cdf 100644 --- a/src/main/java/me/snaptime/reply/service/impl/ReplyServiceImpl.java +++ b/src/main/java/me/snaptime/reply/service/impl/ReplyServiceImpl.java @@ -105,7 +105,7 @@ public FindParentReplyResDto readParentReply(Long snapId, Long pageNum){ List parentReplyInfoList = result.stream().map(entity -> { - String profilePhotoURL = urlComponent.makeProfileURL(entity.get(user.profilePhoto.id)); + String profilePhotoURL = urlComponent.makeProfileURL(entity.get(user.profilePhoto.profilePhotoId)); String timeAgo = TimeAgoCalculator.findTimeAgo(entity.get(parentReply.lastModifiedDate)); return ParentReplyInfo.toDto(entity,profilePhotoURL,timeAgo); }).collect(Collectors.toList()); @@ -121,7 +121,7 @@ public FindChildReplyResDto readChildReply(Long parentReplyId, Long pageNum){ List childReplyInfoList = result.stream().map(entity -> { - String profilePhotoURL = urlComponent.makeProfileURL(entity.get(writerUser.profilePhoto.id)); + String profilePhotoURL = urlComponent.makeProfileURL(entity.get(writerUser.profilePhoto.profilePhotoId)); String timeAgo = TimeAgoCalculator.findTimeAgo(entity.get(childReply.lastModifiedDate)); return ChildReplyInfo.toDto(entity,profilePhotoURL,timeAgo); diff --git a/src/main/java/me/snaptime/snap/repository/impl/SnapPagingRepositoryImpl.java b/src/main/java/me/snaptime/snap/repository/impl/SnapPagingRepositoryImpl.java index b1ec6a25..698ebef5 100644 --- a/src/main/java/me/snaptime/snap/repository/impl/SnapPagingRepositoryImpl.java +++ b/src/main/java/me/snaptime/snap/repository/impl/SnapPagingRepositoryImpl.java @@ -33,12 +33,12 @@ public List findSnapPaging(Long pageNum, User reqUser) { Pageable pageable= PageRequest.of((int) (pageNum-1),10); List result = jpaQueryFactory.select( - user.loginId, user.profilePhoto.id, user.name, + user.loginId, user.profilePhoto.profilePhotoId, user.name, snap.id, snap.createdDate, snap.lastModifiedDate, snap.oneLineJournal, snap.fileName ).distinct() .from(friend) - .rightJoin(user).on(friend.receiver.id.eq(user.id)) - .join(snap).on(snap.user.id.eq(user.id)) + .rightJoin(user).on(friend.receiver.userId.eq(user.userId)) + .join(snap).on(snap.user.userId.eq(user.userId)) .where(getBuilder(reqUser)) .orderBy(createOrderSpecifier()) .offset(pageable.getOffset()) @@ -60,7 +60,7 @@ private OrderSpecifier createOrderSpecifier() { private BooleanBuilder getBuilder(User reqUser){ BooleanBuilder builder = new BooleanBuilder(); - builder.and( friend.sender.id.eq(reqUser.getId()).and(snap.isPrivate.isFalse()) ); + builder.and( friend.sender.userId.eq(reqUser.getUserId()).and(snap.isPrivate.isFalse()) ); builder.or( user.eq(reqUser).and(snap.isPrivate.isFalse()) ); return builder; diff --git a/src/main/java/me/snaptime/snap/service/impl/SnapPagingServiceImpl.java b/src/main/java/me/snaptime/snap/service/impl/SnapPagingServiceImpl.java index 25b1ee6c..5582c331 100644 --- a/src/main/java/me/snaptime/snap/service/impl/SnapPagingServiceImpl.java +++ b/src/main/java/me/snaptime/snap/service/impl/SnapPagingServiceImpl.java @@ -46,7 +46,7 @@ public FindSnapPagingResDto findSnapPaging(String loginId, Long pageNum){ List snapPagingInfoList = result.stream().map(entity -> { Long snapId = entity.get(snap.id); - String profilePhotoURL = urlComponent.makeProfileURL(entity.get(user.profilePhoto.id)); + String profilePhotoURL = urlComponent.makeProfileURL(entity.get(user.profilePhoto.profilePhotoId)); String snapPhotoURL = urlComponent.makePhotoURL(entity.get(snap.fileName),false); return SnapPagingInfo.toDto(entity,profilePhotoURL,snapPhotoURL, diff --git a/src/main/java/me/snaptime/snap/service/impl/SnapServiceImpl.java b/src/main/java/me/snaptime/snap/service/impl/SnapServiceImpl.java index 2f1f9441..dd97286c 100644 --- a/src/main/java/me/snaptime/snap/service/impl/SnapServiceImpl.java +++ b/src/main/java/me/snaptime/snap/service/impl/SnapServiceImpl.java @@ -89,12 +89,12 @@ public FindSnapResDto findSnap(Long id, String uId) { if(foundSnap.isPrivate()) { User foundUser = userRepository.findByLoginId(uId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); // Snap이 비공개라면, 요청한 유저와 스냅의 ID가 일치하는지 확인한다. - if (!Objects.equals(foundUser.getId(), foundSnap.getUser().getId())) { + if (!Objects.equals(foundUser.getUserId(), foundSnap.getUser().getUserId())) { throw new CustomException(ExceptionCode.SNAP_IS_PRIVATE); } } String snapPhotoUrl = urlComponent.makePhotoURL(foundSnap.getFileName(), foundSnap.isPrivate()); - String profilePhotoUrl = urlComponent.makeProfileURL(foundSnap.getUser().getProfilePhoto().getId()); + String profilePhotoUrl = urlComponent.makeProfileURL(foundSnap.getUser().getProfilePhoto().getProfilePhotoId()); return FindSnapResDto.entityToResDto(foundSnap, snapPhotoUrl, profilePhotoUrl); } @@ -104,7 +104,7 @@ public Long modifySnap(Long snapId, ModifySnapReqDto modifySnapReqDto, String us User foundUser = userRepository.findByLoginId(userUid).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); // 수정하려는 유저와 수정되려는 스냅의 저자가 일치하는지 확인한다. - if (!foundSnap.getUser().getId().equals(foundUser.getId())) { + if (!foundSnap.getUser().getUserId().equals(foundUser.getUserId())) { throw new CustomException(ExceptionCode.SNAP_USER_IS_NOT_THE_SAME); } @@ -214,7 +214,7 @@ public void deleteSnap(Long snapId, String uId) { User foundUser = userRepository.findByLoginId(uId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); // 삭제를 요청한 사용자가 Snap를 만든 사용자인지 확인한다. - if (!Objects.equals(foundSnap.getUser().getId(), foundUser.getId())) { + if (!Objects.equals(foundSnap.getUser().getUserId(), foundUser.getUserId())) { // 다르다면 에러를 던진다. throw new CustomException(ExceptionCode.SNAP_USER_IS_NOT_THE_SAME); } @@ -246,7 +246,7 @@ public void relocateSnap(Long snapId, Long albumId, String uId) { Album foundAlbum = albumRepository.findById(albumId).orElseThrow(() -> new CustomException(ExceptionCode.ALBUM_NOT_EXIST)); User foundUser = userRepository.findByLoginId(uId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); // 찾은 Snap의 소유자가 요청자와 일치하고, 새로 옮길 앨범의 소유자가 요청자와 일치한다면 - if (Objects.equals(foundSnap.getUser().getId(), foundUser.getId()) && Objects.equals(foundSnap.getAlbum().getUser().getId(), foundUser.getId())) { + if (Objects.equals(foundSnap.getUser().getUserId(), foundUser.getUserId()) && Objects.equals(foundSnap.getAlbum().getUser().getUserId(), foundUser.getUserId())) { // 새로 연관관계를 맺어주고 DB에 반영한다. foundSnap.associateAlbum(foundAlbum); snapRepository.save(foundSnap); diff --git a/src/main/java/me/snaptime/user/controller/UserController.java b/src/main/java/me/snaptime/user/controller/UserController.java index 54e22db8..a78c2591 100644 --- a/src/main/java/me/snaptime/user/controller/UserController.java +++ b/src/main/java/me/snaptime/user/controller/UserController.java @@ -2,6 +2,7 @@ import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import jakarta.validation.constraints.NotBlank; import lombok.RequiredArgsConstructor; @@ -48,8 +49,8 @@ public ResponseEntity> getUser(@AuthenticationPrin "
Token을 버리고 재 login을 유도해야 합니다.") @PatchMapping() public ResponseEntity> changeUser(@AuthenticationPrincipal UserDetails principal, - @Valid @RequestBody UserUpdateReqDto userUpdateDto){ - UserResDto userResDto = userService.updateUser(principal.getUsername(), userUpdateDto); + @Valid @RequestBody UserUpdateReqDto userUpdateReqDto){ + UserResDto userResDto = userService.updateUser(principal.getUsername(), userUpdateReqDto); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "유저 정보 수정이 성공적으로 완료되었습니다.", @@ -94,11 +95,23 @@ public ResponseEntity> signUp(@Valid @RequestBody @Operation(summary = "로그인", description = "회원 가입 한 유저의 loginId와 password를 입력합니다.") @PostMapping("/sign-in") public ResponseEntity> signIn(@Valid @RequestBody SignInReqDto signInReqDto){ - SignInResDto signInResponseDto = signService.signIn(signInReqDto); + SignInResDto signInResDto = signService.signIn(signInReqDto); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "유저 로그인을 성공적으로 완료하였습니다.", - signInResponseDto)); + signInResDto)); + } + + @Operation(summary = "엑세스 토큰 재발급", description = "RefreshToken 을 통해 AccessToken 재발급") + @PostMapping("/reissue") + public ResponseEntity> reissue(HttpServletRequest request){ + SignInResDto signInResDto = signService.reissueAccessToken(request); + + return ResponseEntity.status(HttpStatus.OK).body( + new CommonResponseDto<>( + "리프레시 토큰으로 엑세스 토큰 재발급 성공", + signInResDto + )); } } diff --git a/src/main/java/me/snaptime/user/domain/User.java b/src/main/java/me/snaptime/user/domain/User.java index ea56d28c..e201941d 100644 --- a/src/main/java/me/snaptime/user/domain/User.java +++ b/src/main/java/me/snaptime/user/domain/User.java @@ -27,7 +27,7 @@ public class User extends BaseTimeEntity implements UserDetails{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "user_id") - private Long id; + private Long userId; @Column(name = "user_name",nullable = false) private String name; diff --git a/src/main/java/me/snaptime/user/dto/res/SignInResDto.java b/src/main/java/me/snaptime/user/dto/res/SignInResDto.java index db6b8c46..f43f0a17 100644 --- a/src/main/java/me/snaptime/user/dto/res/SignInResDto.java +++ b/src/main/java/me/snaptime/user/dto/res/SignInResDto.java @@ -5,6 +5,7 @@ @Builder public record SignInResDto( - String accessToken + String accessToken, + String refreshToken ) {} diff --git a/src/main/java/me/snaptime/user/dto/res/UserResDto.java b/src/main/java/me/snaptime/user/dto/res/UserResDto.java index 2fff2a70..ac82c027 100644 --- a/src/main/java/me/snaptime/user/dto/res/UserResDto.java +++ b/src/main/java/me/snaptime/user/dto/res/UserResDto.java @@ -6,7 +6,7 @@ @Builder public record UserResDto( - Long id, + Long userId, String name, String loginId, String email, @@ -14,7 +14,7 @@ public record UserResDto( ){ public static UserResDto toDto(User user){ return UserResDto.builder() - .id(user.getId()) + .userId(user.getUserId()) .name(user.getName()) .loginId(user.getLoginId()) .email(user.getEmail()) diff --git a/src/main/java/me/snaptime/user/service/SignService.java b/src/main/java/me/snaptime/user/service/SignService.java index ef17c08e..1cb5fa1b 100644 --- a/src/main/java/me/snaptime/user/service/SignService.java +++ b/src/main/java/me/snaptime/user/service/SignService.java @@ -1,5 +1,6 @@ package me.snaptime.user.service; +import jakarta.servlet.http.HttpServletRequest; import me.snaptime.user.dto.req.SignInReqDto; import me.snaptime.user.dto.req.UserReqDto; import me.snaptime.user.dto.res.SignInResDto; @@ -8,7 +9,10 @@ public interface SignService { /* 회원 가입 하는 메서드 */ - public UserResDto signUp(UserReqDto userRequestDto); + public UserResDto signUp(UserReqDto userReqDto); /* 로그인 하는 메서드, accessToken을 리턴한다 */ - public SignInResDto signIn(SignInReqDto signInRequestDto); + public SignInResDto signIn(SignInReqDto signInReqDto); + + /* 헤더에 담긴 RefreshToken 을 통해 AccessToken을 재발급합니다 */ + public SignInResDto reissueAccessToken(HttpServletRequest request); } diff --git a/src/main/java/me/snaptime/user/service/UserService.java b/src/main/java/me/snaptime/user/service/UserService.java index 6dd719e5..3e2da3e5 100644 --- a/src/main/java/me/snaptime/user/service/UserService.java +++ b/src/main/java/me/snaptime/user/service/UserService.java @@ -5,7 +5,7 @@ public interface UserService { public UserResDto getUser(String loginId); - public UserResDto updateUser(String loginId, UserUpdateReqDto userUpdateDto); + public UserResDto updateUser(String loginId, UserUpdateReqDto userUpdateReqDto); public void deleteUser(String loginId); public void updatePassword(String loginId, String password); } diff --git a/src/main/java/me/snaptime/user/service/impl/SignServiceImpl.java b/src/main/java/me/snaptime/user/service/impl/SignServiceImpl.java index e22312b8..7e7f4b5b 100644 --- a/src/main/java/me/snaptime/user/service/impl/SignServiceImpl.java +++ b/src/main/java/me/snaptime/user/service/impl/SignServiceImpl.java @@ -1,5 +1,6 @@ package me.snaptime.user.service.impl; +import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.snaptime.exception.CustomException; @@ -7,6 +8,8 @@ import me.snaptime.jwt.JwtProvider; import me.snaptime.profilePhoto.domain.ProfilePhoto; import me.snaptime.profilePhoto.repository.ProfilePhotoRepository; +import me.snaptime.redis.RefreshToken; +import me.snaptime.redis.RefreshTokenRepository; import me.snaptime.user.domain.User; import me.snaptime.user.dto.req.SignInReqDto; import me.snaptime.user.dto.req.UserReqDto; @@ -30,12 +33,13 @@ public class SignServiceImpl implements SignService { private final ProfilePhotoRepository profilePhotoRepository; private final PasswordEncoder passwordEncoder; private final JwtProvider jwtProvider; + private final RefreshTokenRepository refreshTokenRepository; @Override - public UserResDto signUp(UserReqDto userRequestDto) { + public UserResDto signUp(UserReqDto userReqDto) { //로그인 id가 이미 존재하는지 확인 - if(userRepository.findByLoginId(userRequestDto.loginId()).isPresent()){ + if(userRepository.findByLoginId(userReqDto.loginId()).isPresent()){ throw new CustomException(ExceptionCode.LOGIN_ID_ALREADY_EXIST); } @@ -51,11 +55,11 @@ public UserResDto signUp(UserReqDto userRequestDto) { //새로운 사용자 객체 생성 User user = User.builder() - .name(userRequestDto.name()) - .loginId(userRequestDto.loginId()) - .password(passwordEncoder.encode(userRequestDto.password())) - .email(userRequestDto.email()) - .birthDay(userRequestDto.birthDay()) + .name(userReqDto.name()) + .loginId(userReqDto.loginId()) + .password(passwordEncoder.encode(userReqDto.password())) + .email(userReqDto.email()) + .birthDay(userReqDto.birthDay()) //단일 권한을 가진 리스트 생성, 하나의 요소를 가진 불변의 리스트 생성 .roles(Collections.singletonList("ROLE_USER")) .profilePhoto(profilePhoto) @@ -66,18 +70,45 @@ public UserResDto signUp(UserReqDto userRequestDto) { @Override @Transactional(readOnly = true) - public SignInResDto signIn(SignInReqDto signInRequestDto) { - User user = userRepository.findByLoginId(signInRequestDto.loginId()).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + public SignInResDto signIn(SignInReqDto signInReqDto) { + User user = userRepository.findByLoginId(signInReqDto.loginId()).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); - if (!passwordEncoder.matches(signInRequestDto.password(), user.getPassword())) { + if (!passwordEncoder.matches(signInReqDto.password(), user.getPassword())) { throw new CustomException(ExceptionCode.PASSWORD_NOT_EQUAL); } - String accessToken = jwtProvider.createAccessToken(user.getLoginId(), user.getRoles()); + String accessToken = jwtProvider.createAccessToken(user.getUserId(), user.getLoginId(), user.getRoles()); + String refreshToken = jwtProvider.createRefreshToken(user.getUserId(), user.getLoginId(),user.getRoles()); + refreshTokenRepository.save(new RefreshToken(user.getUserId(),refreshToken)); - SignInResDto signInResponseDto = SignInResDto.builder() + return SignInResDto.builder() .accessToken(accessToken) + .refreshToken(refreshToken) .build(); + } + + public SignInResDto reissueAccessToken(HttpServletRequest request){ + + String token = jwtProvider.getAuthorizationToken(request); + Long userId = jwtProvider.getUserId(token); + + RefreshToken refreshToken = refreshTokenRepository.findById(userId).orElseThrow(()-> new CustomException(ExceptionCode.INVALID_REFRESH_TOKEN)); + + if(!refreshToken.getRefreshToken().equals(token)) { + throw new CustomException(ExceptionCode.INVALID_REFRESH_TOKEN); + } + + User user = userRepository.findById(userId).orElseThrow(()-> new CustomException(ExceptionCode.USER_NOT_EXIST)); + + String newAccessToken = jwtProvider.createAccessToken(userId,user.getLoginId(),user.getRoles()); + String newRefreshToken = jwtProvider.createRefreshToken(userId,user.getLoginId(),user.getRoles()); + + SignInResDto signInResDto = SignInResDto.builder() + .accessToken(newAccessToken) + .refreshToken(newRefreshToken) + .build(); + + refreshTokenRepository.save(new RefreshToken(userId, newRefreshToken)); - return signInResponseDto; + return signInResDto; } } diff --git a/src/main/java/me/snaptime/user/service/impl/UserServiceImpl.java b/src/main/java/me/snaptime/user/service/impl/UserServiceImpl.java index 3f07689b..166eab3d 100644 --- a/src/main/java/me/snaptime/user/service/impl/UserServiceImpl.java +++ b/src/main/java/me/snaptime/user/service/impl/UserServiceImpl.java @@ -31,27 +31,27 @@ public UserResDto getUser(String loginId) { return UserResDto.toDto(user); } - public UserResDto updateUser(String loginId, UserUpdateReqDto userUpdateDto) { + public UserResDto updateUser(String loginId, UserUpdateReqDto userUpdateReqDto) { User user = userRepository.findByLoginId(loginId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); - if (userUpdateDto.name() != null && !userUpdateDto.name().isEmpty()) { - user.updateUserName(userUpdateDto.name()); + if (userUpdateReqDto.name() != null && !userUpdateReqDto.name().isEmpty()) { + user.updateUserName(userUpdateReqDto.name()); } - if (userUpdateDto.email() != null && !userUpdateDto.email().isEmpty()) { - user.updateUserEmail(userUpdateDto.email()); + if (userUpdateReqDto.email() != null && !userUpdateReqDto.email().isEmpty()) { + user.updateUserEmail(userUpdateReqDto.email()); } - if (userUpdateDto.birthDay() != null && !userUpdateDto.birthDay().isEmpty()) { - user.updateUserBirthDay(userUpdateDto.birthDay()); + if (userUpdateReqDto.birthDay() != null && !userUpdateReqDto.birthDay().isEmpty()) { + user.updateUserBirthDay(userUpdateReqDto.birthDay()); } return UserResDto.toDto(user); } public void deleteUser(String loginId) { User user = userRepository.findByLoginId(loginId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); - userRepository.deleteById(user.getId()); + userRepository.deleteById(user.getUserId()); } public void updatePassword(String loginId, String password){ diff --git a/src/test/java/me/snaptime/snap/controller/SnapPagingControllerTest.java b/src/test/java/me/snaptime/snap/controller/SnapPagingControllerTest.java index 4d9814a3..4b6abde8 100644 --- a/src/test/java/me/snaptime/snap/controller/SnapPagingControllerTest.java +++ b/src/test/java/me/snaptime/snap/controller/SnapPagingControllerTest.java @@ -35,6 +35,9 @@ public class SnapPagingControllerTest { @MockBean private UserDetailsServiceImpl userDetailsService; + //프로퍼티 값 주입을 위함. accessTokenValidTime, refreshTokenValidTime + @MockBean JwtProvider jwtProvider; + @Autowired private MockMvc mockMvc; diff --git a/src/test/java/me/snaptime/snap/service/SnapPagingServiceImplTest.java b/src/test/java/me/snaptime/snap/service/SnapPagingServiceImplTest.java index 3de61c42..841b514e 100644 --- a/src/test/java/me/snaptime/snap/service/SnapPagingServiceImplTest.java +++ b/src/test/java/me/snaptime/snap/service/SnapPagingServiceImplTest.java @@ -71,9 +71,9 @@ public void findSnapPagingTest1(){ given(tuple1.get(snap.id)).willReturn(1L); given(tuple2.get(snap.id)).willReturn(2L); given(tuple3.get(snap.id)).willReturn(3L); - given(tuple1.get(user.profilePhoto.id)).willReturn(1L); - given(tuple2.get(user.profilePhoto.id)).willReturn(2L); - given(tuple3.get(user.profilePhoto.id)).willReturn(3L); + given(tuple1.get(user.profilePhoto.profilePhotoId)).willReturn(1L); + given(tuple2.get(user.profilePhoto.profilePhotoId)).willReturn(2L); + given(tuple3.get(user.profilePhoto.profilePhotoId)).willReturn(3L); given(tuple1.get(snap.oneLineJournal)).willReturn("일기1"); given(tuple2.get(snap.oneLineJournal)).willReturn("일기2"); given(tuple3.get(snap.oneLineJournal)).willReturn("일기3"); diff --git a/src/test/java/me/snaptime/social/controller/FriendControllerTest.java b/src/test/java/me/snaptime/social/controller/FriendControllerTest.java index d7b0509d..073728ca 100644 --- a/src/test/java/me/snaptime/social/controller/FriendControllerTest.java +++ b/src/test/java/me/snaptime/social/controller/FriendControllerTest.java @@ -35,6 +35,10 @@ public class FriendControllerTest { @MockBean private UserDetailsServiceImpl userDetailsService; + //프로퍼티 값 주입을 위함. accessTokenValidTime, refreshTokenValidTime + @MockBean + private JwtProvider jwtProvider; + @Autowired private MockMvc mockMvc; diff --git a/src/test/java/me/snaptime/social/controller/ReplyControllerTest.java b/src/test/java/me/snaptime/social/controller/ReplyControllerTest.java index c7f465a4..28cad735 100644 --- a/src/test/java/me/snaptime/social/controller/ReplyControllerTest.java +++ b/src/test/java/me/snaptime/social/controller/ReplyControllerTest.java @@ -37,6 +37,10 @@ public class ReplyControllerTest { @MockBean private UserDetailsServiceImpl userDetailsService; + //프로퍼티 값 주입을 위함. accessTokenValidTime, refreshTokenValidTime + @MockBean + private JwtProvider jwtProvider; + @Autowired private MockMvc mockMvc; diff --git a/src/test/java/me/snaptime/social/service/FriendServiceImplTest.java b/src/test/java/me/snaptime/social/service/FriendServiceImplTest.java index 9ae4214f..dc162ccd 100644 --- a/src/test/java/me/snaptime/social/service/FriendServiceImplTest.java +++ b/src/test/java/me/snaptime/social/service/FriendServiceImplTest.java @@ -67,8 +67,8 @@ public void sendFriendReqTest1(){ //given User sender = spy(user1); User receiver = spy(user1); - given(sender.getId()).willReturn(1L); - given(receiver.getId()).willReturn(2L); + given(sender.getUserId()).willReturn(1L); + given(receiver.getUserId()).willReturn(2L); given(userRepository.findByLoginId(any(String.class))) .willReturn(Optional.of(sender)) @@ -141,8 +141,8 @@ public void sendFriendReqTest5(){ //given User sender = spy(user1); User receiver = spy(user1); - given(sender.getId()).willReturn(1L); - given(receiver.getId()).willReturn(1L); + given(sender.getUserId()).willReturn(1L); + given(receiver.getUserId()).willReturn(1L); given(userRepository.findByLoginId(any(String.class))) .willReturn(Optional.of(sender)) @@ -290,9 +290,9 @@ public void findFriendListTest1(){ given(tuple2.get(user.loginId)).willReturn("testLoginId2"); given(tuple3.get(user.loginId)).willReturn("testLoginId3"); - given(tuple1.get(user.profilePhoto.id)).willReturn(4L); - given(tuple2.get(user.profilePhoto.id)).willReturn(5L); - given(tuple3.get(user.profilePhoto.id)).willReturn(6L); + given(tuple1.get(user.profilePhoto.profilePhotoId)).willReturn(4L); + given(tuple2.get(user.profilePhoto.profilePhotoId)).willReturn(5L); + given(tuple3.get(user.profilePhoto.profilePhotoId)).willReturn(6L); given(tuple1.get(user.name)).willReturn("name1"); given(tuple2.get(user.name)).willReturn("name2"); diff --git a/src/test/java/me/snaptime/user/controller/UserControllerTest.java b/src/test/java/me/snaptime/user/controller/UserControllerTest.java index a7ec13e5..73b387de 100644 --- a/src/test/java/me/snaptime/user/controller/UserControllerTest.java +++ b/src/test/java/me/snaptime/user/controller/UserControllerTest.java @@ -49,6 +49,10 @@ public class UserControllerTest { @MockBean private UserDetailsServiceImpl userDetailsService; + //프로퍼티 값 주입을 위함. accessTokenValidTime, refreshTokenValidTime + @MockBean + private JwtProvider jwtProvider; + @Test @WithMockUser(username = "kang4746",password = "test1234",roles = "USER") @DisplayName("유저 정보 조회 컨트롤러 테스트") @@ -91,7 +95,7 @@ void signUpTest() throws Exception{ given(signService.signUp(any(UserReqDto.class))) .willReturn(UserResDto.builder() - .id(1L) + .userId(1L) .loginId("kang4746") .name("홍길순") .email("strong@gmail.com") @@ -105,7 +109,7 @@ void signUpTest() throws Exception{ mockMvc.perform(post("/users/sign-up").content(content).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(jsonPath("$.msg").exists()) - .andExpect(jsonPath("$.result.id").exists()) + .andExpect(jsonPath("$.result.userId").exists()) .andExpect(jsonPath("$.result.loginId").exists()) .andExpect(jsonPath("$.result.email").exists()) .andExpect(jsonPath("$.result.birthDay").exists()) diff --git a/src/test/java/me/snaptime/user/service/ProfilePhotoServiceTest.java b/src/test/java/me/snaptime/user/service/ProfilePhotoServiceTest.java index b20f7195..05623cd1 100644 --- a/src/test/java/me/snaptime/user/service/ProfilePhotoServiceTest.java +++ b/src/test/java/me/snaptime/user/service/ProfilePhotoServiceTest.java @@ -80,7 +80,7 @@ void updatePhotoToFileSystemTest() throws Exception { .build(); given(mockuser.getProfilePhoto()).willReturn(mockProfile); - given(mockProfile.getId()).willReturn(1L); + given(mockProfile.getProfilePhotoId()).willReturn(1L); given(mockProfile.getProfilePhotoName()).willReturn("image"); given(mockProfile.getProfilePhotoPath()).willReturn("/image"); diff --git a/src/test/java/me/snaptime/user/service/UserServiceTest.java b/src/test/java/me/snaptime/user/service/UserServiceTest.java index 74567bb0..f9a7cef6 100644 --- a/src/test/java/me/snaptime/user/service/UserServiceTest.java +++ b/src/test/java/me/snaptime/user/service/UserServiceTest.java @@ -3,6 +3,8 @@ import me.snaptime.jwt.JwtProvider; import me.snaptime.profilePhoto.domain.ProfilePhoto; import me.snaptime.profilePhoto.repository.ProfilePhotoRepository; +import me.snaptime.redis.RefreshToken; +import me.snaptime.redis.RefreshTokenRepository; import me.snaptime.user.domain.User; import me.snaptime.user.dto.req.SignInReqDto; import me.snaptime.user.dto.req.UserReqDto; @@ -45,6 +47,9 @@ class UserServiceTest { @Mock private ProfilePhotoRepository profilePhotoRepository; + @Mock + private RefreshTokenRepository refreshTokenRepository; + @Mock private PasswordEncoder passwordEncoder; @@ -74,7 +79,7 @@ public void getUser() { UserResDto userResDto = userService.getUser("kang4746"); //then - Assertions.assertEquals(givenUser.getId(),userResDto.id()); + Assertions.assertEquals(givenUser.getUserId(),userResDto.userId()); Assertions.assertEquals(givenUser.getName(),userResDto.name()); Assertions.assertEquals(givenUser.getLoginId(),userResDto.loginId()); Assertions.assertEquals(givenUser.getEmail(),userResDto.email()); @@ -117,29 +122,34 @@ public void signUp() { @DisplayName("given_when_then 방식으로 signIn 서비스 성공 테스트") public void signIn(){ //given - SignInReqDto signInRequestDto = SignInReqDto.builder() + SignInReqDto signInReqDto = SignInReqDto.builder() .loginId("kang4746") .password("test1234") .build(); Mockito.when(userRepository.findByLoginId("kang4746")) .thenReturn(Optional.of(givenUser)); - Mockito.when(passwordEncoder.matches(signInRequestDto.password(), givenUser.getPassword())) + Mockito.when(passwordEncoder.matches(signInReqDto.password(), givenUser.getPassword())) .thenReturn(true); - Mockito.when(jwtProvider.createAccessToken(givenUser.getLoginId(), givenUser.getRoles())) - .thenReturn("mockToken"); + Mockito.when(jwtProvider.createAccessToken(givenUser.getUserId(),givenUser.getLoginId(), givenUser.getRoles())) + .thenReturn("mockAccessToken"); + Mockito.when(jwtProvider.createRefreshToken(givenUser.getUserId(),givenUser.getLoginId(), givenUser.getRoles())) + .thenReturn("mockRefreshToken"); + Mockito.when(refreshTokenRepository.save(any(RefreshToken.class))) + .then(returnsFirstArg()); //when - SignInResDto signInResponseDto = signService.signIn(signInRequestDto); + SignInResDto signInResDto = signService.signIn(signInReqDto); //then - Assertions.assertEquals("mockToken",signInResponseDto.accessToken()); - Assertions.assertEquals(signInRequestDto.loginId(),givenUser.getLoginId()); - Assertions.assertEquals(signInRequestDto.password(),givenUser.getPassword()); + Assertions.assertEquals("mockAccessToken",signInResDto.accessToken()); + Assertions.assertEquals("mockRefreshToken",signInResDto.refreshToken()); + Assertions.assertEquals(signInReqDto.loginId(),givenUser.getLoginId()); + Assertions.assertEquals(signInReqDto.password(),givenUser.getPassword()); verify(userRepository,times(1)).findByLoginId("kang4746"); - verify(passwordEncoder,times(1)).matches(signInRequestDto.password(),givenUser.getPassword()); - verify(jwtProvider,times(1)).createAccessToken(givenUser.getLoginId(),givenUser.getRoles()); + verify(passwordEncoder,times(1)).matches(signInReqDto.password(),givenUser.getPassword()); + verify(jwtProvider,times(1)).createAccessToken(givenUser.getUserId(),givenUser.getLoginId(),givenUser.getRoles()); } @@ -149,7 +159,7 @@ public void signIn(){ public void deleteUser() { //given User user = spy(givenUser); - given(user.getId()).willReturn(1L); + given(user.getUserId()).willReturn(1L); Mockito.when(userRepository.findByLoginId("kang4746")) .thenReturn(Optional.of(user)); From 48fdab92dc263c413def75c522112b62e7938716 Mon Sep 17 00:00:00 2001 From: hyeangjun Date: Sat, 20 Jul 2024 22:15:12 +0900 Subject: [PATCH 2/2] =?UTF-8?q?=EB=A1=9C=EA=B7=B8=20=EC=A4=84=EC=9D=B4?= =?UTF-8?q?=EA=B8=B0,=20=EB=B3=80=EC=88=98=EB=AA=85=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/me/snaptime/jwt/JwtProvider.java | 14 -------------- .../profile/controller/ProfileController.java | 8 ++++---- .../controller/ProfilePhotoController.java | 4 ++-- .../snaptime/user/controller/UserController.java | 16 ++++++++-------- 4 files changed, 14 insertions(+), 28 deletions(-) diff --git a/src/main/java/me/snaptime/jwt/JwtProvider.java b/src/main/java/me/snaptime/jwt/JwtProvider.java index 2d25f08c..b772035c 100644 --- a/src/main/java/me/snaptime/jwt/JwtProvider.java +++ b/src/main/java/me/snaptime/jwt/JwtProvider.java @@ -33,14 +33,10 @@ public class JwtProvider { @PostConstruct protected void init(){ - log.info("[init] JwtTokenProvide 내 secretKey 초기화 시작"); secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256); - log.info("[init] JwtTokenProvider 내 secretKey 초기화 완료"); } public String createAccessToken(Long userId, String loginId, List roles){ - log.info("[createAccessToken] 엑세스 토큰 생성 시작"); - Claims claims = Jwts.claims().setSubject(loginId); claims.put("userId",userId); claims.put("type","access"); @@ -53,13 +49,10 @@ public String createAccessToken(Long userId, String loginId, List roles) .signWith(secretKey) .compact(); - log.info("[createAccessToken] 엑세스 토큰 생성 완료"); return token; } public String createRefreshToken(Long id, String loginId, List roles){ - log.info("[createRefreshToken] 리프레시 토큰 생성 시작"); - Claims claims = Jwts.claims().setSubject(loginId); claims.put("userId", id); claims.put("type", "refresh"); @@ -71,13 +64,10 @@ public String createRefreshToken(Long id, String loginId, List roles){ .setExpiration(new Date(now.getTime() + refreshTokenValidTime)) .signWith(secretKey) .compact(); - - log.info("[createAccessToken] 엑세스 토큰 생성 완료"); return token; } public Long getUserId(String token) { - log.info("[getUserId] 토큰 기반 회원 구별 정보 추출"); Long userId = Long.valueOf(Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().get("userId").toString()); log.info("[getUserId] 토큰 기반 회원 구별 정보 추출 완료, userId : {}", userId); return userId; @@ -86,7 +76,6 @@ public Long getUserId(String token) { // 필터에서 인증 성공 후, SecurityContextHolder 에 저장할 Authentication 을 생성 //UsernamePasswordAuthenticationToken 클래스를 사용 public Authentication getAuthentication(String token){ - log.info("[getAuthentication] 토큰 인증 정보 조회 시작"); UserDetails userDetails = userDetailsService.loadUserByUsername(this.getUsername(token)); log.info("[getAuthentication] 토큰 인증 정보 조회 완료, UserDetails loginId : {}",userDetails.getUsername()); @@ -97,7 +86,6 @@ public Authentication getAuthentication(String token){ //Jwts.parser()를 통해 secretKey를 설정하고 클레임을 추출해서 토큰을 생성할 때 넣었던 sub값을 추출합니다. public String getUsername(String token) { - log.info("[getUsername] 토큰 기반 회원 구별 정보 추출"); String loginId = Jwts.parserBuilder() .setSigningKey(secretKey) .build() @@ -109,7 +97,6 @@ public String getUsername(String token) } public String getAuthorizationToken(HttpServletRequest request){ - log.info("[getAuthorizationToken] HTTP 헤더에서 Token 값 추출"); String token = request.getHeader("Authorization"); try{ if(!token.substring(0,"BEARER ".length()).equalsIgnoreCase("Bearer ")){ @@ -126,7 +113,6 @@ public String getAuthorizationToken(HttpServletRequest request){ 이 메소드는 토큰을 전달 받아 클레임의 유효기간을 체크하고 boolean 타입 값을 리턴하는 역할을 한다. */ public boolean validateToken(String token) { - log.info("[validateToken] 토큰 유효 체크 시작"); try{ //복잡한 설정일 떈, Jwts.parserBuilder()를 이용 Jws claims = Jwts.parser() diff --git a/src/main/java/me/snaptime/profile/controller/ProfileController.java b/src/main/java/me/snaptime/profile/controller/ProfileController.java index 763dead9..1b7ec9ff 100644 --- a/src/main/java/me/snaptime/profile/controller/ProfileController.java +++ b/src/main/java/me/snaptime/profile/controller/ProfileController.java @@ -40,10 +40,10 @@ public class ProfileController { "
다른 사람의 프로필 조회 -> snap이 전부 private이거나 없는 경우 앨범 리턴 x 그리고 private 인 snap 리턴 x") @Parameter(name = "targetLoginId", description = "앨범과 사진들을 가져오기 위한 loginId", required = true) @GetMapping("/album-snap") - public ResponseEntity>> getAlbumSnap(@AuthenticationPrincipal UserDetails principal, + public ResponseEntity>> getAlbumSnap(@AuthenticationPrincipal UserDetails userDetails, @RequestParam("targetLoginId") @NotBlank(message = "로그인 아이디 입력은 필수입니다.") String targetLoginId){ - String reqLoginId = principal.getUsername(); + String reqLoginId = userDetails.getUsername(); List albumSnapResDtos = profileService.getAlbumSnap(reqLoginId, targetLoginId); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( @@ -57,10 +57,10 @@ public ResponseEntity>> getAlbumSnap(@Au "
토큰이 없어도 해당 Api 엔드포인트를 요청할 수 있습니다.") @Parameter(name = "targetLoginId", description = "이름과 프로필 사진을 가져오기 위한 loginId", required = true) @GetMapping("/profile") - public ResponseEntity> getUserProfile(@AuthenticationPrincipal UserDetails principal, + public ResponseEntity> getUserProfile(@AuthenticationPrincipal UserDetails userDetails, @RequestParam("targetLoginId") @NotBlank(message = "로그인 아이디 입력은 필수입니다.") String targetLoginId){ - String reqLoginId = principal.getUsername(); + String reqLoginId = userDetails.getUsername(); UserProfileResDto userProfileResDto = profileService.getUserProfile(reqLoginId, targetLoginId); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( diff --git a/src/main/java/me/snaptime/profilePhoto/controller/ProfilePhotoController.java b/src/main/java/me/snaptime/profilePhoto/controller/ProfilePhotoController.java index b3097639..678d526c 100644 --- a/src/main/java/me/snaptime/profilePhoto/controller/ProfilePhotoController.java +++ b/src/main/java/me/snaptime/profilePhoto/controller/ProfilePhotoController.java @@ -42,9 +42,9 @@ public ResponseEntity downloadProfileToFileSystem(@PathVariable("profilePhoto @Operation(summary = "프로필 사진 수정",description = "유저의 프로필 사진을 수정 합니다." + "
유저의 Token 으로 유저를 구분짓습니다.") @PutMapping(consumes = MULTIPART_FORM_DATA) - public ResponseEntity updateProfileToFileSystem(@AuthenticationPrincipal UserDetails principal, + public ResponseEntity updateProfileToFileSystem(@AuthenticationPrincipal UserDetails userDetails, @RequestParam MultipartFile file) throws Exception { - String loginId = principal.getUsername(); + String loginId = userDetails.getUsername(); log.info("[updateProfile] 유저의 프로필 사진을 수정합니다. loginId : {}", loginId); ProfilePhotoResDto updateProfile = profilePhotoService.updatePhotoFromFileSystem(loginId, file); return ResponseEntity.status(HttpStatus.OK).body( diff --git a/src/main/java/me/snaptime/user/controller/UserController.java b/src/main/java/me/snaptime/user/controller/UserController.java index a78c2591..8bd5f7c4 100644 --- a/src/main/java/me/snaptime/user/controller/UserController.java +++ b/src/main/java/me/snaptime/user/controller/UserController.java @@ -35,8 +35,8 @@ public class UserController { @Operation(summary = "유저 정보 조회",description = "유저 번호로 유저 정보를 조회합니다. ") @GetMapping() - public ResponseEntity> getUser(@AuthenticationPrincipal UserDetails principal){ - UserResDto userResDto = userService.getUser(principal.getUsername()); + public ResponseEntity> getUser(@AuthenticationPrincipal UserDetails userDetails){ + UserResDto userResDto = userService.getUser(userDetails.getUsername()); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "유저 정보가 성공적으로 조회되었습니다.", @@ -48,9 +48,9 @@ public ResponseEntity> getUser(@AuthenticationPrin "
유저 loginId 수정 이후에는, Token의 loginId 정보와 현재 유저의 loginId가 다르므로," + "
Token을 버리고 재 login을 유도해야 합니다.") @PatchMapping() - public ResponseEntity> changeUser(@AuthenticationPrincipal UserDetails principal, + public ResponseEntity> changeUser(@AuthenticationPrincipal UserDetails userDetails, @Valid @RequestBody UserUpdateReqDto userUpdateReqDto){ - UserResDto userResDto = userService.updateUser(principal.getUsername(), userUpdateReqDto); + UserResDto userResDto = userService.updateUser(userDetails.getUsername(), userUpdateReqDto); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "유저 정보 수정이 성공적으로 완료되었습니다.", @@ -58,10 +58,10 @@ public ResponseEntity> changeUser(@AuthenticationP } @Operation(summary = "유저 비밀번호 수정",description = "해당 유저의 비밀번호를 수정합니다.") @PatchMapping("/password") - public ResponseEntity> changeUser(@AuthenticationPrincipal UserDetails principal, + public ResponseEntity> changeUser(@AuthenticationPrincipal UserDetails userDetails, @RequestParam("password") @NotBlank(message = "로그인 아이디 입력은 필수입니다.") String password) { - userService.updatePassword(principal.getUsername(), password); + userService.updatePassword(userDetails.getUsername(), password); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "유저 비밀번호 수정이 성공적으로 완료되었습니다.", @@ -71,8 +71,8 @@ public ResponseEntity> changeUser(@AuthenticationPrincip @Operation(summary = "유저 삭제",description = "유저 번호로 유저를 삭제합니다.") @DeleteMapping() - public ResponseEntity> deleteUser(@AuthenticationPrincipal UserDetails principal){ - userService.deleteUser(principal.getUsername()); + public ResponseEntity> deleteUser(@AuthenticationPrincipal UserDetails userDetails){ + userService.deleteUser(userDetails.getUsername()); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "유저 삭제가 성공적으로 완료되었습니다.",