Skip to content

Commit

Permalink
Merge pull request #66 from Nawabali-project/feature/59/totalLikesCount
Browse files Browse the repository at this point in the history
좋아요, 로컬좋아요 합계 계산 추가 및 기타 코드 수정,삭제
  • Loading branch information
juwum12 authored Apr 10, 2024
2 parents ac80951 + 3c4c9ee commit e3c24ab
Show file tree
Hide file tree
Showing 15 changed files with 118 additions and 56 deletions.
2 changes: 1 addition & 1 deletion .idea/compiler.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 10 additions & 3 deletions .idea/dataSources.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,4 @@ public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws-stomp").setAllowedOriginPatterns("*")
.withSockJS();
}
// 웹소켓
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@Controller
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class KakaoController {
Expand All @@ -22,11 +23,11 @@ public class KakaoController {

// 카카오 로그인 요청 처리
@GetMapping("/kakao/callback")
public ResponseEntity<UserDto.kakaoLoginResponseDto> kakaoLogin(@RequestParam String code,
public String kakaoLogin(@RequestParam String code,
HttpServletResponse response)
throws JsonProcessingException, IOException {

return kakaoService.kakaoLogin(code, response);

kakaoService.kakaoLogin(code, response);
return "redirect:/";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,18 +52,15 @@ public ResponseEntity<UserDto.deleteResponseDto> deleteUserInfo(@AuthenticationP

@Operation(summary = "닉네임 중복검사", description = "닉네임 중복여부를 boolean 값으로 반환.")
@GetMapping("/check-nickname")
public boolean checkNickname(@RequestBody String nickname){
public boolean checkNickname(@RequestParam("nickname") String nickname){
return userService.checkNickname(nickname);
}

@GetMapping("/test")
public String test(){
return "login";
@Operation(summary = "정보 수정을 위한 비밀 번호 확인", description = "입력한 비밀번호와 현재 비밀번호를 비교하여 boolean 값으로 반환")
@GetMapping("/check-myPassword")
public boolean checkMyPassword(@RequestParam("inputPassword") String inputPassword, @AuthenticationPrincipal UserDetailsImpl userDetails){
return userService.checkMyPassword(inputPassword, userDetails.getUser());
}

@GetMapping("test1")
public void test1(@AuthenticationPrincipal UserDetailsImpl userDetails){
System.out.println("userDetails.getUser() = " + userDetails.getUser().getEmail());
}

}
8 changes: 8 additions & 0 deletions src/main/java/com/nawabali/nawabali/dto/PostDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -165,4 +165,12 @@ public static class DeleteDto {
private String message;

}

@Getter
@Setter
@AllArgsConstructor
public static class getMyPostsResponseDto {

private Long id;
}
}
4 changes: 2 additions & 2 deletions src/main/java/com/nawabali/nawabali/dto/UserDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ public static class UserInfoResponseDto{
String city;
String district;
UserRankEnum rank;
Long localCount;
Long likesCount;
Long totalLikesCount;
Long totalLocalLikesCount;


public UserInfoResponseDto(User user) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public interface LikeRepository extends JpaRepository <Like, Long> {

Optional<Like> findByUserAndPost (User user, Post post);
Long countByPostIdAndLikeCategoryEnum(Long postId, LikeCategoryEnum likeCategory);
Like findByUserIdAndPostIdAndLikeCategoryEnum(Long id, Long postId, LikeCategoryEnum likeCategoryEnum);
Like findByUserIdAndPostIdAndLikeCategoryEnum(Long userId, Long postId, LikeCategoryEnum likeCategoryEnum);
Optional<Object> findFirstByPostIdAndUserIdAndLikeCategoryEnum(Long postId, Long userId, LikeCategoryEnum likeCategoryEnum);

}
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package com.nawabali.nawabali.repository;

import com.nawabali.nawabali.domain.Post;
import com.nawabali.nawabali.dto.PostDto;
import com.nawabali.nawabali.repository.querydsl.post.PostDslRepositoryCustom;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface PostRepository extends JpaRepository<Post, Long> , PostDslRepositoryCustom {
List<PostDto.getMyPostsResponseDto> findByUserId(Long userId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j(topic = "로그인 및 JWT 생성")
Expand Down Expand Up @@ -108,6 +109,18 @@ protected void successfulAuthentication(HttpServletRequest request, HttpServletR
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
log.info("로그인 실패");
// 로그인 성공 메시지를 JSON 형태로 응답 본문에 추가
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setStatus(401);

// 로그인 응답 메시지 설정
Map<String, String> failedMessage = new LinkedHashMap<>();
failedMessage.put("status", "401");
failedMessage.put("errorCode", "USER_NOT_FOUND");
failedMessage.put("message", "존재하지 않는 회원이거나 아이디 또는 비밀번호가 일치하지 않습니다.");

String jsonResponse = new ObjectMapper().writeValueAsString(failedMessage);
response.getWriter().write(jsonResponse);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;
Expand All @@ -17,35 +18,40 @@

@Component
@RequiredArgsConstructor
@Slf4j(topic = "LogoutHandler")
public class JwtLogoutHandler implements LogoutHandler {
private final JwtUtil jwtUtil;
private final RedisTool redisTool;
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
// 쿠키 삭제
log.info("쿠키삭제");
Cookie cookie = new Cookie(JwtUtil.AUTHORIZATION_HEADER, null);
cookie.setMaxAge(0);
cookie.setPath("/");
response.addHeader(JwtUtil.AUTHORIZATION_HEADER, null);
response.addCookie(cookie);

// refresh 토큰 삭제
log.info("refreshToken 삭제");
String accessToken = jwtUtil.getTokenFromCookieAndName(request, JwtUtil.AUTHORIZATION_HEADER);
if(StringUtils.hasText(accessToken)){
accessToken = jwtUtil.substringToken(accessToken);
String refreshToken = redisTool.getValues(accessToken);
if(refreshToken.equals("false")){
throw new CustomException(ErrorCode.INVALID_REFRESH_TOKEN);
if(!refreshToken.equals("false")){
redisTool.deleteValues(accessToken);

//access의 남은 유효시간만큼 redis에 블랙리스트로 저장
log.info("redis에 블랙리스트 저장");
Long remainedExpiration = jwtUtil.getUserInfoFromToken(accessToken).getExpiration().getTime();
Long now = new Date().getTime();
if(remainedExpiration > now){
long newExpiration = remainedExpiration - now;
redisTool.setValues(accessToken, "logout", Duration.ofMillis(newExpiration));
}
}
redisTool.deleteValues(accessToken);
}

//access의 남은 유효시간만큼 redis에 블랙리스트로 저장
Long remainedExpiration = jwtUtil.getUserInfoFromToken(accessToken).getExpiration().getTime();
Long now = new Date().getTime();
if(remainedExpiration > now){
long newExpiration = remainedExpiration - now;
redisTool.setValues(accessToken, "logout", Duration.ofMillis(newExpiration));
}

}
}
6 changes: 0 additions & 6 deletions src/main/java/com/nawabali/nawabali/security/Jwt/JwtUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,6 @@ public String substringToken(String token){
}
throw new NullPointerException("Not Found Token");
}
// public String substringToken(String token){
// if (StringUtils.hasText(token) && token.startsWith("Bearer ")) {
// return token.substring(7);
// }
// throw new IllegalArgumentException("Invalid or Missing Authorization Header");
// }


}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public class KakaoService {
private String clientId;

@Transactional
public ResponseEntity<UserDto.kakaoLoginResponseDto> kakaoLogin(String code , HttpServletResponse response) throws JsonProcessingException, IOException {
public void kakaoLogin(String code , HttpServletResponse response) throws JsonProcessingException, IOException {
// 1. "인가 코드"로 "액세스 토큰" 요청
String accessToken = getAccessToken(code, aws);

Expand All @@ -63,8 +63,6 @@ public ResponseEntity<UserDto.kakaoLoginResponseDto> kakaoLogin(String code , Ht

// 3. 로그인 JWT 토큰 발행 및 리프레시 토큰 저장
jwtTokenCreate(kakaoUser,response);
return ResponseEntity.ok(new UserDto.kakaoLoginResponseDto(kakaoUser.getId()));

}

// 토큰을 요청하고 카카오 서버에서 토큰을 발급 받음- post요청
Expand Down
21 changes: 10 additions & 11 deletions src/main/java/com/nawabali/nawabali/service/LikeService.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
public class LikeService {

private final LikeRepository likeRepository;
// private final LocalLikeRepository localLikeRepository;
private final UserRepository userRepository;
private final PostRepository postRepository;
private final NotificationService notificationService;
Expand Down Expand Up @@ -91,10 +90,10 @@ public LikeDto.responseDto toggleLocalLike(Long postId, String username) {
Post post = postRepository.findById(postId)
.orElseThrow(() -> new CustomException(ErrorCode.POST_NOT_FOUND));

// 해당 지역의 회원인지 확인
// if(!isMatchDistrict(user, post)){
// throw new CustomException(ErrorCode.MISMATCH_ADDRESS);
// }
// 해당 지역의 회원인지 확인
if(!isMatchDistrict(user, post)){
throw new CustomException(ErrorCode.MISMATCH_ADDRESS);
}

// 해당 게시물에 로컬좋아요를 눌렀는지 확인
Like findLocalLike = likeRepository.findByUserIdAndPostIdAndLikeCategoryEnum(user.getId(), postId, LikeCategoryEnum.LOCAL_LIKE);
Expand Down Expand Up @@ -136,11 +135,11 @@ public LikeDto.responseDto toggleLocalLike(Long postId, String username) {
}
}

// private boolean isMatchDistrict(User user, Post post){
// String userAddress = user.getAddress().getDistrict();
// String postAddress = post.getTitle();
//
// return userAddress.equals(postAddress);
// }
private boolean isMatchDistrict(User user, Post post){
String userAddress = user.getAddress().getDistrict();
String postAddress = post.getTown().getDistrict();

return userAddress.equals(postAddress);
}

}
Loading

0 comments on commit e3c24ab

Please sign in to comment.