Skip to content

Commit c5b429c

Browse files
authored
Merge pull request #120 from 2024-Java-Study/jihyun_feat/#118
[Feat] 쿠키 삭제
2 parents 5cf73c0 + 4df921d commit c5b429c

File tree

16 files changed

+71
-51
lines changed

16 files changed

+71
-51
lines changed

pro/src/main/java/com/example/pro/auth/config/SecurityConfig.java

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import lombok.RequiredArgsConstructor;
99
import org.springframework.context.annotation.Bean;
1010
import org.springframework.context.annotation.Configuration;
11+
import org.springframework.http.HttpMethod;
1112
import org.springframework.security.authentication.AuthenticationManager;
1213
import org.springframework.security.authentication.AuthenticationProvider;
1314
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
@@ -86,7 +87,7 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
8687
antMatcher("/api/test"),
8788
antMatcher("/members/signup"),
8889
antMatcher("/members/login"),
89-
antMatcher("/boards"),
90+
antMatcher(HttpMethod.GET, "/boards"),
9091
antMatcher("/health")
9192
).permitAll()
9293
.anyRequest().authenticated();
@@ -99,22 +100,6 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
99100
return http.build();
100101
}
101102

102-
103-
// @Bean
104-
// public CorsConfigurationSource corsConfigurationSource() {
105-
// CorsConfiguration configuration = new CorsConfiguration();
106-
//
107-
// configuration.addAllowedOriginPattern("*"); // addAllowedOrigin("*")은 allowCredentials(true)랑 같이 사용 불가능
108-
// configuration.addAllowedMethod("*");
109-
// configuration.addAllowedHeader("*");
110-
// configuration.setAllowCredentials(true);
111-
// configuration.setMaxAge(7200L);
112-
//
113-
// UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
114-
// source.registerCorsConfiguration("/**", configuration);
115-
//
116-
// return source;
117-
// }
118103
@Bean
119104
public CorsConfigurationSource corsConfigurationSource() {
120105
CorsConfiguration configuration = new CorsConfiguration();

pro/src/main/java/com/example/pro/auth/controller/MemberController.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,15 @@
1010
import com.example.pro.common.response.BasicResponse;
1111
import com.example.pro.common.response.ResponseUtil;
1212
import jakarta.servlet.http.HttpServletRequest;
13+
import jakarta.servlet.http.HttpServletResponse;
1314
import jakarta.validation.Valid;
1415
import lombok.RequiredArgsConstructor;
1516
import lombok.extern.slf4j.Slf4j;
1617
import org.springframework.web.bind.annotation.*;
1718

1819
import static com.example.pro.auth.domain.UserSession.SESSION_KEY;
1920

21+
2022
@RestController
2123
@RequestMapping("/members")
2224
@RequiredArgsConstructor
@@ -37,6 +39,13 @@ public BasicResponse<String> signIn(@Valid @RequestBody LoginRequest form) {
3739
return ResponseUtil.success("로그인 성공: " + username);
3840
}
3941

42+
@PostMapping("/logout")
43+
public BasicResponse<String> signOut(HttpServletRequest request, HttpServletResponse response) {
44+
authService.logout();
45+
CookieUtil.deleteCookie(request, response, SESSION_KEY);
46+
return ResponseUtil.success("로그아웃되었습니다.");
47+
}
48+
4049
@PutMapping("/profiles")
4150
public BasicResponse<String> updateProfile(@ModelAttribute ProfileUpdateRequest request) {
4251
Member member = authService.loadUser();
@@ -45,8 +54,9 @@ public BasicResponse<String> updateProfile(@ModelAttribute ProfileUpdateRequest
4554
}
4655

4756
@DeleteMapping
48-
public BasicResponse<String> quitMember() {
57+
public BasicResponse<String> quitMember(HttpServletRequest request, HttpServletResponse response) {
4958
authService.quit();
59+
CookieUtil.deleteCookie(request, response, SESSION_KEY);
5060
return ResponseUtil.success("탈퇴되었습니다.");
5161
}
5262

pro/src/main/java/com/example/pro/auth/domain/UserSession.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public class UserSession {
1919
private LocalDateTime lastAccessedAt;
2020
private LocalDateTime expiredAt;
2121
public static final String SESSION_KEY = "JSESSIONID";
22-
public static final int SESSION_EXPIRED_SECOND = 1800; // TODO: 테스트를 위해 1분으로 설정. 배포전 수정 필요.
22+
public static final int SESSION_EXPIRED_SECOND = 30 * 60; // 30분
2323

2424
public static UserSession create(String sessionId, String username, Clock clock) {
2525
return new UserSession(sessionId, username, clock);

pro/src/main/java/com/example/pro/auth/service/AuthService.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import org.springframework.transaction.annotation.Transactional;
2020

2121
import java.time.Clock;
22+
import java.util.Optional;
2223

2324
@Slf4j
2425
@Service
@@ -53,9 +54,17 @@ public String login(LoginRequest form) {
5354
return form.getUsername();
5455
}
5556

57+
@Transactional
58+
public void logout() {
59+
Member member = loadUser();
60+
Optional<UserSession> session = sessionRepository.findByUsername(member.getUsername());
61+
session.ifPresent(sessionRepository::delete);
62+
}
63+
5664
@Transactional
5765
public void quit() {
5866
Member member = loadUser();
67+
log.info("login user:{}", member.getUsername());
5968
memberService.markQuitInWriterInfo(member);
6069
UserSession session = sessionRepository.findByUsername(member.getUsername())
6170
.orElseThrow(() -> new AuthException(AuthErrorCode.UNAUTHORIZED_USER));

pro/src/main/java/com/example/pro/auth/service/MemberService.java

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,9 @@ public Member updateProfile(MultipartFile file, Member member) {
3838
}
3939

4040
public void markQuitInWriterInfo(Member member) {
41-
WriterInfo writer = new WriterInfo(member.getUsername(), member.getProfile(), false);
42-
43-
List<Board> boards = boardRepository.findAllByWriterInfo(writer);
44-
List<Comment> comments = commentRepository.findAllByWriter(writer);
45-
List<Reply> replies = replyRepository.findAllByWriter(writer);
41+
List<Board> boards = boardRepository.findAllByWriter(member.getUsername());
42+
List<Comment> comments = commentRepository.findAllByWriter(member.getUsername());
43+
List<Reply> replies = replyRepository.findAllByWriter(member.getUsername());
4644

4745
boards.forEach(Board::removeWriterInfo);
4846
comments.forEach(Comment::removeWriterInfo);

pro/src/main/java/com/example/pro/auth/utils/CookieUtil.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@
77

88
import java.util.Base64;
99

10+
import static com.example.pro.auth.domain.UserSession.SESSION_EXPIRED_SECOND;
11+
1012
public class CookieUtil {
13+
1114
public static String getCookieValue(HttpServletRequest request, String name) {
1215
Cookie[] cookies = request.getCookies();
1316

@@ -26,9 +29,8 @@ public static void addCookie(HttpServletResponse response, String name, String v
2629
cookie.setPath("/");
2730
cookie.setSecure(true);
2831
cookie.setHttpOnly(true);
29-
// cookie.setDomain("localhost");
3032
cookie.setAttribute("SameSite", "None");
31-
cookie.setMaxAge(300);
33+
cookie.setMaxAge(SESSION_EXPIRED_SECOND);
3234

3335
response.addCookie(cookie);
3436
}

pro/src/main/java/com/example/pro/board/controller/BoardController.java

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,12 @@
1818
public class BoardController {
1919

2020
private final BoardService boardService;
21-
private final BoardImageService boardImageService;
2221
private final AuthService authService;
2322

2423
@PostMapping
2524
public BasicResponse<String> create(@ModelAttribute @Valid BoardSaveDto boardDto) {
2625
Member member = authService.loadUser();
2726
Board board = boardService.createBoard(boardDto, member.getUsername(), member.getProfile());
28-
boardImageService.uploadBoardImage(boardDto.getImages(), board);
2927
return ResponseUtil.success("게시물 생성에 성공하였습니다. 게시물id: " + board.getId());
3028
}
3129

@@ -55,9 +53,7 @@ public BasicResponse<String> delete(@PathVariable Long id) {
5553

5654
@PutMapping("/{id}/upload")
5755
public BasicResponse<String> uploadImage(@ModelAttribute BoardImageUploadDto request, @PathVariable Long id) {
58-
Board board = boardService.findBoard(id);
59-
boardImageService.deleteBoardImage(board);
60-
boardImageService.uploadBoardImage(request.getImages(), board);
61-
return ResponseUtil.success("게시물 id: " + id + "번 사진 추가에 성공하였습니다.");
56+
boardService.updateBoardImages(id, request);
57+
return ResponseUtil.success("사진 수정에 성공하였습니다. 게시물 id: " + id);
6258
}
6359
}

pro/src/main/java/com/example/pro/board/dto/BoardSaveDto.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package com.example.pro.board.dto;
22

3-
import com.example.pro.board.domain.Board;
43
import jakarta.validation.constraints.NotBlank;
54
import lombok.*;
65
import org.springframework.web.multipart.MultipartFile;

pro/src/main/java/com/example/pro/board/repository/BoardRepository.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,15 @@
33
import com.example.pro.board.domain.Board;
44
import com.example.pro.comment.domain.WriterInfo;
55
import org.springframework.data.jpa.repository.JpaRepository;
6+
import org.springframework.data.jpa.repository.Query;
7+
import org.springframework.data.repository.query.Param;
68

79
import java.util.List;
810

911
public interface BoardRepository extends JpaRepository<Board, Long> {
1012

1113
List<Board> findByTitle(String title);
12-
List<Board> findAllByWriterInfo(WriterInfo writer);
14+
15+
@Query("select board from Board board where board.writerInfo.username = :writerName")
16+
List<Board> findAllByWriter(@Param("writerName") String writerName);
1317
}

pro/src/main/java/com/example/pro/board/service/BoardService.java

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import lombok.RequiredArgsConstructor;
1111
import org.springframework.stereotype.Service;
1212
import org.springframework.transaction.annotation.Transactional;
13+
import org.springframework.web.bind.annotation.PathVariable;
1314

1415
import java.util.List;
1516
import java.util.stream.Collectors;
@@ -24,13 +25,16 @@ public class BoardService {
2425

2526
@Transactional
2627
public Board createBoard(BoardSaveDto boardDto, String username, String profile) {
27-
Board board = Board.builder()
28-
.username(username)
29-
.profile(profile)
30-
.title(boardDto.getTitle())
31-
.content(boardDto.getContent())
32-
.build();
33-
return boardRepository.save(board);
28+
Board board = boardRepository.save(
29+
Board.builder()
30+
.username(username)
31+
.profile(profile)
32+
.title(boardDto.getTitle())
33+
.content(boardDto.getContent())
34+
.build()
35+
);
36+
boardImageService.uploadBoardImage(boardDto.getImages(), board);
37+
return board;
3438
}
3539

3640
public BoardResponseDto makeBoardResponse(Long boardId) {
@@ -46,19 +50,18 @@ public Board findBoard(Long boardId) {
4650
}
4751

4852
public BoardCountResponseDto findAllBoards() {
53+
long totalCount = boardRepository.count();
4954
List<Board> boards = boardRepository.findAll();
5055

5156
// 엔티티를 Dto로 변환하는 로직
5257
List<BoardListResponseDto> responses = boards.stream()
5358
.map(BoardListResponseDto::toBoardListDto)
5459
.collect(Collectors.toList());
55-
long count = boardRepository.count();
56-
return new BoardCountResponseDto(responses, count);
60+
return new BoardCountResponseDto(responses, totalCount);
5761
}
5862

5963
public List<Board> searchTitle(String title) {
6064
return boardRepository.findByTitle(title);
61-
6265
}
6366

6467
@Transactional
@@ -76,6 +79,13 @@ public BoardUpdateDto updateBoard(Long boardId, BoardUpdateDto boardUpdateDto, M
7679
return BoardUpdateDto.toBoardUpdateDto(board);
7780
}
7881

82+
@Transactional
83+
public void updateBoardImages(Long boardId, BoardImageUploadDto dto) {
84+
Board board = findBoard(boardId);
85+
boardImageService.deleteBoardImage(board);
86+
boardImageService.uploadBoardImage(dto.getImages(), board);
87+
}
88+
7989
@Transactional
8090
public void deleteBoard(Long boardId, Member member) {
8191
Board board = boardRepository.findById(boardId)

pro/src/main/java/com/example/pro/comment/repository/CommentRepository.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22

33
import com.example.pro.board.domain.Board;
44
import com.example.pro.comment.domain.Comment;
5-
import com.example.pro.comment.domain.WriterInfo;
65
import org.springframework.data.jpa.repository.JpaRepository;
6+
import org.springframework.data.jpa.repository.Query;
7+
import org.springframework.data.repository.query.Param;
78

89
import java.util.List;
910

1011
public interface CommentRepository extends JpaRepository<Comment, Long> {
1112

1213
List<Comment> findAllByBoard(Board board);
13-
List<Comment> findAllByWriter(WriterInfo writer);
14+
@Query("select comment from Comment comment where comment.writer.username = :writerName")
15+
List<Comment> findAllByWriter(@Param("writerName") String writerName);
1416
}

pro/src/main/java/com/example/pro/comment/repository/ReplyRepository.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,14 @@
44
import com.example.pro.comment.domain.Reply;
55
import com.example.pro.comment.domain.WriterInfo;
66
import org.springframework.data.jpa.repository.JpaRepository;
7+
import org.springframework.data.jpa.repository.Query;
8+
import org.springframework.data.repository.query.Param;
79

810
import java.util.List;
911

1012
public interface ReplyRepository extends JpaRepository<Reply, Long> {
1113

1214
List<Reply> findAllByComment(Comment comment);
13-
List<Reply> findAllByWriter(WriterInfo writer);
15+
@Query("select reply from Reply reply where reply.writer.username = :writerName")
16+
List<Reply> findAllByWriter(@Param("writerName") String writerName);
1417
}

pro/src/test/java/com/example/pro/auth/service/MemberServiceTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ void markQuitWriterInfo() {
100100
List<Board> boards = List.of(board);
101101
List<Comment> comments = List.of(comment);
102102
List<Reply> replies = List.of(reply);
103-
when(boardRepository.findAllByWriterInfo(any())).thenReturn(boards);
103+
when(boardRepository.findAllByWriter(any())).thenReturn(boards);
104104
when(commentRepository.findAllByWriter(any())).thenReturn(comments);
105105
when(replyRepository.findAllByWriter(any())).thenReturn(replies);
106106

pro/src/test/java/com/example/pro/board/controller/BoardControllerTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,6 @@ void deleteBoardNotValidation() throws Exception {
616616

617617
@Override
618618
protected Object injectController() {
619-
return new BoardController(boardService, boardImageService, authService);
619+
return new BoardController(boardService, authService);
620620
}
621621
}

pro/src/test/java/com/example/pro/board/controller/BoardUploadControllerTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,6 @@ void init() {
100100

101101
@Override
102102
protected Object injectController() {
103-
return new BoardController(boardService, boardImageService, authService);
103+
return new BoardController(boardService, authService);
104104
}
105105
}

pro/src/test/java/com/example/pro/board/service/BoardServiceSearchTest.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,14 @@
2323
import static org.assertj.core.api.Assertions.assertThat;
2424
import static org.junit.jupiter.api.Assertions.assertThrows;
2525
import static org.mockito.ArgumentMatchers.any;
26+
import static org.mockito.Mockito.doNothing;
2627
import static org.mockito.Mockito.when;
2728

2829
@ExtendWith(MockitoExtension.class) // Junit5 & Mockito 연동
2930
public class BoardServiceSearchTest {
3031

3132
@Mock BoardRepository boardRepository; // 의존성 주입
33+
@Mock BoardImageService boardImageService;
3234
@Mock FileUploader fileUploader;
3335
@InjectMocks BoardService boardService;
3436

@@ -76,7 +78,7 @@ public void createBoard() throws Exception {
7678

7779
// when
7880
when(boardRepository.save(any())).thenReturn(board);
79-
81+
doNothing().when(boardImageService).uploadBoardImage(any(), any());
8082

8183
// then
8284
assertThat(boardService.createBoard(boardSaveDto, member.getUsername(), any()).getTitle()).isEqualTo("제목");

0 commit comments

Comments
 (0)