From d31c0786ad8b6dc34309077abca8759f10e5685f Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 09:47:12 +0900 Subject: [PATCH 01/39] =?UTF-8?q?#34=20-=20Test:=20=ED=9A=8C=EC=9B=90=20?= =?UTF-8?q?=EB=A1=9C=EA=B7=B8=EC=9D=B8=20POST=20=EC=9A=94=EC=B2=AD(JSON=20?= =?UTF-8?q?=EB=B0=A9=EC=8B=9D)=20=EC=BB=A8=ED=8A=B8=EB=A1=A4=EB=9F=AC=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/MemberApiControllerTest.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java diff --git a/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java b/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java new file mode 100644 index 0000000..9bc8bdc --- /dev/null +++ b/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java @@ -0,0 +1,50 @@ +package com.example.mutbooks.app.api.controller; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.transaction.annotation.Transactional; + +import java.nio.charset.StandardCharsets; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +@Transactional +@ActiveProfiles("test") +class MemberApiControllerTest { + + @Autowired + private MockMvc mvc; + + @Test + @DisplayName("POST /api/v1/member/login 은 로그인 처리 URL 이다.") + void t1() throws Exception { + // When + ResultActions resultActions = mvc + .perform( + post("/api/v1/member/login") + .content(""" + { + "username": "user1", + "password": "1234" + } + """.stripIndent()) + .contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8)) + ) + .andDo(print()); + + // Then + resultActions + .andExpect(status().is2xxSuccessful()); + } +} \ No newline at end of file From 295851c7ecccbd81d4e78f14983f797d402684e9 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 09:51:13 +0900 Subject: [PATCH 02/39] =?UTF-8?q?#33=20-=20Feat:=20LoginDto=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80,=20=EB=A1=9C=EA=B7=B8=EC=9D=B8=20POST=20=EC=9A=94?= =?UTF-8?q?=EC=B2=AD(JSON)=20=EA=B5=AC=ED=98=84(=EC=9E=84=EC=8B=9C)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/api/controller/MemberApiController.java | 17 +++++++++++++++++ .../app/base/initData/TestInitData.java | 10 ++++++++++ .../mutbooks/app/member/dto/LoginDto.java | 13 +++++++++++++ 3 files changed, 40 insertions(+) create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/dto/LoginDto.java diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java new file mode 100644 index 0000000..3222b98 --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java @@ -0,0 +1,17 @@ +package com.example.mutbooks.app.api.controller; + +import com.example.mutbooks.app.member.dto.LoginDto; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/v1/member") +public class MemberApiController { + + @PostMapping("/login") + public String login(@RequestBody LoginDto loginDto) { + return "username : %s, password : %s".formatted(loginDto.getUsername(), loginDto.getPassword()); + } +} diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/initData/TestInitData.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/initData/TestInitData.java index 0542090..ff66b7c 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/initData/TestInitData.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/initData/TestInitData.java @@ -5,6 +5,7 @@ import com.example.mutbooks.app.order.service.OrderService; import com.example.mutbooks.app.post.service.PostService; import com.example.mutbooks.app.product.service.ProductService; +import lombok.extern.slf4j.Slf4j; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -12,7 +13,11 @@ @Configuration @Profile("test") +@Slf4j public class TestInitData implements InitDataBefore { + // initData 실행 여부(2번 생성되는 것을 막기 위함) + private boolean initDataDone = false; + @Bean CommandLineRunner initData( MemberService memberService, @@ -22,6 +27,11 @@ CommandLineRunner initData( OrderService orderService ) { return args -> { + if(initDataDone) return; + initDataDone = true; + + log.info("TestInitData 실행"); + before(memberService, postService, productService, cartService, orderService); }; } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/dto/LoginDto.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/dto/LoginDto.java new file mode 100644 index 0000000..b0fec25 --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/dto/LoginDto.java @@ -0,0 +1,13 @@ +package com.example.mutbooks.app.member.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +@Data +public class LoginDto { + @NotBlank(message = "username 을(를) 입력해주세요.") + private String username; + @NotBlank(message = "password 을(를) 입력해주세요.") + private String password; +} From 60aa1cef9f150fed1e972cf6449e0346f1f129a5 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 10:00:04 +0900 Subject: [PATCH 03/39] =?UTF-8?q?#34=20-=20Test:=20=EC=98=AC=EB=B0=94?= =?UTF-8?q?=EB=A5=B8=20POST=20/api/v1/member/login=20=EC=9A=94=EC=B2=AD?= =?UTF-8?q?=EC=9D=98=20=EC=9D=91=EB=8B=B5=20=ED=97=A4=EB=8D=94=EC=97=90=20?= =?UTF-8?q?Authentication=20=EA=B0=92(JWT=20=ED=86=A0=ED=81=B0)=EC=9D=B4?= =?UTF-8?q?=20=EC=9E=88=EB=8A=94=EC=A7=80=20=ED=85=8C=EC=8A=A4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/MemberApiControllerTest.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java b/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java index 9bc8bdc..be26429 100644 --- a/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java +++ b/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java @@ -6,13 +6,16 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultActions; import org.springframework.transaction.annotation.Transactional; import java.nio.charset.StandardCharsets; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -47,4 +50,35 @@ void t1() throws Exception { resultActions .andExpect(status().is2xxSuccessful()); } + + @Test + @DisplayName("POST /api/v1/member/login 으로 올바른 username과 password 데이터를 넘기면 JWT키를 발급해 응답 헤더에 담아준다.") + void t2() throws Exception { + // When + ResultActions resultActions = mvc + .perform( + post("/api/v1/member/login") + .content(""" + { + "username": "user1", + "password": "1234" + } + """.stripIndent()) + .contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8)) + ) + .andDo(print()); + + // Then + resultActions + .andExpect(status().is2xxSuccessful()); + + // 응답 결과 + MvcResult mvcResult = resultActions.andReturn(); + + MockHttpServletResponse response = mvcResult.getResponse(); + // 응답 헤더 Authentication(key) : JWT 키(value) + String authentication = response.getHeader("Authentication"); + + assertThat(authentication).isNotEmpty(); + } } \ No newline at end of file From 96bf825b4b808a07b45d014bb3e152f2612667dd Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 10:03:51 +0900 Subject: [PATCH 04/39] =?UTF-8?q?#33=20-=20Feat:=20HttpServletResponse=20?= =?UTF-8?q?=ED=97=A4=EB=8D=94=EC=97=90=20=EC=9E=84=EC=8B=9C=20Authenticati?= =?UTF-8?q?on=20=EA=B0=92=EC=9D=84=20=EB=8B=B4=EC=95=84=20=EC=9D=91?= =?UTF-8?q?=EB=8B=B5=20=EB=B3=B4=EB=82=B4=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mutbooks/app/api/controller/MemberApiController.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java index 3222b98..25d475c 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java @@ -6,12 +6,16 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import javax.servlet.http.HttpServletResponse; + @RestController @RequestMapping("/api/v1/member") public class MemberApiController { @PostMapping("/login") - public String login(@RequestBody LoginDto loginDto) { + public String login(@RequestBody LoginDto loginDto, HttpServletResponse response) { + response.addHeader("Authentication", "JWT Token"); + return "username : %s, password : %s".formatted(loginDto.getUsername(), loginDto.getPassword()); } } From 058a9354da5928ec7d41aee88f9d161c1d9ab610 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 10:08:11 +0900 Subject: [PATCH 05/39] =?UTF-8?q?#33=20-=20Feat:=20ResponseEntity=20?= =?UTF-8?q?=EB=A1=9C=20=EC=9D=91=EB=8B=B5=20=ED=97=A4=EB=8D=94,=20?= =?UTF-8?q?=EB=B0=94=EB=94=94,=20=EC=83=81=ED=83=9C=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=84=A4=EC=A0=95=ED=95=98=EC=97=AC=20=EC=9D=91=EB=8B=B5=20?= =?UTF-8?q?=EB=B3=B4=EB=82=B4=EB=8A=94=20=EA=B2=83=EC=9C=BC=EB=A1=9C=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/api/controller/MemberApiController.java | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java index 25d475c..cf5ee42 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java @@ -1,21 +1,26 @@ package com.example.mutbooks.app.api.controller; import com.example.mutbooks.app.member.dto.LoginDto; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import javax.servlet.http.HttpServletResponse; - @RestController @RequestMapping("/api/v1/member") public class MemberApiController { @PostMapping("/login") - public String login(@RequestBody LoginDto loginDto, HttpServletResponse response) { - response.addHeader("Authentication", "JWT Token"); + public ResponseEntity login(@RequestBody LoginDto loginDto) { + // 헤더(Authentication) 에 JWT 토큰 & 바디에 username, password + HttpHeaders headers = new HttpHeaders(); + headers.set("Authentication", "JWT Token"); + + String body = "username : %s, password : %s".formatted(loginDto.getUsername(), loginDto.getPassword()); - return "username : %s, password : %s".formatted(loginDto.getUsername(), loginDto.getPassword()); + return new ResponseEntity<>(body, headers, HttpStatus.OK); } } From a06a89d85fb70d4a5e4a8255aa18fdda5dd08ecb Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 10:15:26 +0900 Subject: [PATCH 06/39] =?UTF-8?q?#33=20-=20Feat:=20=EB=A1=9C=EA=B7=B8?= =?UTF-8?q?=EC=9D=B8=20=EC=9A=94=EC=B2=AD=EC=8B=9C,=20=EC=9E=85=EB=A0=A5?= =?UTF-8?q?=20=EB=8D=B0=EC=9D=B4=ED=84=B0(username,=20password)=20?= =?UTF-8?q?=EC=9C=A0=ED=9A=A8=EC=84=B1=20=EA=B2=80=EC=A6=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mutbooks/app/api/controller/MemberApiController.java | 5 +++++ .../java/com/example/mutbooks/app/member/dto/LoginDto.java | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java index cf5ee42..77c3e2f 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java @@ -15,6 +15,11 @@ public class MemberApiController { @PostMapping("/login") public ResponseEntity login(@RequestBody LoginDto loginDto) { + // 입력 데이터 유효성 검증 + if(loginDto.isNotValid()) { + return new ResponseEntity<>(null, null, HttpStatus.BAD_REQUEST); + } + // 헤더(Authentication) 에 JWT 토큰 & 바디에 username, password HttpHeaders headers = new HttpHeaders(); headers.set("Authentication", "JWT Token"); diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/dto/LoginDto.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/dto/LoginDto.java index b0fec25..8983ff2 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/dto/LoginDto.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/dto/LoginDto.java @@ -10,4 +10,8 @@ public class LoginDto { private String username; @NotBlank(message = "password 을(를) 입력해주세요.") private String password; + + public boolean isNotValid() { + return username == null || password == null || username.trim().length() == 0 || password.trim().length() == 0; + } } From fc972c358eb68855aebc12ad0e2fa53b3e0b8fc9 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 10:20:48 +0900 Subject: [PATCH 07/39] =?UTF-8?q?#34=20-=20Test:=20=EB=A1=9C=EA=B7=B8?= =?UTF-8?q?=EC=9D=B8=20=EC=9A=94=EC=B2=AD=EC=8B=9C=20username/password=20?= =?UTF-8?q?=EC=9E=85=EB=A0=A5=EB=8D=B0=EC=9D=B4=ED=84=B0=20=EC=9C=A0?= =?UTF-8?q?=ED=9A=A8=EC=84=B1=20=EA=B2=80=EC=A6=9D=20=EC=8B=A4=ED=8C=A8?= =?UTF-8?q?=ED=95=98=EB=A9=B4=20400(BadRequest)=20=EC=9D=91=EB=8B=B5=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/MemberApiControllerTest.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java b/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java index be26429..65011ad 100644 --- a/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java +++ b/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java @@ -81,4 +81,43 @@ void t2() throws Exception { assertThat(authentication).isNotEmpty(); } + + @Test + @DisplayName("POST /api/v1/member/login 호출할 때 username 이나 password 를 누락하면 400") + void t3() throws Exception { + // When + ResultActions resultActions = mvc + .perform( + post("/api/v1/member/login") + .content(""" + { + "username": "", + "password": "1234" + } + """.stripIndent()) + .contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8)) + ) + .andDo(print()); + + // Then + resultActions + .andExpect(status().is4xxClientError()); + + resultActions = mvc + .perform( + post("/api/v1/member/login") + .content(""" + { + "username": "user1", + "password": " " + } + """.stripIndent()) + .contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8)) + ) + .andDo(print()); + + // Then + resultActions + .andExpect(status().is4xxClientError()); + } } \ No newline at end of file From 330e0f361a16718a36af512f3b0e99984585efe1 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 10:25:24 +0900 Subject: [PATCH 08/39] =?UTF-8?q?#34=20-=20Test:=20=EC=A1=B4=EC=9E=AC?= =?UTF-8?q?=ED=95=98=EC=A7=80=20=EC=95=8A=EB=8A=94=20=ED=9A=8C=EC=9B=90(us?= =?UTF-8?q?ername,=20password)=EC=97=90=20=EB=8C=80=ED=95=9C=20=EB=A1=9C?= =?UTF-8?q?=EA=B7=B8=EC=9D=B8=20=EC=9A=94=EC=B2=AD=EC=8B=9C=20400(BadReque?= =?UTF-8?q?st)=20=EC=9D=91=EB=8B=B5=20=ED=85=8C=EC=8A=A4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/MemberApiControllerTest.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java b/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java index 65011ad..95fde17 100644 --- a/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java +++ b/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java @@ -120,4 +120,44 @@ void t3() throws Exception { resultActions .andExpect(status().is4xxClientError()); } + + @Test + @DisplayName("POST /api/v1/member/login 호출할 때 올바르지 않는 username 이나 password 를 입력하면 400") + void t4() throws Exception { + // When(존재하지 않는 아이디) + ResultActions resultActions = mvc + .perform( + post("/api/v1/member/login") + .content(""" + { + "username": "user3", + "password": "1234" + } + """.stripIndent()) + .contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8)) + ) + .andDo(print()); + + // Then + resultActions + .andExpect(status().is4xxClientError()); + + // when(비밀번호 틀림) + resultActions = mvc + .perform( + post("/api/v1/member/login") + .content(""" + { + "username": "user1", + "password": "12345" + } + """.stripIndent()) + .contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8)) + ) + .andDo(print()); + + // Then + resultActions + .andExpect(status().is4xxClientError()); + } } \ No newline at end of file From 53ea4b81ff6274d43e94231df6e56d4d3293b5d1 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 10:33:42 +0900 Subject: [PATCH 09/39] =?UTF-8?q?#33=20-=20Feat:=20=EC=A1=B4=EC=9E=AC?= =?UTF-8?q?=ED=95=98=EC=A7=80=20=EC=95=8A=EB=8A=94=20=ED=9A=8C=EC=9B=90,?= =?UTF-8?q?=20=EC=98=AC=EB=B0=94=EB=A5=B4=EC=A7=80=20=EC=95=8A=EC=9D=80=20?= =?UTF-8?q?=EB=B9=84=EB=B0=80=EB=B2=88=ED=98=B8=EB=A1=9C=20=EB=A1=9C?= =?UTF-8?q?=EA=B7=B8=EC=9D=B8=20=EC=9A=94=EC=B2=AD=EC=8B=9C=20400(BadReque?= =?UTF-8?q?st)=20=EC=9D=91=EB=8B=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../api/controller/MemberApiController.java | 18 ++++++++++++++++++ .../controller/MemberApiControllerTest.java | 2 +- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java index 77c3e2f..47a9a08 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java @@ -1,9 +1,13 @@ package com.example.mutbooks.app.api.controller; import com.example.mutbooks.app.member.dto.LoginDto; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.member.service.MemberService; +import lombok.RequiredArgsConstructor; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -11,7 +15,10 @@ @RestController @RequestMapping("/api/v1/member") +@RequiredArgsConstructor public class MemberApiController { + private final MemberService memberService; + private final PasswordEncoder passwordEncoder; @PostMapping("/login") public ResponseEntity login(@RequestBody LoginDto loginDto) { @@ -20,6 +27,17 @@ public ResponseEntity login(@RequestBody LoginDto loginDto) { return new ResponseEntity<>(null, null, HttpStatus.BAD_REQUEST); } + Member member = memberService.findByUsername(loginDto.getUsername()); + // 1. 존재하지 않는 회원 + if(member == null) { + return new ResponseEntity<>(null, null, HttpStatus.BAD_REQUEST); + } + // 2. 올바르지 않은 비밀번호 + // matches(비밀번호 원문, 암호화된 비밀번호) + if(!passwordEncoder.matches(loginDto.getPassword(), member.getPassword())) { + return new ResponseEntity<>(null, null, HttpStatus.BAD_REQUEST); + } + // 헤더(Authentication) 에 JWT 토큰 & 바디에 username, password HttpHeaders headers = new HttpHeaders(); headers.set("Authentication", "JWT Token"); diff --git a/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java b/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java index 95fde17..a22ee8d 100644 --- a/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java +++ b/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java @@ -130,7 +130,7 @@ void t4() throws Exception { post("/api/v1/member/login") .content(""" { - "username": "user3", + "username": "user4", "password": "1234" } """.stripIndent()) From 7e4ffe9832ad49cb6c5ae8c776fbe1004e2143bd Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 10:52:31 +0900 Subject: [PATCH 10/39] =?UTF-8?q?#2=20-=20Feat:=20Util.spring.responseEnti?= =?UTF-8?q?tyOf()=20=EB=8F=84=EC=9E=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/com/example/mutbooks/util/Ut.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java index 8275e0d..88f68d2 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java @@ -1,5 +1,9 @@ package com.example.mutbooks.util; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; @@ -7,6 +11,12 @@ import java.util.Calendar; public class Ut { + public static class spring { + public static ResponseEntity responseEntityOf(HttpHeaders headers) { + return new ResponseEntity<>(null, headers, HttpStatus.OK); + } + } + public static class date { // 해당 년, 월의 마지막 일자 구하기 From 0dd7bab4874b527275d23684dd1f8b738cfd5575 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 10:56:55 +0900 Subject: [PATCH 11/39] =?UTF-8?q?#2=20-=20Feat:=20RsData(REST=20API=20?= =?UTF-8?q?=EC=9A=A9=20ResponseEntity=20Body=20DTO)=20=EB=8F=84=EC=9E=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../example/mutbooks/app/base/dto/RsData.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java new file mode 100644 index 0000000..bd8b69f --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java @@ -0,0 +1,26 @@ +package com.example.mutbooks.app.base.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor +public class RsData { + private String resultCode; + private String msg; + private T data; + + public static RsData of(String resultCode, String msg) { + return new RsData<>(resultCode, msg, null); + } + + public boolean isSuccess() { + return resultCode.startsWith("S-1"); + } + + public boolean isFail() { + return isSuccess() == false; + } +} From 4c258b7c7ed55d94853986d01c87e99b2c2b446d Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 11:07:54 +0900 Subject: [PATCH 12/39] =?UTF-8?q?#33=20-=20Feat:=20=EB=A1=9C=EA=B7=B8?= =?UTF-8?q?=EC=9D=B8=20=EC=9A=94=EC=B2=AD=20=EC=9D=91=EB=8B=B5=20body?= =?UTF-8?q?=EC=97=90=20resultCode,=20msg,=20data=EA=B0=80=20=ED=8F=AC?= =?UTF-8?q?=ED=95=A8=EB=90=98=EB=8F=84=EB=A1=9D=20RsData=20=EC=A0=81?= =?UTF-8?q?=EC=9A=A9(ResponseEntity)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/api/controller/MemberApiController.java | 13 +++++++------ .../src/main/java/com/example/mutbooks/util/Ut.java | 11 +++++++++-- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java index 47a9a08..75c29bd 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java @@ -1,11 +1,12 @@ package com.example.mutbooks.app.api.controller; +import com.example.mutbooks.app.base.dto.RsData; import com.example.mutbooks.app.member.dto.LoginDto; import com.example.mutbooks.app.member.entity.Member; import com.example.mutbooks.app.member.service.MemberService; +import com.example.mutbooks.util.Ut; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.PostMapping; @@ -21,21 +22,21 @@ public class MemberApiController { private final PasswordEncoder passwordEncoder; @PostMapping("/login") - public ResponseEntity login(@RequestBody LoginDto loginDto) { + public ResponseEntity login(@RequestBody LoginDto loginDto) { // 입력 데이터 유효성 검증 if(loginDto.isNotValid()) { - return new ResponseEntity<>(null, null, HttpStatus.BAD_REQUEST); + return Ut.spring.responseEntityOf(RsData.of("F-1", "로그인 정보가 올바르지 않습니다..")); } Member member = memberService.findByUsername(loginDto.getUsername()); // 1. 존재하지 않는 회원 if(member == null) { - return new ResponseEntity<>(null, null, HttpStatus.BAD_REQUEST); + return Ut.spring.responseEntityOf(RsData.of("F-2", "일치하는 회원이 존재하지 않습니다.")); } // 2. 올바르지 않은 비밀번호 // matches(비밀번호 원문, 암호화된 비밀번호) if(!passwordEncoder.matches(loginDto.getPassword(), member.getPassword())) { - return new ResponseEntity<>(null, null, HttpStatus.BAD_REQUEST); + return Ut.spring.responseEntityOf(RsData.of("F-3", "비밀번호가 일치하지 않습니다.")); } // 헤더(Authentication) 에 JWT 토큰 & 바디에 username, password @@ -44,6 +45,6 @@ public ResponseEntity login(@RequestBody LoginDto loginDto) { String body = "username : %s, password : %s".formatted(loginDto.getUsername(), loginDto.getPassword()); - return new ResponseEntity<>(body, headers, HttpStatus.OK); + return Ut.spring.responseEntityOf(RsData.of("S-1", "로그인 성공, JWT AccessToken 을 발급합니다."), headers); } } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java index 88f68d2..ee5a38c 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java @@ -1,5 +1,6 @@ package com.example.mutbooks.util; +import com.example.mutbooks.app.base.dto.RsData; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -12,8 +13,14 @@ public class Ut { public static class spring { - public static ResponseEntity responseEntityOf(HttpHeaders headers) { - return new ResponseEntity<>(null, headers, HttpStatus.OK); + public static ResponseEntity responseEntityOf(RsData rsData) { + return responseEntityOf(rsData, null); + } + + public static ResponseEntity responseEntityOf(RsData rsData, HttpHeaders headers) { + HttpStatus httpStatus = rsData.isSuccess() ? HttpStatus.OK : HttpStatus.BAD_REQUEST; + // body, header, httpStatus + return new ResponseEntity<>(rsData, headers, httpStatus); } } From 886bdf280f09f2edd83461c9d9138ff366530792 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 11:11:25 +0900 Subject: [PATCH 13/39] =?UTF-8?q?#2=20-=20Feat:=20Ut.mapOf()=20=EB=8F=84?= =?UTF-8?q?=EC=9E=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/example/mutbooks/util/Ut.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java index ee5a38c..ba06e66 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java @@ -10,8 +10,28 @@ import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; +import java.util.LinkedHashMap; +import java.util.Map; public class Ut { + // 인자 값들을 map 형태로 반환 + public static Map mapOf(Object... args) { + Map map = new LinkedHashMap<>(); + + int size = args.length / 2; + + for (int i = 0; i < size; i++) { + int keyIndex = i * 2; + int valueIndex = keyIndex + 1; + + K key = (K) args[keyIndex]; + V value = (V) args[valueIndex]; + + map.put(key, value); + } + return map; + } + public static class spring { public static ResponseEntity responseEntityOf(RsData rsData) { return responseEntityOf(rsData, null); From 8523f92e4cec5f4145798280e5f98b39e546cea7 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 11:15:40 +0900 Subject: [PATCH 14/39] =?UTF-8?q?#35=20-=20Test:=20Ut.mapOf()=20=ED=85=8C?= =?UTF-8?q?=EC=8A=A4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/example/mutbooks/util/UtTest.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/util/UtTest.java diff --git a/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/util/UtTest.java b/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/util/UtTest.java new file mode 100644 index 0000000..f35223f --- /dev/null +++ b/4Week_Mission/mutbooks/src/test/java/com/example/mutbooks/util/UtTest.java @@ -0,0 +1,21 @@ +package com.example.mutbooks.util; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +class UtTest { + @Test + @DisplayName("Ut.mapOf() 인자값을 map 으로 변환") + void t1() { + Map ages = Ut.mapOf("영수", 22, "철수", 33, "영희", 44, "민수", 55); + + assertThat(ages.get("영수")).isEqualTo(22); + assertThat(ages.get("철수")).isEqualTo(33); + assertThat(ages.get("영희")).isEqualTo(44); + assertThat(ages.get("민수")).isEqualTo(55); + } +} \ No newline at end of file From c26d3571a9364d04ed2c731a2c1c95e3f8f2adac Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 11:22:39 +0900 Subject: [PATCH 15/39] =?UTF-8?q?#2=20-=20Feat:=20=EB=93=A4=EC=96=B4?= =?UTF-8?q?=EC=98=A8=20=EC=9D=B8=EC=9E=90=EB=93=A4=EC=9D=84=20(key,=20valu?= =?UTF-8?q?e)=20=EC=8C=8D=EC=9C=BC=EB=A1=9C=20HttpHeaders=20=EC=97=90=20?= =?UTF-8?q?=EB=8B=B4=EC=95=84=20=EB=B0=98=ED=99=98=ED=95=98=EB=8A=94=20Ut.?= =?UTF-8?q?spring.httpHeadersOf()=20=EB=8F=84=EC=9E=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/com/example/mutbooks/util/Ut.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java index ba06e66..ac3463f 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java @@ -42,6 +42,21 @@ public static ResponseEntity responseEntityOf(RsData rsData, Http // body, header, httpStatus return new ResponseEntity<>(rsData, headers, httpStatus); } + + // 들어온 인자를 (key, value) 형태의 HttpHeaders 로 반환 + public static HttpHeaders httpHeadersOf(String... args) { + HttpHeaders headers = new HttpHeaders(); + + // (key, value) + Map map = Ut.mapOf(args); + + for(String key : map.keySet()) { + String value = map.get(key); + headers.set(key, value); + } + + return headers; + } } public static class date { From 1e1c454086db4d18149bc0545ca69342747e1f8e Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 11:32:26 +0900 Subject: [PATCH 16/39] =?UTF-8?q?#33=20-=20Feat:=20=EB=A1=9C=EA=B7=B8?= =?UTF-8?q?=EC=9D=B8=20=EC=84=B1=EA=B3=B5=EC=8B=9C=20=EC=9D=91=EB=8B=B5=20?= =?UTF-8?q?=ED=97=A4=EB=8D=94,=20=EB=B0=94=EB=94=94=EC=97=90=20=EB=AA=A8?= =?UTF-8?q?=EB=91=90=20accessToken=20=EB=8B=B4=EC=95=84=20=EC=9D=91?= =?UTF-8?q?=EB=8B=B5=EB=B3=B4=EB=82=B4=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../api/controller/MemberApiController.java | 18 ++++++++++-------- .../example/mutbooks/app/base/dto/RsData.java | 6 +++++- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java index 75c29bd..424e0af 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java @@ -6,7 +6,6 @@ import com.example.mutbooks.app.member.service.MemberService; import com.example.mutbooks.util.Ut; import lombok.RequiredArgsConstructor; -import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.PostMapping; @@ -39,12 +38,15 @@ public ResponseEntity login(@RequestBody LoginDto loginDto) { return Ut.spring.responseEntityOf(RsData.of("F-3", "비밀번호가 일치하지 않습니다.")); } - // 헤더(Authentication) 에 JWT 토큰 & 바디에 username, password - HttpHeaders headers = new HttpHeaders(); - headers.set("Authentication", "JWT Token"); - - String body = "username : %s, password : %s".formatted(loginDto.getUsername(), loginDto.getPassword()); - - return Ut.spring.responseEntityOf(RsData.of("S-1", "로그인 성공, JWT AccessToken 을 발급합니다."), headers); + String accessToken = "JWT Access Token"; + // 응답 헤더, 바디에 accessToken 담기 + return Ut.spring.responseEntityOf( + RsData.of( + "S-1", + "로그인 성공, JWT AccessToken 을 발급합니다.", + Ut.mapOf("Authentication", accessToken) + ), + Ut.spring.httpHeadersOf("Authentication", accessToken) + ); } } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java index bd8b69f..69fa4a0 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java @@ -12,8 +12,12 @@ public class RsData { private String msg; private T data; + public static RsData of(String resultCode, String msg, T data) { + return new RsData<>(resultCode, msg, data); + } + public static RsData of(String resultCode, String msg) { - return new RsData<>(resultCode, msg, null); + return of(resultCode, msg, null); } public boolean isSuccess() { From cef4d55d2fb1edba5403289964063dd46b212d0f Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 11:45:25 +0900 Subject: [PATCH 17/39] =?UTF-8?q?#36=20-=20Chore:=20JWT=20dependency=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 4Week_Mission/mutbooks/build.gradle | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/4Week_Mission/mutbooks/build.gradle b/4Week_Mission/mutbooks/build.gradle index 7ebaf24..0f94bc2 100644 --- a/4Week_Mission/mutbooks/build.gradle +++ b/4Week_Mission/mutbooks/build.gradle @@ -56,6 +56,11 @@ dependencies { testImplementation 'org.springframework.batch:spring-batch-test' // apache httpclient implementation 'org.apache.httpcomponents:httpclient:4.5' + + // jwt + implementation 'io.jsonwebtoken:jjwt-api:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' } tasks.named('test') { From 260b27e5105078a80f3bd6e50ad253174f659b1a Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 11:47:00 +0900 Subject: [PATCH 18/39] =?UTF-8?q?#2=20#36=20-=20Feat:=20Ut.json=20?= =?UTF-8?q?=EB=8F=84=EC=9E=85(Json<->String:=20=EC=A7=81=EB=A0=AC=ED=99=94?= =?UTF-8?q?,=20=EC=97=AD=EC=A7=81=EB=A0=AC=ED=99=94=20=EB=A9=94=EC=84=9C?= =?UTF-8?q?=EB=93=9C=20=EC=B6=94=EA=B0=80)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/example/mutbooks/util/Ut.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java index ac3463f..8fa4b17 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java @@ -1,6 +1,9 @@ package com.example.mutbooks.util; +import com.example.mutbooks.app.AppConfig; import com.example.mutbooks.app.base.dto.RsData; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -14,6 +17,34 @@ import java.util.Map; public class Ut { + // jwt 관련 + private static ObjectMapper getObjectMapper() { + return (ObjectMapper) AppConfig.getContext().getBean("objectMapper"); + } + + public static class json { + + // map(json) -> String 변환 + public static Object toStr(Map map) { + try { + return getObjectMapper().writeValueAsString(map); + } catch (JsonProcessingException e) { + return null; + } + } + + // String -> map(json) 변환 + public static Map toMap(String jsonStr) { + try { + return getObjectMapper().readValue(jsonStr, LinkedHashMap.class); + } catch (JsonProcessingException e) { + return null; + } + } + } + // 추가 끝 + + // 인자 값들을 map 형태로 반환 public static Map mapOf(Object... args) { Map map = new LinkedHashMap<>(); From 0e92a77aa78afc95e8e2e2f3de83bbd9773acf46 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 14:48:43 +0900 Subject: [PATCH 19/39] =?UTF-8?q?#36=20-=20Feat:=20JwtConfig(JWT=20SecretK?= =?UTF-8?q?ey=20=EA=B4=80=EB=A6=AC),=20JwtProvider(JWT=20=ED=86=A0?= =?UTF-8?q?=ED=81=B0=20=EC=83=9D=EC=84=B1/=EA=B2=80=EC=A6=9D)=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mutbooks/app/security/jwt/JwtConfig.java | 26 +++++++ .../app/security/jwt/JwtProvider.java | 68 +++++++++++++++++++ .../src/main/resources/application.yml | 4 +- 3 files changed, 97 insertions(+), 1 deletion(-) create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtConfig.java create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtConfig.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtConfig.java new file mode 100644 index 0000000..963942d --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtConfig.java @@ -0,0 +1,26 @@ +package com.example.mutbooks.app.security.jwt; + +import io.jsonwebtoken.security.Keys; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.crypto.SecretKey; +import java.util.Base64; + +/** + * JwtConfig + * - JWT 비밀키 관리 + */ +@Configuration +public class JwtConfig { + @Value("${custom.jwt.secretKey}") + private String secretKeyPlain; // 비밀키 원문 + + // JWT 비밀키 싱글톤 빈 관리 + @Bean + public SecretKey jwtSecretKey() { + String keyBase64Encoded = Base64.getEncoder().encodeToString(secretKeyPlain.getBytes()); + return Keys.hmacShaKeyFor(keyBase64Encoded.getBytes()); + } +} diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java new file mode 100644 index 0000000..c43c710 --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java @@ -0,0 +1,68 @@ +package com.example.mutbooks.app.security.jwt; + +import com.example.mutbooks.util.Ut; +import io.jsonwebtoken.ExpiredJwtException; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import java.util.Date; +import java.util.Map; + +/** + * JwtProvider + * - JWT 토큰 생성, 검증에 관여 + */ +@Component +@RequiredArgsConstructor +public class JwtProvider { + private final SecretKey jwtSecretKey; // 비밀키 + + private SecretKey getSecretKey() { + return jwtSecretKey; + } + + // JWT Access Token 발급 + public String generateAccessToken(Map claims, int seconds) { + long now = new Date().getTime(); + Date accessTokenExpiresIn = new Date(now + 1000L * seconds); + + return Jwts.builder() + .claim("body", Ut.json.toStr(claims)) // Claims 정보 설정 + .setExpiration(accessTokenExpiresIn) // accessToken 만료 시간 설정 + .signWith(getSecretKey(), SignatureAlgorithm.HS512) // HS512, 비밀키로 서명 + .compact(); // 토큰 생성 + } + + // JWT Access Token 검증 + public boolean verify(String accessToken) { + try { + Jwts.parserBuilder() + .setSigningKey(getSecretKey()) // 비밀키 + .build() + .parseClaimsJws(accessToken); // 파싱 및 검증(실패시 에러) + } catch (ExpiredJwtException e) { + // 토큰이 만료되었을 경우 + return false; + } + catch (Exception e) { + // 그 외 에러 + return false; + } + return true; + } + + // accessToken 으로부터 Claim 정보 얻기 + public Map getClaims(String accessToken) { + String body = Jwts.parserBuilder() + .setSigningKey(getSecretKey()) + .build() + .parseClaimsJws(accessToken) + .getBody() + .get("body", String.class); + + return Ut.json.toMap(body); + } +} diff --git a/4Week_Mission/mutbooks/src/main/resources/application.yml b/4Week_Mission/mutbooks/src/main/resources/application.yml index 9c3af69..2a49bc8 100644 --- a/4Week_Mission/mutbooks/src/main/resources/application.yml +++ b/4Week_Mission/mutbooks/src/main/resources/application.yml @@ -36,4 +36,6 @@ logging: custom: site: name: MUTBooks - baseUrl: "http://localhost:8010" \ No newline at end of file + baseUrl: "http://localhost:8010" + jwt: + secretKey: secretKeysecretKeysecretKeysecretKeysecretKeysecretKeysecretKeysecretKeysecretKeysecretKey \ No newline at end of file From 45af45920f1b1b98cb27a02b7332f274b8814400 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 15:04:17 +0900 Subject: [PATCH 20/39] =?UTF-8?q?#33=20-=20Feat:=20=EB=A1=9C=EA=B7=B8?= =?UTF-8?q?=EC=9D=B8=20=EC=84=B1=EA=B3=B5=EC=8B=9C=20=ED=9A=8C=EC=9B=90=20?= =?UTF-8?q?=EC=A0=95=EB=B3=B4=EB=A5=BC=20=EB=B0=94=ED=83=95=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EB=B0=9C=EA=B8=89=ED=95=9C=20accessToken=20?= =?UTF-8?q?=EC=9D=84=20=EC=9D=91=EB=8B=B5=20=ED=97=A4=EB=8D=94,=20?= =?UTF-8?q?=EB=B0=94=EB=94=94=EC=97=90=20=EB=8B=B4=EC=95=84=20=EB=B3=B4?= =?UTF-8?q?=EB=82=B4=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/api/controller/MemberApiController.java | 6 +++++- .../example/mutbooks/app/member/entity/Member.java | 14 ++++++++++++++ .../mutbooks/app/member/service/MemberService.java | 10 ++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java index 424e0af..eee6a39 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java @@ -6,6 +6,7 @@ import com.example.mutbooks.app.member.service.MemberService; import com.example.mutbooks.util.Ut; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.PostMapping; @@ -16,6 +17,7 @@ @RestController @RequestMapping("/api/v1/member") @RequiredArgsConstructor +@Slf4j public class MemberApiController { private final MemberService memberService; private final PasswordEncoder passwordEncoder; @@ -38,7 +40,9 @@ public ResponseEntity login(@RequestBody LoginDto loginDto) { return Ut.spring.responseEntityOf(RsData.of("F-3", "비밀번호가 일치하지 않습니다.")); } - String accessToken = "JWT Access Token"; + log.debug("Ut.json.toStr(member.getAccessTokenClaims()) : " + Ut.json.toStr(member.getAccessTokenClaims())); + // accessToken 발급 + String accessToken = memberService.genAccessToken(member); // 응답 헤더, 바디에 accessToken 담기 return Ut.spring.responseEntityOf( RsData.of( diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java index 3e35048..17357ba 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java @@ -1,6 +1,7 @@ package com.example.mutbooks.app.member.entity; import com.example.mutbooks.app.base.entity.BaseEntity; +import com.example.mutbooks.util.Ut; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.*; import lombok.experimental.SuperBuilder; @@ -11,6 +12,7 @@ import javax.persistence.*; import java.util.ArrayList; import java.util.List; +import java.util.Map; @Entity @Getter @@ -79,4 +81,16 @@ public List genAuthorities() { return authorities; } + + // AccessToken 발급을 위해 회원 정보를 바탕으로 claim map 객체 만들어 반환 + public Map getAccessTokenClaims() { + return Ut.mapOf( + "id", getId(), + "createDate", getCreateDate(), + "updateDate", getUpdateDate(), + "username", getUsername(), + "email", getEmail(), + "authorities", genAuthorities() + ); + } } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java index 4abf50d..125d318 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java @@ -13,6 +13,7 @@ import com.example.mutbooks.app.member.form.PwdModifyForm; import com.example.mutbooks.app.member.form.WithdrawAccountForm; import com.example.mutbooks.app.member.repository.MemberRepository; +import com.example.mutbooks.app.security.jwt.JwtProvider; import lombok.RequiredArgsConstructor; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContext; @@ -21,6 +22,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.Map; import java.util.UUID; @Service @@ -31,6 +33,7 @@ public class MemberService { private final PasswordEncoder passwordEncoder; private final MailService mailService; private final CashService cashService; + private final JwtProvider jwtProvider; @Transactional public Member join(JoinForm joinForm) { @@ -157,4 +160,11 @@ public void createBankInfo(Member member, WithdrawAccountForm withDrawAccountFor // TODO: 계좌 정보는 memberContext 값에 담겨있지 않으므로 세션값 강제 수정할 필요X //forceAuthentication(member); } + + public String genAccessToken(Member member) { + Map claims = member.getAccessTokenClaims(); + String accessToken = jwtProvider.generateAccessToken(claims, 60 * 60 * 24 * 90); // 유효기간 90일 + + return accessToken; + } } From 11034d5cb5f7f2514443d7b656ef1289b8a97031 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 15:26:13 +0900 Subject: [PATCH 21/39] =?UTF-8?q?Feat:=20security=20=EA=B4=80=EB=A0=A8=20?= =?UTF-8?q?=ED=8C=A8=ED=82=A4=EC=A7=80=20=EC=9D=B4=EB=8F=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/com/example/mutbooks/app/AppConfig.java | 1 + .../example/mutbooks/app/cart/controller/CartController.java | 2 +- .../mutbooks/app/member/controller/MemberController.java | 2 +- .../example/mutbooks/app/member/service/MemberService.java | 2 +- .../mutbooks/app/order/controller/OrderController.java | 2 +- .../example/mutbooks/app/post/controller/PostController.java | 2 +- .../mutbooks/app/product/controller/ProductController.java | 2 +- .../mutbooks/app/{base => }/security/SecurityConfig.java | 2 +- .../mutbooks/app/{base => }/security/dto/MemberContext.java | 2 +- .../{base => }/security/service/CustomUserDetailsService.java | 4 ++-- .../app/withdraw/controller/AdmWithdrawController.java | 2 +- .../mutbooks/app/withdraw/controller/WithdrawController.java | 2 +- 12 files changed, 13 insertions(+), 12 deletions(-) rename 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/{base => }/security/SecurityConfig.java (97%) rename 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/{base => }/security/dto/MemberContext.java (97%) rename 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/{base => }/security/service/CustomUserDetailsService.java (89%) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/AppConfig.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/AppConfig.java index 59eebdc..e62a32c 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/AppConfig.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/AppConfig.java @@ -68,6 +68,7 @@ public static boolean isTest() { @Bean public ObjectMapper objectMapper() { + // LocalDateTime 관련 직렬화/역직렬화 오류시, new JavaTimeModule() 추가 return new ObjectMapper().registerModule(new JavaTimeModule()); } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/cart/controller/CartController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/cart/controller/CartController.java index c38ca07..3251a1e 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/cart/controller/CartController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/cart/controller/CartController.java @@ -1,6 +1,6 @@ package com.example.mutbooks.app.cart.controller; -import com.example.mutbooks.app.base.security.dto.MemberContext; +import com.example.mutbooks.app.security.dto.MemberContext; import com.example.mutbooks.app.cart.entity.CartItem; import com.example.mutbooks.app.cart.service.CartService; import com.example.mutbooks.app.member.entity.Member; diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/controller/MemberController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/controller/MemberController.java index a25f755..2d85d6c 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/controller/MemberController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/controller/MemberController.java @@ -1,6 +1,6 @@ package com.example.mutbooks.app.member.controller; -import com.example.mutbooks.app.base.security.dto.MemberContext; +import com.example.mutbooks.app.security.dto.MemberContext; import com.example.mutbooks.app.mail.service.MailService; import com.example.mutbooks.app.member.entity.Member; import com.example.mutbooks.app.member.form.JoinForm; diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java index 125d318..4a4f40c 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java @@ -1,6 +1,6 @@ package com.example.mutbooks.app.member.service; -import com.example.mutbooks.app.base.security.dto.MemberContext; +import com.example.mutbooks.app.security.dto.MemberContext; import com.example.mutbooks.app.cash.entity.CashLog; import com.example.mutbooks.app.cash.service.CashService; import com.example.mutbooks.app.mail.service.MailService; diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/order/controller/OrderController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/order/controller/OrderController.java index 67d1a4a..0684414 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/order/controller/OrderController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/order/controller/OrderController.java @@ -1,6 +1,6 @@ package com.example.mutbooks.app.order.controller; -import com.example.mutbooks.app.base.security.dto.MemberContext; +import com.example.mutbooks.app.security.dto.MemberContext; import com.example.mutbooks.app.member.entity.Member; import com.example.mutbooks.app.member.service.MemberService; import com.example.mutbooks.app.order.entity.Order; diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/post/controller/PostController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/post/controller/PostController.java index 3b01c20..128e14a 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/post/controller/PostController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/post/controller/PostController.java @@ -1,6 +1,6 @@ package com.example.mutbooks.app.post.controller; -import com.example.mutbooks.app.base.security.dto.MemberContext; +import com.example.mutbooks.app.security.dto.MemberContext; import com.example.mutbooks.app.member.entity.Member; import com.example.mutbooks.app.post.entity.Post; import com.example.mutbooks.app.post.form.WriteForm; diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/product/controller/ProductController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/product/controller/ProductController.java index 9fbb6f6..1663d69 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/product/controller/ProductController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/product/controller/ProductController.java @@ -1,6 +1,6 @@ package com.example.mutbooks.app.product.controller; -import com.example.mutbooks.app.base.security.dto.MemberContext; +import com.example.mutbooks.app.security.dto.MemberContext; import com.example.mutbooks.app.member.entity.Member; import com.example.mutbooks.app.postKeyword.dto.PostKeywordDto; import com.example.mutbooks.app.postKeyword.service.PostKeywordService; diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/security/SecurityConfig.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/SecurityConfig.java similarity index 97% rename from 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/security/SecurityConfig.java rename to 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/SecurityConfig.java index 9b90ffa..b45ef7a 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/security/SecurityConfig.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/SecurityConfig.java @@ -1,4 +1,4 @@ -package com.example.mutbooks.app.base.security; +package com.example.mutbooks.app.security; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/security/dto/MemberContext.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/dto/MemberContext.java similarity index 97% rename from 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/security/dto/MemberContext.java rename to 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/dto/MemberContext.java index ec279e3..909ed03 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/security/dto/MemberContext.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/dto/MemberContext.java @@ -1,4 +1,4 @@ -package com.example.mutbooks.app.base.security.dto; +package com.example.mutbooks.app.security.dto; import com.example.mutbooks.app.member.entity.Member; import lombok.Getter; diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/security/service/CustomUserDetailsService.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/service/CustomUserDetailsService.java similarity index 89% rename from 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/security/service/CustomUserDetailsService.java rename to 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/service/CustomUserDetailsService.java index fca11ee..5f682a8 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/security/service/CustomUserDetailsService.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/service/CustomUserDetailsService.java @@ -1,6 +1,6 @@ -package com.example.mutbooks.app.base.security.service; +package com.example.mutbooks.app.security.service; -import com.example.mutbooks.app.base.security.dto.MemberContext; +import com.example.mutbooks.app.security.dto.MemberContext; import com.example.mutbooks.app.member.entity.Member; import com.example.mutbooks.app.member.repository.MemberRepository; import lombok.RequiredArgsConstructor; diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/AdmWithdrawController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/AdmWithdrawController.java index 70b5289..72e1d98 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/AdmWithdrawController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/AdmWithdrawController.java @@ -1,6 +1,6 @@ package com.example.mutbooks.app.withdraw.controller; -import com.example.mutbooks.app.base.security.dto.MemberContext; +import com.example.mutbooks.app.security.dto.MemberContext; import com.example.mutbooks.app.withdraw.entity.WithdrawApply; import com.example.mutbooks.app.withdraw.service.WithdrawService; import lombok.RequiredArgsConstructor; diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/WithdrawController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/WithdrawController.java index 021dab7..9a2cbee 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/WithdrawController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/WithdrawController.java @@ -1,6 +1,6 @@ package com.example.mutbooks.app.withdraw.controller; -import com.example.mutbooks.app.base.security.dto.MemberContext; +import com.example.mutbooks.app.security.dto.MemberContext; import com.example.mutbooks.app.member.entity.Member; import com.example.mutbooks.app.member.service.MemberService; import com.example.mutbooks.app.withdraw.entity.WithdrawApply; From 976e7dcc8de914f53b271adb0ea87297746d587f Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 16:59:45 +0900 Subject: [PATCH 22/39] =?UTF-8?q?#36=20-=20Feat:=20REST=20API=20=EC=9A=94?= =?UTF-8?q?=EC=B2=AD=EC=97=90=20=EB=8C=80=ED=95=9C=20ApiSecurityConfig=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80,=20=EC=9D=B8=EC=A6=9D/=EC=9D=B8=EA=B0=80=20?= =?UTF-8?q?=EC=88=98=ED=96=89=ED=95=98=EB=8A=94=20JwtAuthorizationFilter?= =?UTF-8?q?=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mutbooks/app/member/entity/Member.java | 4 +- .../app/member/service/MemberService.java | 2 +- .../app/security/ApiSecurityConfig.java | 66 +++++++++++++++++ .../app/security/dto/MemberContext.java | 11 +++ .../filter/JwtAuthorizationFilter.java | 71 +++++++++++++++++++ .../service/CustomUserDetailsService.java | 2 +- 6 files changed, 152 insertions(+), 4 deletions(-) create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/ApiSecurityConfig.java create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java index 17357ba..f5a3f37 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java @@ -64,7 +64,7 @@ public boolean hasBankInfo() { } // 권한 부여 - public List genAuthorities() { + public List getAuthorities() { List authorities = new ArrayList<>(); // 모든 로그인한 회원에게는 USER 권한 부여 authorities.add(new SimpleGrantedAuthority(AuthLevel.USER.getValue())); // 일반 회원 @@ -90,7 +90,7 @@ public Map getAccessTokenClaims() { "updateDate", getUpdateDate(), "username", getUsername(), "email", getEmail(), - "authorities", genAuthorities() + "authorities", getAuthorities() ); } } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java index 4a4f40c..0cbbfa5 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java @@ -68,7 +68,7 @@ public void modifyProfile(Member member, ModifyForm modifyForm) { // 세션에 담긴 회원 기본정보 강제 수정 public void forceAuthentication(Member member) { - MemberContext memberContext = new MemberContext(member, member.genAuthorities()); + MemberContext memberContext = new MemberContext(member, member.getAuthorities()); UsernamePasswordAuthenticationToken authentication = UsernamePasswordAuthenticationToken.authenticated( diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/ApiSecurityConfig.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/ApiSecurityConfig.java new file mode 100644 index 0000000..2b4cc78 --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/ApiSecurityConfig.java @@ -0,0 +1,66 @@ +package com.example.mutbooks.app.security; + +import com.example.mutbooks.app.security.filter.JwtAuthorizationFilter; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS; + +@EnableWebSecurity +@RequiredArgsConstructor +public class ApiSecurityConfig { + private final JwtAuthorizationFilter jwtAuthorizationFilter; +// private final ApiAuthenticationEntryPoint authenticationEntryPoint; + + @Bean + public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception { + http + .antMatcher("/api/**") +// .exceptionHandling(exceptionHandling -> exceptionHandling +// .authenticationEntryPoint(authenticationEntryPoint) +// ) + .httpBasic().disable() + .csrf().disable() + .cors(cors -> cors + .configurationSource(corsConfigurationSource()) + ) + .authorizeRequests( + authorizeRequests -> authorizeRequests + // 로그인 요청 외 모든 요청은 로그인 필수 + .antMatchers("/api/*/member/login").permitAll() + .anyRequest() + .authenticated() // 최소자격 : 로그인 + ) + .sessionManagement(sessionManagement -> sessionManagement + .sessionCreationPolicy(STATELESS) + ) + .formLogin().disable() + .addFilterBefore( + jwtAuthorizationFilter, + UsernamePasswordAuthenticationFilter.class + ) + .logout().disable(); + + return http.build(); + } + + @Bean + public CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration corsConfiguration = new CorsConfiguration(); + + corsConfiguration.addAllowedOrigin("*"); + corsConfiguration.addAllowedHeader("*"); + corsConfiguration.addAllowedMethod("*"); + + UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); + urlBasedCorsConfigurationSource.registerCorsConfiguration("/api/**", corsConfiguration); + return urlBasedCorsConfigurationSource; + } +} \ No newline at end of file diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/dto/MemberContext.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/dto/MemberContext.java index 909ed03..d59dd36 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/dto/MemberContext.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/dto/MemberContext.java @@ -63,6 +63,17 @@ public Member getMember() { .build(); } + public MemberContext(Member member) { + super(member.getUsername(), "", member.getAuthorities()); + + id = member.getId(); + createDate = member.getCreateDate(); + updateDate = member.getUpdateDate(); + username = member.getUsername(); + email = member.getEmail(); +// authorities = member.getAuthorities().stream().collect(Collectors.toSet()); + } + public String getName() { return getUsername(); } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java new file mode 100644 index 0000000..8c8bf12 --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java @@ -0,0 +1,71 @@ +package com.example.mutbooks.app.security.filter; + +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.member.service.MemberService; +import com.example.mutbooks.app.security.dto.MemberContext; +import com.example.mutbooks.app.security.jwt.JwtProvider; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Map; + +/** + * 매 요청마다 컨트롤러에 요청이 도달하기 전에 필터를 거쳐 인증/인가 수행 + * 1. 요청 헤더의 Access Token 유효성 검증 + * 2. 토큰으로부터 회원 정보(claims)를 이용해 DB에서 Member 객체 조회 + * 3. 해당 회원 강제 로그인 처리(MemberContext 세션 등록) + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class JwtAuthorizationFilter extends OncePerRequestFilter { + private final JwtProvider jwtProvider; + private final MemberService memberService; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + String barerToken = request.getHeader("Authorization"); + // 토큰 유효성 검증 + if(barerToken != null) { + String token = barerToken.substring("Barer ".length()); + // 토큰이 유효하면 회원 정보 얻어서 강제 로그인 처리 + if(jwtProvider.verify(token)) { + Map claims = jwtProvider.getClaims(token); + String username = (String) claims.get("username"); + Member member = memberService.findByUsername(username); + + if(member != null) { + forceAuthentication(member); + } + } + } + filterChain.doFilter(request, response); + } + + // 강제 로그인 처리 + private void forceAuthentication(Member member) { + MemberContext memberContext = new MemberContext(member); + + UsernamePasswordAuthenticationToken authentication = + UsernamePasswordAuthenticationToken.authenticated( + memberContext, + null, + member.getAuthorities() + ); + + // 이후 컨트롤러 단에서 MemberContext 객체 사용O + SecurityContext context = SecurityContextHolder.createEmptyContext(); + context.setAuthentication(authentication); + SecurityContextHolder.setContext(context); + } +} \ No newline at end of file diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/service/CustomUserDetailsService.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/service/CustomUserDetailsService.java index 5f682a8..a212f82 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/service/CustomUserDetailsService.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/service/CustomUserDetailsService.java @@ -21,7 +21,7 @@ public class CustomUserDetailsService implements UserDetailsService { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Member member = memberRepository.findByUsername(username).get(); - List authorities = member.genAuthorities(); + List authorities = member.getAuthorities(); return new MemberContext(member, authorities); } From b2e8bfc9bc52b48825f4b22220ce0bbb2a0707aa Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 17:31:18 +0900 Subject: [PATCH 23/39] =?UTF-8?q?#2=20-=20Feat:=20=EC=84=B1=EA=B3=B5/?= =?UTF-8?q?=EC=8B=A4=ED=8C=A8=20=EB=94=94=ED=8F=B4=ED=8A=B8=20=EC=9D=91?= =?UTF-8?q?=EB=8B=B5(resultCode,=20msg=20=EB=94=94=ED=8F=B4=ED=8A=B8=20?= =?UTF-8?q?=EA=B0=92=20=EC=84=A4=EC=A0=95)=20=EB=A9=94=EC=84=9C=EB=93=9C?= =?UTF-8?q?=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/MemberApiController.java | 19 ++++++++++++++----- .../member/dto/request}/LoginDto.java | 0 .../example/mutbooks/app/base/dto/RsData.java | 10 ++++++++++ 3 files changed, 24 insertions(+), 5 deletions(-) rename 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/{ => member}/controller/MemberApiController.java (77%) rename 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/{member/dto => api/member/dto/request}/LoginDto.java (100%) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/controller/MemberApiController.java similarity index 77% rename from 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java rename to 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/controller/MemberApiController.java index eee6a39..0195ec0 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/controller/MemberApiController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/controller/MemberApiController.java @@ -4,15 +4,14 @@ import com.example.mutbooks.app.member.dto.LoginDto; import com.example.mutbooks.app.member.entity.Member; import com.example.mutbooks.app.member.service.MemberService; +import com.example.mutbooks.app.security.dto.MemberContext; import com.example.mutbooks.util.Ut; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/v1/member") @@ -47,10 +46,20 @@ public ResponseEntity login(@RequestBody LoginDto loginDto) { return Ut.spring.responseEntityOf( RsData.of( "S-1", - "로그인 성공, JWT AccessToken 을 발급합니다.", + "로그인 성공, Access Token을 발급합니다.", Ut.mapOf("Authentication", accessToken) ), Ut.spring.httpHeadersOf("Authentication", accessToken) ); } + + // 회원 정보 + @GetMapping("/me") + public ResponseEntity test(@AuthenticationPrincipal MemberContext memberContext) { + if(memberContext == null) { + return Ut.spring.responseEntityOf(RsData.failOf(null)); + } + + return Ut.spring.responseEntityOf(RsData.successOf(memberContext)); + } } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/dto/LoginDto.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/request/LoginDto.java similarity index 100% rename from 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/dto/LoginDto.java rename to 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/request/LoginDto.java diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java index 69fa4a0..71be8ec 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java @@ -20,6 +20,16 @@ public static RsData of(String resultCode, String msg) { return of(resultCode, msg, null); } + // 성공 응답 + public static RsData successOf(T data) { + return of("S-1", "성공", data); + } + + // 실패 응답 + public static RsData failOf(T data) { + return of("F-1", "실패", data); + } + public boolean isSuccess() { return resultCode.startsWith("S-1"); } From 24e0b94e6bcf89efb4aaaad5a2805174a70c1be7 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 17:33:05 +0900 Subject: [PATCH 24/39] =?UTF-8?q?#33=20-=20Feat:=20GET=20/api/v1/member/me?= =?UTF-8?q?=20(=EB=A1=9C=EA=B7=B8=EC=9D=B8=ED=95=9C=20=ED=9A=8C=EC=9B=90?= =?UTF-8?q?=EC=A0=95=EB=B3=B4=20=EC=A1=B0=ED=9A=8C)=20=EC=9A=94=EC=B2=AD?= =?UTF-8?q?=20=EA=B5=AC=ED=98=84,=20response=20MemberDto=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/MemberApiController.java | 10 +++--- .../app/api/member/dto/request/LoginDto.java | 2 +- .../api/member/dto/response/MemberDto.java | 34 +++++++++++++++++++ 3 files changed, 41 insertions(+), 5 deletions(-) create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/response/MemberDto.java diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/controller/MemberApiController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/controller/MemberApiController.java index 0195ec0..f81cbc1 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/controller/MemberApiController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/controller/MemberApiController.java @@ -1,7 +1,8 @@ -package com.example.mutbooks.app.api.controller; +package com.example.mutbooks.app.api.member.controller; +import com.example.mutbooks.app.api.member.dto.response.MemberDto; import com.example.mutbooks.app.base.dto.RsData; -import com.example.mutbooks.app.member.dto.LoginDto; +import com.example.mutbooks.app.api.member.dto.request.LoginDto; import com.example.mutbooks.app.member.entity.Member; import com.example.mutbooks.app.member.service.MemberService; import com.example.mutbooks.app.security.dto.MemberContext; @@ -59,7 +60,8 @@ public ResponseEntity test(@AuthenticationPrincipal MemberContext member if(memberContext == null) { return Ut.spring.responseEntityOf(RsData.failOf(null)); } - - return Ut.spring.responseEntityOf(RsData.successOf(memberContext)); + MemberDto memberDto = MemberDto.toDto(memberContext.getMember()); + + return Ut.spring.responseEntityOf(RsData.successOf(Ut.mapOf("member", memberDto))); } } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/request/LoginDto.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/request/LoginDto.java index 8983ff2..06f5c7a 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/request/LoginDto.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/request/LoginDto.java @@ -1,4 +1,4 @@ -package com.example.mutbooks.app.member.dto; +package com.example.mutbooks.app.api.member.dto.request; import lombok.Data; diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/response/MemberDto.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/response/MemberDto.java new file mode 100644 index 0000000..355db95 --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/response/MemberDto.java @@ -0,0 +1,34 @@ +package com.example.mutbooks.app.api.member.dto.response; + +import com.example.mutbooks.app.member.entity.Member; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@Builder +@AllArgsConstructor +public class MemberDto { + private Long id; + private LocalDateTime createDate; + private LocalDateTime modifyDate; + private String username; + private String email; + private boolean emailVerified; + private String nickname; + + public static MemberDto toDto(Member member) { + return MemberDto.builder() + .id(member.getId()) + .createDate(member.getCreateDate()) + .modifyDate(member.getUpdateDate()) + .username(member.getUsername()) + .email(member.getEmail()) + .nickname(member.getNickname()) + .build(); + } +} From c23e7a834b5ac35d3839d123ec4c744ca8802ebc Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 18:17:08 +0900 Subject: [PATCH 25/39] =?UTF-8?q?#33=20-=20Feat:=20GET=20/api/v1/myBooks?= =?UTF-8?q?=20(=EB=82=B4=20=EB=8F=84=EC=84=9C=20=EB=A6=AC=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=20=EC=A1=B0=ED=9A=8C)=20=EA=B5=AC=ED=98=84,=20respons?= =?UTF-8?q?e.MyBookDto,=20ProductDto=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/api/myBooks/MyBooksApiController.java | 34 +++++++++++++++++++ .../app/mybook/dto/response/MyBookDto.java | 34 +++++++++++++++++++ .../mybook/repository/MyBookRepository.java | 4 +++ .../app/mybook/service/MyBookService.java | 14 ++++++++ .../app/product/dto/response/ProductDto.java | 33 ++++++++++++++++++ 5 files changed, 119 insertions(+) create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDto.java create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDto.java diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java new file mode 100644 index 0000000..66153da --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java @@ -0,0 +1,34 @@ +package com.example.mutbooks.app.api.myBooks; + +import com.example.mutbooks.app.base.dto.RsData; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.mybook.dto.response.MyBookDto; +import com.example.mutbooks.app.mybook.service.MyBookService; +import com.example.mutbooks.app.security.dto.MemberContext; +import com.example.mutbooks.util.Ut; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api/v1/myBooks") +@RequiredArgsConstructor +public class MyBooksApiController { + private final MyBookService myBookService; + + // 내 도서 리스트 + @GetMapping("") + public ResponseEntity list(@AuthenticationPrincipal MemberContext memberContext) { + Member member = memberContext.getMember(); + List myBookDtos = myBookService.findAllByOwner(member); + + return Ut.spring.responseEntityOf( + RsData.successOf(Ut.mapOf("myBooks", myBookDtos)) + ); + } +} diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDto.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDto.java new file mode 100644 index 0000000..e07b4e4 --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDto.java @@ -0,0 +1,34 @@ +package com.example.mutbooks.app.mybook.dto.response; + +import com.example.mutbooks.app.mybook.entity.MyBook; +import com.example.mutbooks.app.product.dto.response.ProductDto; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@Builder +@AllArgsConstructor +public class MyBookDto { + private Long id; + private LocalDateTime createDate; + private LocalDateTime modifyDate; + private Long ownerId; + private ProductDto product; + + public static MyBookDto toDto(MyBook myBook) { + ProductDto productDto = ProductDto.toDto(myBook.getProduct()); + + return MyBookDto.builder() + .id(myBook.getId()) + .createDate(myBook.getCreateDate()) + .modifyDate(myBook.getUpdateDate()) + .ownerId(myBook.getOwner().getId()) + .product(productDto) + .build(); + } +} diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/repository/MyBookRepository.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/repository/MyBookRepository.java index f2e119a..5be2108 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/repository/MyBookRepository.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/repository/MyBookRepository.java @@ -1,12 +1,16 @@ package com.example.mutbooks.app.mybook.repository; +import com.example.mutbooks.app.member.entity.Member; import com.example.mutbooks.app.mybook.entity.MyBook; import org.springframework.data.jpa.repository.JpaRepository; +import java.util.List; import java.util.Optional; public interface MyBookRepository extends JpaRepository { Optional findByProductIdAndOwnerId(Long productId, Long ownerId); void deleteByProductIdAndOwnerId(Long productId, Long ownerId); + + List findByOwner(Member owner); } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java index 2d2f209..fad5492 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java @@ -1,6 +1,7 @@ package com.example.mutbooks.app.mybook.service; import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.mybook.dto.response.MyBookDto; import com.example.mutbooks.app.mybook.entity.MyBook; import com.example.mutbooks.app.mybook.repository.MyBookRepository; import com.example.mutbooks.app.order.entity.Order; @@ -10,6 +11,9 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.List; +import java.util.stream.Collectors; + @Service @RequiredArgsConstructor @Transactional(readOnly = true) @@ -51,4 +55,14 @@ public void remove(Order order) { public MyBook findByProductIdAndOwnerId(long productId, long ownerId) { return myBookRepository.findByProductIdAndOwnerId(productId, ownerId).orElse(null); } + + public List findAllByOwner(Member owner) { + List myBooks = myBookRepository.findByOwner(owner); + + List myBookDtos = myBooks.stream() + .map(myBook -> MyBookDto.toDto(myBook)) + .collect(Collectors.toList()); + + return myBookDtos; + } } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDto.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDto.java new file mode 100644 index 0000000..1db557e --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDto.java @@ -0,0 +1,33 @@ +package com.example.mutbooks.app.product.dto.response; + +import com.example.mutbooks.app.product.entity.Product; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@Builder +@AllArgsConstructor +public class ProductDto { + private Long id; + private LocalDateTime createDate; + private LocalDateTime modifyDate; + private Long authorId; + private String authorName; + private String subject; + + public static ProductDto toDto(Product product) { + return ProductDto.builder() + .id(product.getId()) + .createDate(product.getCreateDate()) + .modifyDate(product.getUpdateDate()) + .authorId(product.getAuthor().getId()) + .authorName(product.getAuthor().getNickname()) + .subject(product.getSubject()) + .build(); + } +} From 033f34edeff12ff55c4a10dabf41378277829cdd Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 21:54:40 +0900 Subject: [PATCH 26/39] =?UTF-8?q?#33=20-=20Feat:=20GET=20/api/v1/myBooks/{?= =?UTF-8?q?myBookId}=20(=EB=82=B4=20=EB=8F=84=EC=84=9C=20=EC=83=81?= =?UTF-8?q?=EC=84=B8=EC=A1=B0=ED=9A=8C=20=EC=9A=94=EC=B2=AD)=20=EA=B5=AC?= =?UTF-8?q?=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/api/myBooks/MyBooksApiController.java | 12 ++++++ .../mybook/dto/response/MyBookDetailDto.java | 36 +++++++++++++++++ .../exception/MyBookNotFoundException.java | 7 ++++ .../app/mybook/service/MyBookService.java | 27 +++++++++++++ .../app/post/dto/response/PostDetailDto.java | 38 ++++++++++++++++++ .../repository/PostHashTagRepository.java | 3 ++ .../service/PostHashTagService.java | 4 ++ .../dto/response/ProductDetailDto.java | 40 +++++++++++++++++++ 8 files changed, 167 insertions(+) create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDetailDto.java create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/exception/MyBookNotFoundException.java create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/post/dto/response/PostDetailDto.java create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDetailDto.java diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java index 66153da..daa731f 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java @@ -2,6 +2,7 @@ import com.example.mutbooks.app.base.dto.RsData; import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.mybook.dto.response.MyBookDetailDto; import com.example.mutbooks.app.mybook.dto.response.MyBookDto; import com.example.mutbooks.app.mybook.service.MyBookService; import com.example.mutbooks.app.security.dto.MemberContext; @@ -10,6 +11,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -31,4 +33,14 @@ public ResponseEntity list(@AuthenticationPrincipal MemberContext member RsData.successOf(Ut.mapOf("myBooks", myBookDtos)) ); } + + // 도서 상세 조회 + @GetMapping("/{myBookId}") + public ResponseEntity detail(@PathVariable long myBookId, @AuthenticationPrincipal MemberContext memberContext) { + MyBookDetailDto myBookDetailDto = myBookService.findByIdForDetail(myBookId); + + return Ut.spring.responseEntityOf( + RsData.successOf(Ut.mapOf("myBook", myBookDetailDto)) + ); + } } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDetailDto.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDetailDto.java new file mode 100644 index 0000000..58d82e3 --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDetailDto.java @@ -0,0 +1,36 @@ +package com.example.mutbooks.app.mybook.dto.response; + +import com.example.mutbooks.app.mybook.entity.MyBook; +import com.example.mutbooks.app.post.entity.Post; +import com.example.mutbooks.app.product.dto.response.ProductDetailDto; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; +import java.util.List; + +@Getter +@Setter +@Builder +@AllArgsConstructor +public class MyBookDetailDto { + private Long id; + private LocalDateTime createDate; + private LocalDateTime modifyDate; + private Long ownerId; + private ProductDetailDto product; + + public static MyBookDetailDto toDto(MyBook myBook, List posts) { + ProductDetailDto productDetailDto = ProductDetailDto.toDto(myBook.getProduct(), posts); + + return MyBookDetailDto.builder() + .id(myBook.getId()) + .createDate(myBook.getCreateDate()) + .modifyDate(myBook.getUpdateDate()) + .ownerId(myBook.getOwner().getId()) + .product(productDetailDto) + .build(); + } +} diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/exception/MyBookNotFoundException.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/exception/MyBookNotFoundException.java new file mode 100644 index 0000000..9a33311 --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/exception/MyBookNotFoundException.java @@ -0,0 +1,7 @@ +package com.example.mutbooks.app.mybook.exception; + +public class MyBookNotFoundException extends RuntimeException { + public MyBookNotFoundException(String message) { + super(message); + } +} diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java index fad5492..0dc4001 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java @@ -1,11 +1,17 @@ package com.example.mutbooks.app.mybook.service; import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.mybook.dto.response.MyBookDetailDto; import com.example.mutbooks.app.mybook.dto.response.MyBookDto; import com.example.mutbooks.app.mybook.entity.MyBook; +import com.example.mutbooks.app.mybook.exception.MyBookNotFoundException; import com.example.mutbooks.app.mybook.repository.MyBookRepository; import com.example.mutbooks.app.order.entity.Order; import com.example.mutbooks.app.order.entity.OrderItem; +import com.example.mutbooks.app.post.entity.Post; +import com.example.mutbooks.app.postHashTag.entity.PostHashTag; +import com.example.mutbooks.app.postHashTag.service.PostHashTagService; +import com.example.mutbooks.app.postKeyword.entity.PostKeyword; import com.example.mutbooks.app.product.entity.Product; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @@ -19,6 +25,7 @@ @Transactional(readOnly = true) public class MyBookService { private final MyBookRepository myBookRepository; + private final PostHashTagService postHashTagService; // MyBook 추가 @Transactional @@ -65,4 +72,24 @@ public List findAllByOwner(Member owner) { return myBookDtos; } + + public MyBook findById(long id) { + return myBookRepository.findById(id).orElseThrow(() -> { + throw new MyBookNotFoundException(""); + }); + } + + public MyBookDetailDto findByIdForDetail(long id) { + MyBook myBook = findById(id); + + PostKeyword postKeyword = myBook.getProduct().getPostKeyword(); + List postHashTags = postHashTagService.findByPostKeyword(postKeyword); + + List posts = postHashTags.stream() + .map(postHashTag -> postHashTag.getPost()) + .collect(Collectors.toList()); + + // 본인이 소유한 도서인지 검증 + return MyBookDetailDto.toDto(myBook, posts); + } } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/post/dto/response/PostDetailDto.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/post/dto/response/PostDetailDto.java new file mode 100644 index 0000000..3bac035 --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/post/dto/response/PostDetailDto.java @@ -0,0 +1,38 @@ +package com.example.mutbooks.app.post.dto.response; + +import com.example.mutbooks.app.post.entity.Post; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +import java.util.List; +import java.util.stream.Collectors; + +@Getter +@Setter +@Builder +@AllArgsConstructor +public class PostDetailDto { + private Long id; + private String subject; + private String content; + private String contentHtml; + + public static PostDetailDto toDto(Post post) { + return PostDetailDto.builder() + .id(post.getId()) + .subject(post.getSubject()) + .content(post.getContent()) + .contentHtml(post.getContentHtml()) + .build(); + } + + public static List toDtos(List posts) { + List postDetailDtos = posts.stream() + .map(post -> PostDetailDto.toDto(post)) + .collect(Collectors.toList()); + + return postDetailDtos; + } +} diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/repository/PostHashTagRepository.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/repository/PostHashTagRepository.java index d6176d2..b9622aa 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/repository/PostHashTagRepository.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/repository/PostHashTagRepository.java @@ -1,6 +1,7 @@ package com.example.mutbooks.app.postHashTag.repository; import com.example.mutbooks.app.postHashTag.entity.PostHashTag; +import com.example.mutbooks.app.postKeyword.entity.PostKeyword; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; @@ -10,4 +11,6 @@ public interface PostHashTagRepository extends JpaRepository Optional findByPostIdAndPostKeywordId(Long postId, Long postKeywordId); List findByPostId(Long postId); + + List findByPostKeyword(PostKeyword postKeyword); } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/service/PostHashTagService.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/service/PostHashTagService.java index 2d2f773..cca6459 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/service/PostHashTagService.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/service/PostHashTagService.java @@ -77,4 +77,8 @@ public PostHashTag save(Post post, String keywordContent) { public List findByPostId(long postId) { return postHashTagRepository.findByPostId(postId); } + + public List findByPostKeyword(PostKeyword postKeyword) { + return postHashTagRepository.findByPostKeyword(postKeyword); + } } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDetailDto.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDetailDto.java new file mode 100644 index 0000000..3bb4240 --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDetailDto.java @@ -0,0 +1,40 @@ +package com.example.mutbooks.app.product.dto.response; + +import com.example.mutbooks.app.post.dto.response.PostDetailDto; +import com.example.mutbooks.app.post.entity.Post; +import com.example.mutbooks.app.product.entity.Product; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; +import java.util.List; + +@Getter +@Setter +@Builder +@AllArgsConstructor +public class ProductDetailDto { + private Long id; + private LocalDateTime createDate; + private LocalDateTime modifyDate; + private Long authorId; + private String authorName; + private String subject; + private List bookChapters; + + public static ProductDetailDto toDto(Product product, List posts) { + List postDetailDtos = PostDetailDto.toDtos(posts); + + return ProductDetailDto.builder() + .id(product.getId()) + .createDate(product.getCreateDate()) + .modifyDate(product.getUpdateDate()) + .authorId(product.getAuthor().getId()) + .authorName(product.getAuthor().getNickname()) + .subject(product.getSubject()) + .bookChapters(postDetailDtos) + .build(); + } +} From 9c18dbe6c6ea67c468173cbbcb94c482cf2d6b91 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 22:32:03 +0900 Subject: [PATCH 27/39] =?UTF-8?q?#33=20-=20Fix:=20=EB=A6=AC=EC=95=A1?= =?UTF-8?q?=ED=8A=B8=20=EB=A1=9C=EA=B7=B8=EC=9D=B8=20=EC=9A=94=EC=B2=AD?= =?UTF-8?q?=EB=B3=B4=EB=83=88=EC=9D=84=20=EB=95=8C,=20=EC=9D=91=EB=8B=B5?= =?UTF-8?q?=EB=B0=94=EB=94=94=EC=9D=98=20accessToken=20null=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=20=ED=95=B4=EA=B2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/api/member/controller/MemberApiController.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/controller/MemberApiController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/controller/MemberApiController.java index f81cbc1..a857618 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/controller/MemberApiController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/member/controller/MemberApiController.java @@ -24,6 +24,7 @@ public class MemberApiController { @PostMapping("/login") public ResponseEntity login(@RequestBody LoginDto loginDto) { + log.info("로그인"); // 입력 데이터 유효성 검증 if(loginDto.isNotValid()) { return Ut.spring.responseEntityOf(RsData.of("F-1", "로그인 정보가 올바르지 않습니다..")); @@ -32,11 +33,13 @@ public ResponseEntity login(@RequestBody LoginDto loginDto) { Member member = memberService.findByUsername(loginDto.getUsername()); // 1. 존재하지 않는 회원 if(member == null) { + log.info("존재하지 않는 회원"); return Ut.spring.responseEntityOf(RsData.of("F-2", "일치하는 회원이 존재하지 않습니다.")); } // 2. 올바르지 않은 비밀번호 // matches(비밀번호 원문, 암호화된 비밀번호) if(!passwordEncoder.matches(loginDto.getPassword(), member.getPassword())) { + log.info("비밀번호 틀림"); return Ut.spring.responseEntityOf(RsData.of("F-3", "비밀번호가 일치하지 않습니다.")); } @@ -48,7 +51,7 @@ public ResponseEntity login(@RequestBody LoginDto loginDto) { RsData.of( "S-1", "로그인 성공, Access Token을 발급합니다.", - Ut.mapOf("Authentication", accessToken) + Ut.mapOf("accessToken", accessToken) ), Ut.spring.httpHeadersOf("Authentication", accessToken) ); From 50fe75fd31276b59527508f4494b4ccdfa72e16f Mon Sep 17 00:00:00 2001 From: ahah525 Date: Tue, 8 Nov 2022 23:04:16 +0900 Subject: [PATCH 28/39] =?UTF-8?q?#33=20-=20spring=20doc=20=EC=9D=98?= =?UTF-8?q?=EC=A1=B4=EC=84=B1=20=EC=B6=94=EA=B0=80,=20SpringDocConfig=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80,=20spring=20doc=20=EA=B4=80=EB=A6=AC?= =?UTF-8?q?=EC=9E=90=20=ED=9A=8C=EC=9B=90=EB=A7=8C=20=EC=A0=91=EA=B7=BC?= =?UTF-8?q?=EA=B0=80=EB=8A=A5=ED=95=98=EB=8F=84=EB=A1=9D=20security=20?= =?UTF-8?q?=EC=84=A4=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 4Week_Mission/mutbooks/build.gradle | 3 +++ .../mutbooks/app/base/SpringDocConfig.java | 23 +++++++++++++++++++ .../mutbooks/app/security/SecurityConfig.java | 9 ++++++++ 3 files changed, 35 insertions(+) create mode 100644 4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/SpringDocConfig.java diff --git a/4Week_Mission/mutbooks/build.gradle b/4Week_Mission/mutbooks/build.gradle index 0f94bc2..15ce448 100644 --- a/4Week_Mission/mutbooks/build.gradle +++ b/4Week_Mission/mutbooks/build.gradle @@ -61,6 +61,9 @@ dependencies { implementation 'io.jsonwebtoken:jjwt-api:0.11.5' runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' + + // spring doc + implementation 'org.springdoc:springdoc-openapi-ui:1.6.11' } tasks.named('test') { diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/SpringDocConfig.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/SpringDocConfig.java new file mode 100644 index 0000000..80273a5 --- /dev/null +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/base/SpringDocConfig.java @@ -0,0 +1,23 @@ +package com.example.mutbooks.app.base; + +import io.swagger.v3.oas.models.ExternalDocumentation; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.info.License; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SpringDocConfig { + @Bean + public OpenAPI springShopOpenAPI() { + return new OpenAPI() + .info(new Info().title("SpringShop API") + .description("Spring shop sample application") + .version("v0.0.1") + .license(new License().name("Apache 2.0").url("http://springdoc.org"))) + .externalDocs(new ExternalDocumentation() + .description("SpringShop Wiki Documentation") + .url("https://springshop.wiki.github.org/docs")); + } +} diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/SecurityConfig.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/SecurityConfig.java index b45ef7a..705ede8 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/SecurityConfig.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/SecurityConfig.java @@ -19,6 +19,7 @@ public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http + .httpBasic().disable() .formLogin( formLogin -> formLogin .loginPage("/member/login") // GET @@ -26,6 +27,14 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // .successHandler(authenticationSuccessHandler) // .failureHandler(authenticationFailureHandler) ) + .authorizeRequests( + authorizeRequests -> authorizeRequests + // spring doc 관리자 회원만 허용 + .antMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html") + .hasAuthority("ADMIN") + .anyRequest() + .permitAll() + ) .logout( logout -> logout.logoutUrl("/member/logout") // 로그아웃 후 기본 이동경로 = /login?logout From cc25bf40409d65e1c55cf7260ef7670be5d0bf61 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Wed, 9 Nov 2022 15:02:02 +0900 Subject: [PATCH 29/39] =?UTF-8?q?#31=20-=20Docs:=204Week=5FRecord=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...k_\355\225\234\354\212\271\354\227\260.md" | 228 +++++++++++++++++- 1 file changed, 225 insertions(+), 3 deletions(-) diff --git "a/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" "b/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" index 1d7151b..bb261e8 100644 --- "a/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" +++ "b/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" @@ -1,18 +1,240 @@ ## 4Week_Mission +*표시: 개인적으로 추가한 기능 + +### ⭐️ 3Week 추가과제 ⭐️ +- [x] withdrawApply 엔티티 설계 +- [x] MemberExtra 엔티티 설계 + - 회원의 출금 계좌 정보(은행명, 계좌번호) 관리 목적 +- [x] 출금 신청 + - POST /withdraw/apply + - Form: price +- [x] 출금 신청 내역 리스트(사용자 기능)* + - GET /withdraw/applyList +- [x] 출금 신청 내역 리스트(관리자 기능) + - GET /adm/withdraw/applyList +- [x] 출금 처리 + - POST /adm/withdraw/{withdrawApplyId} +- [x] 출금 취소(사용자 기능)* + - POST /withdraw/cancel/{withdrawApplyId} +- [x] 출금 취소(관리자 기능)* + - POST /adm/withdraw/cancel/{withdrawApplyId} ### ⭐️ 4Week 필수과제 ⭐️ +- [x] JWT 로그인 구현(POST /api/v1/member/login) +- [x] 로그인 한 회원의 정보 구현(GET /api/v1/member/me) + - [x] MemberDto 추가 +- [x] 내 도서 리스트 구현(GET /api/v1/myBooks) + - [x] MyBookDto 추가 + - [x] ProductDto 추가 +- [x] 내 도서 상세정보 구현(GET /api/v1/myBooks/{myBookId}) + - [x] MyBookDetailDto 추가 + - [x] ProductDetailDto 추가 + - [x] PostDetailDto 추가 +- [x] Srping Doc 으로 API 문서화(/swagger-ui/index.html ) + - [x] SpringDocConfig 추가 + - [x] 관리자 회원만 spring doc 접근가능하도록 SecurityConfig 설정 ### 👍🏻 4Week 추가과제 👍🏻 +- [x] ERD 완성* +- [ ] 엑세스 토큰 화이트리스트 구현(Member 엔티티에 accessToken 필드 추가) +- [x] 리액트 코드 작동 확인 ### 🙈 요구사항 및 접근방법 정리 🙈 +### JWT 프로세스 +1. 사용자가 `username, password` 를 입력하고 서버로 로그인 요청을 보낸다. +2. 로그인 성공시 서버는 비밀키로 서명을 하고 공개키로 암호화 하여 `Access Token` 을 발급한다. +3. `Authorization Header` 에 `Access Token` 을 담아 클라이언트에게 응답을 보낸다. +4. 클라이언트는 API를 요청할 때 `Authorization Header` 에 `Access Token` 을 담아 요청을 보낸다. +5. 서버에서는 `Access Token` 을 검증하고 사용자를 인증한다. +6. 서버가 요청에 대한 응답을 클라이언트에게 전달한다. +- https://velog.io/@junghyeonsu/%ED%94%84%EB%A1%A0%ED%8A%B8%EC%97%90%EC%84%9C-%EB%A1%9C%EA%B7%B8%EC%9D%B8%EC%9D%84-%EC%B2%98%EB%A6%AC%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95 +--- +### Spring Security + JWT 로그인 구현 +- https://samtao.tistory.com/65 -### ❗️ 특이사항 ❗️ +**1. JWT dependency 추가** +- `build.gradle` 파일에 jwt 구현을 위해 필요한 의존성을 추가한다. +```bash +implementation 'io.jsonwebtoken:jjwt-api:0.11.5' +runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' +runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' +``` +**2. JWT secretKey 관리** +- ``JwtConfig`` 는 JWT AccessToken 발급에 사용되는 비밀키를 싱글톤 빈으로 등록하여 관리한다. +```java +@Configuration +public class JwtConfig { + @Value("${custom.jwt.secretKey}") + private String secretKeyPlain; // 비밀키 원문 + + // JWT 비밀키 싱글톤 빈 관리 + @Bean + public SecretKey jwtSecretKey() { + String keyBase64Encoded = Base64.getEncoder().encodeToString(secretKeyPlain.getBytes()); + return Keys.hmacShaKeyFor(keyBase64Encoded.getBytes()); + } +} +``` +- secretKey(원문)은 ``application.yml`` 파일에서 관리한다. -아쉬웠던 점 +**3. JWT 토큰(AccessToken) 발급** +- ``JwtProvider`` 은 JWT 토큰을 발급하는 역할을 하고 비밀키를 이용해 토큰을 생성한다. +```java +// JWT Access Token 발급 +public String generateAccessToken(Map claims, int seconds) { + long now = new Date().getTime(); + Date accessTokenExpiresIn = new Date(now + 1000L * seconds); + + return Jwts.builder() + .claim("body", Ut.json.toStr(claims)) // Claims 정보 설정 + .setExpiration(accessTokenExpiresIn) // accessToken 만료 시간 설정 + .signWith(getSecretKey(), SignatureAlgorithm.HS512) // HS512, 비밀키로 서명 + .compact(); // 토큰 생성 +} +``` +1. `Jwts.builder()` 를 이용해 `JwtBuilder` 객체를 생성한다. +2. Headers, Claims, 토큰 용도, 토큰 만료 시간 등을 설정한다. +3. `HS512(서명 알고리즘), 비밀키` 로 서명한다. +4. `compact()` 로 토큰을 생성한다. +**4. JWT 토큰(AccessToken) 검증** +- ``JwtProvider`` 은 JWT 토큰을 검증하는 역할을 하고 공개키를 이용해 토큰을 검증한다. +```java +// JWT Access Token 검증 +public boolean verify(String accessToken) { + try { + Jwts.parserBuilder() + .setSigningKey(getSecretKey()) // 비밀키 + .build() + .parseClaimsJws(accessToken); // 파싱 및 검증(실패시 에러) + } catch (ExpiredJwtException e) { + // 토큰이 만료되었을 경우 + return false; + } + catch (Exception e) { + // 그 외 에러 + return false; + } + return true; +} +``` +1. ``Jwts.parserBuilder()`` 를 이용해 ``JwtParserBuilder`` 객체를 생성한다. +2. 서명 검증을 위한 비밀키를 지정한다. +3. `parseClaimsJws()` 로 파싱 및 서명 검증을 한다. (예외처리를 위해 try-catch) -궁금했던 점 +**5. JWT 토큰(AccessToken) 으로부터 Claim 정보 가져오기** +- ``JwtProvider`` 은 JWT 토큰으로부터 Claim 정보를 가져오는 역할을 한다. +```java +// accessToken 으로부터 Claim 정보 얻기 +public Map getClaims(String accessToken) { + String body = Jwts.parserBuilder() + .setSigningKey(getSecretKey()) + .build() + .parseClaimsJws(accessToken) + .getBody() + .get("body", String.class); + + return Ut.json.toMap(body); +} +``` +1~3. 위와 동일 +4. `getBody()` 로 claim 정보를 가져온다. + +**6. REST API 요청 Security 설정** +- REST API 요청이 들어왔을 때는 JWT 방식으로 인증을 수행해야하므로 `ApiSecurityConfig` 에 관련 설정을 추가한다. +```java + @Bean + public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception { + http + ... + .authorizeRequests( + authorizeRequests -> authorizeRequests + // 로그인 요청 외 모든 요청은 로그인 필수 + .antMatchers("/api/*/member/login").permitAll() + .anyRequest() + .authenticated() // 최소자격 : 로그인 + ) + .sessionManagement(sessionManagement -> sessionManagement + .sessionCreationPolicy(STATELESS) + ) + .addFilterBefore( + jwtAuthorizationFilter, + UsernamePasswordAuthenticationFilter.class + ) + ... + return http.build(); + } +``` +- `/api/*/member/login` 요청 외 모든 `/api/**` 요청은 인증된 사용자여야 한다. +- 지정된 필터보다 먼저 실행되도록 `jwtAuthorizationFilter` (커스텀 필터) 를 추가한다. + +**7. jwtAuthorizationFilter 추가** +- REST API 요청이 Controller 에 도달하기 이전에 앞 단(Filter 혹은 Interceptor)에서 인증/인가를 수행한다. +```java +@Slf4j +@Component +@RequiredArgsConstructor +public class JwtAuthorizationFilter extends OncePerRequestFilter { + private final JwtProvider jwtProvider; + private final MemberService memberService; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + String barerToken = request.getHeader("Authorization"); + // 토큰 유효성 검증 + if(barerToken != null) { + String token = barerToken.substring("Barer ".length()); + // 토큰이 유효하면 회원 정보 얻어서 강제 로그인 처리 + if(jwtProvider.verify(token)) { + Map claims = jwtProvider.getClaims(token); + String username = (String) claims.get("username"); + Member member = memberService.findByUsername(username); + + if(member != null) { + forceAuthentication(member); + } + } + } + filterChain.doFilter(request, response); + } + + // 강제 로그인 처리 + private void forceAuthentication(Member member) { + MemberContext memberContext = new MemberContext(member); + + UsernamePasswordAuthenticationToken authentication = + UsernamePasswordAuthenticationToken.authenticated( + memberContext, + null, member.getAuthorities() + ); + + // 이후 컨트롤러 단에서 MemberContext 객체 사용O + SecurityContext context = SecurityContextHolder.createEmptyContext(); + context.setAuthentication(authentication); + SecurityContextHolder.setContext(context); + } +} +``` +1. 요청 헤더의 `Access Token` 을 검증한다. +2. 토큰으로부터 `claim(회원 정보)` 를 얻어 DB에서 Member 객체 조회한다. +3. 해당 회원 강제 로그인 처리한다.(`MemberContext` 세션 등록) +--- +### Spring Doc API 문서화 +1. spring doc dependency 추가(build.gradle) +```bash +implementation 'org.springdoc:springdoc-openapi-ui:1.6.11' +``` +2. SpringDocConfig 추가 + +--- +궁금했던 점 +- api 패키지 위치 어디에 해야하는가? +- AuthLevel 같은 enum 클래스는 어느 패키지의 하위에 생성해야는가? Refactoring +- 토스 카드 결제 환불 처리 구현 +- 관리자 회원으로 로그인하면 관리자 회원 메인페이지로 리다이렉트하기 +- 장바구니 단건 삭제에서는 productId 를 넘기고 선택 삭제에서는 cartItemId 를 넘기는 부분을 모두 cartItemId를 넘기도록 통일 +- 금액 콤마 표시(프론트) From 7b5090d88d164aa810916ac2da876f8a7125a814 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Wed, 9 Nov 2022 15:21:06 +0900 Subject: [PATCH 30/39] =?UTF-8?q?#31=20-=20Docs:=204Week=5FRecord=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...k_\355\225\234\354\212\271\354\227\260.md" | 41 +++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git "a/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" "b/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" index bb261e8..bf76938 100644 --- "a/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" +++ "b/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" @@ -33,11 +33,46 @@ - [x] Srping Doc 으로 API 문서화(/swagger-ui/index.html ) - [x] SpringDocConfig 추가 - [x] 관리자 회원만 spring doc 접근가능하도록 SecurityConfig 설정 - + ### 👍🏻 4Week 추가과제 👍🏻 - [x] ERD 완성* +
+ ERD 설계 +
+ +
+
+ - [ ] 엑세스 토큰 화이트리스트 구현(Member 엔티티에 accessToken 필드 추가) - [x] 리액트 코드 작동 확인 +
+ 로그인 성공 메인화면 +
+ 스크린샷 2022-11-08 오후 10 56 03 +
+
+ +
+ 회원 정보 +
+ 스크린샷 2022-11-08 오후 10 57 45 +
+
+ +
+ 내 도서 리스트 +
+ 스크린샷 2022-11-08 오후 10 58 35 +
+
+ +
+ 내 도서 상세정보 +
+ 스크린샷 2022-11-08 오후 10 58 54 +
+
+ ### 🙈 요구사항 및 접근방법 정리 🙈 ### JWT 프로세스 @@ -47,11 +82,11 @@ 4. 클라이언트는 API를 요청할 때 `Authorization Header` 에 `Access Token` 을 담아 요청을 보낸다. 5. 서버에서는 `Access Token` 을 검증하고 사용자를 인증한다. 6. 서버가 요청에 대한 응답을 클라이언트에게 전달한다. -- https://velog.io/@junghyeonsu/%ED%94%84%EB%A1%A0%ED%8A%B8%EC%97%90%EC%84%9C-%EB%A1%9C%EA%B7%B8%EC%9D%B8%EC%9D%84-%EC%B2%98%EB%A6%AC%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95 +[참고](https://velog.io/@junghyeonsu/%ED%94%84%EB%A1%A0%ED%8A%B8%EC%97%90%EC%84%9C-%EB%A1%9C%EA%B7%B8%EC%9D%B8%EC%9D%84-%EC%B2%98%EB%A6%AC%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95) --- ### Spring Security + JWT 로그인 구현 -- https://samtao.tistory.com/65 +[참고](https://samtao.tistory.com/65) **1. JWT dependency 추가** - `build.gradle` 파일에 jwt 구현을 위해 필요한 의존성을 추가한다. From 9ea8927a882f360b05f8a15fb66a2c90a36a7b6d Mon Sep 17 00:00:00 2001 From: ahah525 Date: Wed, 9 Nov 2022 17:20:14 +0900 Subject: [PATCH 31/39] =?UTF-8?q?#37=20-=20Feat:=20JWT=20AccessToken=20?= =?UTF-8?q?=ED=99=94=EC=9D=B4=ED=8A=B8=20=EB=A6=AC=EC=8A=A4=ED=8A=B8=20?= =?UTF-8?q?=EB=B0=A9=EC=8B=9D=20=EC=A0=81=EC=9A=A9(2=EC=B0=A8=20=ED=99=94?= =?UTF-8?q?=EC=9D=B4=ED=8A=B8=EB=A6=AC=EC=8A=A4=ED=8A=B8=20=EA=B2=80?= =?UTF-8?q?=EC=A6=9D)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mutbooks/app/member/entity/Member.java | 4 ++++ .../app/member/service/MemberService.java | 21 ++++++++++++++++--- .../filter/JwtAuthorizationFilter.java | 9 +++++--- .../app/security/jwt/JwtProvider.java | 2 +- 4 files changed, 29 insertions(+), 7 deletions(-) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java index f5a3f37..a2ea20e 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java @@ -35,6 +35,10 @@ public class Member extends BaseEntity { private int restCash; // 예치금 + // accessToken + @Column(columnDefinition = "TEXT") + private String accessToken; + // Member 의 memberExtra 에 값이 저장될 때, MemberExtra 도 같이 저장되도록 @OneToOne(mappedBy = "member", cascade = CascadeType.ALL) private MemberExtra memberExtra; diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java index 0cbbfa5..92c99b0 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java @@ -1,6 +1,5 @@ package com.example.mutbooks.app.member.service; -import com.example.mutbooks.app.security.dto.MemberContext; import com.example.mutbooks.app.cash.entity.CashLog; import com.example.mutbooks.app.cash.service.CashService; import com.example.mutbooks.app.mail.service.MailService; @@ -13,6 +12,7 @@ import com.example.mutbooks.app.member.form.PwdModifyForm; import com.example.mutbooks.app.member.form.WithdrawAccountForm; import com.example.mutbooks.app.member.repository.MemberRepository; +import com.example.mutbooks.app.security.dto.MemberContext; import com.example.mutbooks.app.security.jwt.JwtProvider; import lombok.RequiredArgsConstructor; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -21,6 +21,7 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; import java.util.Map; import java.util.UUID; @@ -161,10 +162,24 @@ public void createBankInfo(Member member, WithdrawAccountForm withDrawAccountFor //forceAuthentication(member); } + // AccessToken 발급(발급된게 있으면 바로 리턴) + @Transactional public String genAccessToken(Member member) { - Map claims = member.getAccessTokenClaims(); - String accessToken = jwtProvider.generateAccessToken(claims, 60 * 60 * 24 * 90); // 유효기간 90일 + // 1. DB에서 AccessToken 조회 + String accessToken = member.getAccessToken(); + // 2. 만료시, 토큰 새로 발급 + if (StringUtils.hasLength(accessToken) == false) { + // 지금으로부터 100년간의 유효기간을 가지는 토큰을 생성, DB에 토큰 저장 + Map claims = member.getAccessTokenClaims(); + accessToken = jwtProvider.generateAccessToken(claims, 60L * 60 * 24 * 365 * 100); + member.setAccessToken(accessToken); + } return accessToken; } + + // 해당 토큰이 화이트 리스트에 있는지 검증 + public boolean verifyWithWhiteList(Member member, String token) { + return member.getAccessToken().equals(token); + } } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java index 8c8bf12..314fd21 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java @@ -35,16 +35,19 @@ public class JwtAuthorizationFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String barerToken = request.getHeader("Authorization"); - // 토큰 유효성 검증 + // 1. 1차 체크(정보가 변조되지 않았는지 검증) if(barerToken != null) { - String token = barerToken.substring("Barer ".length()); + // accessToken에서 회원 정보 가져오려면 Authentication에서 Bearer 제거 필요 + String token = barerToken.substring("Bearer ".length()); // 토큰이 유효하면 회원 정보 얻어서 강제 로그인 처리 if(jwtProvider.verify(token)) { Map claims = jwtProvider.getClaims(token); String username = (String) claims.get("username"); Member member = memberService.findByUsername(username); - if(member != null) { + // 2. 2차 체크(해당 엑세스 토큰이 화이트 리스트에 포함되는지 검증) + if (memberService.verifyWithWhiteList(member, token)) { + // 강제 로그인 처리 forceAuthentication(member); } } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java index c43c710..e5d9b2f 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java @@ -25,7 +25,7 @@ private SecretKey getSecretKey() { } // JWT Access Token 발급 - public String generateAccessToken(Map claims, int seconds) { + public String generateAccessToken(Map claims, long seconds) { long now = new Date().getTime(); Date accessTokenExpiresIn = new Date(now + 1000L * seconds); From 30980c6a4ea900bf097da4af0622c8bc8b237463 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Wed, 9 Nov 2022 17:24:55 +0900 Subject: [PATCH 32/39] =?UTF-8?q?#31=20-=20Docs:=204Week=5FRecord=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...k_\355\225\234\354\212\271\354\227\260.md" | 94 ++++++++++--------- 1 file changed, 49 insertions(+), 45 deletions(-) diff --git "a/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" "b/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" index bf76938..6ca8044 100644 --- "a/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" +++ "b/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" @@ -43,7 +43,7 @@ -- [ ] 엑세스 토큰 화이트리스트 구현(Member 엔티티에 accessToken 필드 추가) +- [x] 엑세스 토큰 화이트리스트 구현(Member 엔티티에 accessToken 필드 추가) - [x] 리액트 코드 작동 확인
로그인 성공 메인화면 @@ -208,53 +208,57 @@ public Map getClaims(String accessToken) { **7. jwtAuthorizationFilter 추가** - REST API 요청이 Controller 에 도달하기 이전에 앞 단(Filter 혹은 Interceptor)에서 인증/인가를 수행한다. ```java -@Slf4j -@Component -@RequiredArgsConstructor -public class JwtAuthorizationFilter extends OncePerRequestFilter { - private final JwtProvider jwtProvider; - private final MemberService memberService; - - @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - String barerToken = request.getHeader("Authorization"); - // 토큰 유효성 검증 - if(barerToken != null) { - String token = barerToken.substring("Barer ".length()); - // 토큰이 유효하면 회원 정보 얻어서 강제 로그인 처리 - if(jwtProvider.verify(token)) { - Map claims = jwtProvider.getClaims(token); - String username = (String) claims.get("username"); - Member member = memberService.findByUsername(username); - - if(member != null) { - forceAuthentication(member); - } - } - } - filterChain.doFilter(request, response); - } - - // 강제 로그인 처리 - private void forceAuthentication(Member member) { - MemberContext memberContext = new MemberContext(member); - - UsernamePasswordAuthenticationToken authentication = - UsernamePasswordAuthenticationToken.authenticated( - memberContext, - null, member.getAuthorities() - ); - - // 이후 컨트롤러 단에서 MemberContext 객체 사용O - SecurityContext context = SecurityContextHolder.createEmptyContext(); - context.setAuthentication(authentication); - SecurityContextHolder.setContext(context); - } -} +@Slf4j +@Component +@RequiredArgsConstructor +public class JwtAuthorizationFilter extends OncePerRequestFilter { + private final JwtProvider jwtProvider; + private final MemberService memberService; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + String barerToken = request.getHeader("Authorization"); + // 1. 1차 체크(정보가 변조되지 않았는지 검증) + if(barerToken != null) { + // accessToken에서 회원 정보 가져오려면 Authentication에서 Bearer 제거 필요 + String token = barerToken.substring("Bearer ".length()); + // 토큰이 유효하면 회원 정보 얻어서 강제 로그인 처리 + if(jwtProvider.verify(token)) { + Map claims = jwtProvider.getClaims(token); + String username = (String) claims.get("username"); + Member member = memberService.findByUsername(username); + + // 2. 2차 체크(해당 엑세스 토큰이 화이트 리스트에 포함되는지 검증) + if (memberService.verifyWithWhiteList(member, token)) { + // 강제 로그인 처리 + forceAuthentication(member); + } + } + } + filterChain.doFilter(request, response); + } + + // 강제 로그인 처리 + private void forceAuthentication(Member member) { + MemberContext memberContext = new MemberContext(member); + + UsernamePasswordAuthenticationToken authentication = + UsernamePasswordAuthenticationToken.authenticated( + memberContext, + null, + member.getAuthorities() + ); + + // 이후 컨트롤러 단에서 MemberContext 객체 사용O + SecurityContext context = SecurityContextHolder.createEmptyContext(); + context.setAuthentication(authentication); + SecurityContextHolder.setContext(context); + } ``` 1. 요청 헤더의 `Access Token` 을 검증한다. 2. 토큰으로부터 `claim(회원 정보)` 를 얻어 DB에서 Member 객체 조회한다. -3. 해당 회원 강제 로그인 처리한다.(`MemberContext` 세션 등록) +3. 해당 AccessToken 이 화이트 리스트에 포함되는지 검증한다. +4. 해당 회원 강제 로그인 처리한다.(`MemberContext` 세션 등록) --- ### Spring Doc API 문서화 1. spring doc dependency 추가(build.gradle) From 67d55ee44e7495ab294eb9bce8319cb75d6e3359 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Thu, 10 Nov 2022 13:47:39 +0900 Subject: [PATCH 33/39] =?UTF-8?q?#39=20-=20Fix:=20=EC=83=81=ED=92=88?= =?UTF-8?q?=EA=B3=BC=20=EA=B4=80=EB=A0=A8=EB=90=9C=20=EA=B8=80=EC=9D=84=20?= =?UTF-8?q?=EC=A1=B0=ED=9A=8C=ED=95=A0=20=EB=95=8C=20=ED=95=B4=EB=8B=B9=20?= =?UTF-8?q?=ED=82=A4=EC=9B=8C=EB=93=9C=EC=99=80=20=EA=B4=80=EB=A0=A8?= =?UTF-8?q?=EB=90=9C=20=EB=8B=A4=EB=A5=B8=20=EC=9E=91=EA=B0=80=EC=9D=98=20?= =?UTF-8?q?=EA=B8=80=EA=B9=8C=EC=A7=80=20=EC=A1=B0=ED=9A=8C=EB=90=98?= =?UTF-8?q?=EB=8A=94=20=EB=AC=B8=EC=A0=9C=20=ED=95=B4=EA=B2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../example/mutbooks/app/mybook/service/MyBookService.java | 5 ++++- .../app/postHashTag/repository/PostHashTagRepository.java | 3 ++- .../app/postHashTag/service/PostHashTagService.java | 7 ++++--- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java index 0dc4001..c51a24c 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java @@ -83,7 +83,10 @@ public MyBookDetailDto findByIdForDetail(long id) { MyBook myBook = findById(id); PostKeyword postKeyword = myBook.getProduct().getPostKeyword(); - List postHashTags = postHashTagService.findByPostKeyword(postKeyword); + Member author = myBook.getProduct().getAuthor(); + + // 해당 작가, 키워드와 관련된 글만 조회 + List postHashTags = postHashTagService.findByPostKeywordAndMember(postKeyword, author); List posts = postHashTags.stream() .map(postHashTag -> postHashTag.getPost()) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/repository/PostHashTagRepository.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/repository/PostHashTagRepository.java index b9622aa..2cc63ae 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/repository/PostHashTagRepository.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/repository/PostHashTagRepository.java @@ -1,5 +1,6 @@ package com.example.mutbooks.app.postHashTag.repository; +import com.example.mutbooks.app.member.entity.Member; import com.example.mutbooks.app.postHashTag.entity.PostHashTag; import com.example.mutbooks.app.postKeyword.entity.PostKeyword; import org.springframework.data.jpa.repository.JpaRepository; @@ -12,5 +13,5 @@ public interface PostHashTagRepository extends JpaRepository List findByPostId(Long postId); - List findByPostKeyword(PostKeyword postKeyword); + List findByPostKeywordAndMember(PostKeyword postKeyword, Member member); } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/service/PostHashTagService.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/service/PostHashTagService.java index cca6459..978eefd 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/service/PostHashTagService.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/service/PostHashTagService.java @@ -1,10 +1,11 @@ package com.example.mutbooks.app.postHashTag.service; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.post.entity.Post; import com.example.mutbooks.app.postHashTag.entity.PostHashTag; import com.example.mutbooks.app.postHashTag.repository.PostHashTagRepository; import com.example.mutbooks.app.postKeyword.entity.PostKeyword; import com.example.mutbooks.app.postKeyword.service.PostKeywordService; -import com.example.mutbooks.app.post.entity.Post; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @@ -78,7 +79,7 @@ public List findByPostId(long postId) { return postHashTagRepository.findByPostId(postId); } - public List findByPostKeyword(PostKeyword postKeyword) { - return postHashTagRepository.findByPostKeyword(postKeyword); + public List findByPostKeywordAndMember(PostKeyword postKeyword, Member member) { + return postHashTagRepository.findByPostKeywordAndMember(postKeyword, member); } } From ad7198d10609e7771a0548ee61ce39aee9307f4d Mon Sep 17 00:00:00 2001 From: ahah525 Date: Thu, 10 Nov 2022 19:18:39 +0900 Subject: [PATCH 34/39] =?UTF-8?q?#39=20-=20Fix:=20=EB=82=B4=EB=8F=84?= =?UTF-8?q?=EC=84=9C=EB=A7=8C=20=EC=83=81=EC=84=B8=20=EC=A0=95=EB=B3=B4?= =?UTF-8?q?=EC=A1=B0=ED=9A=8C=20=EA=B0=80=EB=8A=A5=ED=95=98=EB=8F=84?= =?UTF-8?q?=EB=A1=9D=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/api/myBooks/MyBooksApiController.java | 2 +- .../app/mybook/repository/MyBookRepository.java | 2 ++ .../mutbooks/app/mybook/service/MyBookService.java | 12 ++++++------ 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java index daa731f..07207bb 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java @@ -37,7 +37,7 @@ public ResponseEntity list(@AuthenticationPrincipal MemberContext member // 도서 상세 조회 @GetMapping("/{myBookId}") public ResponseEntity detail(@PathVariable long myBookId, @AuthenticationPrincipal MemberContext memberContext) { - MyBookDetailDto myBookDetailDto = myBookService.findByIdForDetail(myBookId); + MyBookDetailDto myBookDetailDto = myBookService.findByIdForDetail(myBookId, memberContext.getId()); return Ut.spring.responseEntityOf( RsData.successOf(Ut.mapOf("myBook", myBookDetailDto)) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/repository/MyBookRepository.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/repository/MyBookRepository.java index 5be2108..3d90f54 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/repository/MyBookRepository.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/repository/MyBookRepository.java @@ -13,4 +13,6 @@ public interface MyBookRepository extends JpaRepository { void deleteByProductIdAndOwnerId(Long productId, Long ownerId); List findByOwner(Member owner); + + Optional findByIdAndOwnerId(long myBookId, long ownerId); } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java index c51a24c..22feec4 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java @@ -73,14 +73,15 @@ public List findAllByOwner(Member owner) { return myBookDtos; } - public MyBook findById(long id) { - return myBookRepository.findById(id).orElseThrow(() -> { - throw new MyBookNotFoundException(""); + public MyBook findByIdAndOwnerId(long myBookId, long ownerId) { + return myBookRepository.findByIdAndOwnerId(myBookId, ownerId).orElseThrow(() -> { + throw new MyBookNotFoundException("해당 상품 구매 이력이 존재하지 않습니다."); }); } - public MyBookDetailDto findByIdForDetail(long id) { - MyBook myBook = findById(id); + public MyBookDetailDto findByIdForDetail(long myBookId, long ownerId) { + // 본인이 소유한 도서로 조회 + MyBook myBook = findByIdAndOwnerId(myBookId, ownerId); PostKeyword postKeyword = myBook.getProduct().getPostKeyword(); Member author = myBook.getProduct().getAuthor(); @@ -92,7 +93,6 @@ public MyBookDetailDto findByIdForDetail(long id) { .map(postHashTag -> postHashTag.getPost()) .collect(Collectors.toList()); - // 본인이 소유한 도서인지 검증 return MyBookDetailDto.toDto(myBook, posts); } } From b6b10400fce7f4dc7a5be4025d11e2797c1854ee Mon Sep 17 00:00:00 2001 From: ahah525 Date: Thu, 10 Nov 2022 21:27:25 +0900 Subject: [PATCH 35/39] =?UTF-8?q?#40=20-=20Refactor:=20jwt=20=EA=B4=80?= =?UTF-8?q?=EB=A0=A8=20=EC=BD=94=EB=93=9C=20=EB=A6=AC=ED=8C=A9=ED=86=A0?= =?UTF-8?q?=EB=A7=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/member/service/MemberService.java | 2 +- .../app/security/ApiSecurityConfig.java | 18 +++++++++++------- .../filter/JwtAuthorizationFilter.java | 8 ++++---- .../mutbooks/app/security/jwt/JwtProvider.java | 5 +++-- 4 files changed, 19 insertions(+), 14 deletions(-) diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java index 92c99b0..955b536 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java @@ -171,7 +171,7 @@ public String genAccessToken(Member member) { if (StringUtils.hasLength(accessToken) == false) { // 지금으로부터 100년간의 유효기간을 가지는 토큰을 생성, DB에 토큰 저장 Map claims = member.getAccessTokenClaims(); - accessToken = jwtProvider.generateAccessToken(claims, 60L * 60 * 24 * 365 * 100); + accessToken = jwtProvider.generateAccessToken(claims); member.setAccessToken(accessToken); } diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/ApiSecurityConfig.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/ApiSecurityConfig.java index 2b4cc78..9c1dc08 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/ApiSecurityConfig.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/ApiSecurityConfig.java @@ -26,8 +26,14 @@ public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception { // .exceptionHandling(exceptionHandling -> exceptionHandling // .authenticationEntryPoint(authenticationEntryPoint) // ) + // jwt 사용 기본 설정 .httpBasic().disable() + .formLogin().disable() .csrf().disable() + .sessionManagement(sessionManagement -> sessionManagement + .sessionCreationPolicy(STATELESS) + ) + // cors 허용 설정 .cors(cors -> cors .configurationSource(corsConfigurationSource()) ) @@ -38,10 +44,7 @@ public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception { .anyRequest() .authenticated() // 최소자격 : 로그인 ) - .sessionManagement(sessionManagement -> sessionManagement - .sessionCreationPolicy(STATELESS) - ) - .formLogin().disable() + // 필터 설정 .addFilterBefore( jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class @@ -51,13 +54,14 @@ public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception { return http.build(); } + // cors 허용 정책 설정 @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration corsConfiguration = new CorsConfiguration(); - corsConfiguration.addAllowedOrigin("*"); - corsConfiguration.addAllowedHeader("*"); - corsConfiguration.addAllowedMethod("*"); + corsConfiguration.addAllowedOrigin("*"); // 모든 URL 허용 + corsConfiguration.addAllowedHeader("*"); // 모든 Header 허용 + corsConfiguration.addAllowedMethod("*"); // 모든 HTTP METHOD 허용 UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); urlBasedCorsConfigurationSource.registerCorsConfiguration("/api/**", corsConfiguration); diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java index 314fd21..c6e4a05 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java @@ -34,11 +34,11 @@ public class JwtAuthorizationFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - String barerToken = request.getHeader("Authorization"); + String bearerToken = request.getHeader("Authorization"); // 1. 1차 체크(정보가 변조되지 않았는지 검증) - if(barerToken != null) { - // accessToken에서 회원 정보 가져오려면 Authentication에서 Bearer 제거 필요 - String token = barerToken.substring("Bearer ".length()); + if(bearerToken != null) { + // accessToken 에서 회원 정보 가져오려면 Authorization 에서 Bearer 제거 필요 + String token = bearerToken.split(" ")[1]; // 토큰이 유효하면 회원 정보 얻어서 강제 로그인 처리 if(jwtProvider.verify(token)) { Map claims = jwtProvider.getClaims(token); diff --git a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java index e5d9b2f..cc802cf 100644 --- a/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java +++ b/4Week_Mission/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java @@ -19,15 +19,16 @@ @RequiredArgsConstructor public class JwtProvider { private final SecretKey jwtSecretKey; // 비밀키 + private long ACCESS_TOKEN_VALIDATION_SECOND = 60 * 60 * 24 * 365 * 100L; // accessToken 유효시간(100년) private SecretKey getSecretKey() { return jwtSecretKey; } // JWT Access Token 발급 - public String generateAccessToken(Map claims, long seconds) { + public String generateAccessToken(Map claims) { long now = new Date().getTime(); - Date accessTokenExpiresIn = new Date(now + 1000L * seconds); + Date accessTokenExpiresIn = new Date(now + 1000L * ACCESS_TOKEN_VALIDATION_SECOND); return Jwts.builder() .claim("body", Ut.json.toStr(claims)) // Claims 정보 설정 From 1ccb91fa164476427a9bd7f50f0ed4ae6fef3c37 Mon Sep 17 00:00:00 2001 From: ahah525 Date: Thu, 10 Nov 2022 21:28:39 +0900 Subject: [PATCH 36/39] =?UTF-8?q?#31=20-=20Docs:=204Week=5FRecord=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...k_\355\225\234\354\212\271\354\227\260.md" | 179 +++++++++++------- 1 file changed, 112 insertions(+), 67 deletions(-) diff --git "a/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" "b/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" index 6ca8044..b3dad81 100644 --- "a/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" +++ "b/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" @@ -76,17 +76,18 @@ ### 🙈 요구사항 및 접근방법 정리 🙈 ### JWT 프로세스 + 1. 사용자가 `username, password` 를 입력하고 서버로 로그인 요청을 보낸다. 2. 로그인 성공시 서버는 비밀키로 서명을 하고 공개키로 암호화 하여 `Access Token` 을 발급한다. -3. `Authorization Header` 에 `Access Token` 을 담아 클라이언트에게 응답을 보낸다. +3. `응답 Header` 에 `Access Token` 을 담아 클라이언트에게 보낸다. 4. 클라이언트는 API를 요청할 때 `Authorization Header` 에 `Access Token` 을 담아 요청을 보낸다. 5. 서버에서는 `Access Token` 을 검증하고 사용자를 인증한다. 6. 서버가 요청에 대한 응답을 클라이언트에게 전달한다. -[참고](https://velog.io/@junghyeonsu/%ED%94%84%EB%A1%A0%ED%8A%B8%EC%97%90%EC%84%9C-%EB%A1%9C%EA%B7%B8%EC%9D%B8%EC%9D%84-%EC%B2%98%EB%A6%AC%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95) +- [JWT, 정확하게 무엇이고 왜 쓰이는 걸까?](https://velog.io/@junghyeonsu/%ED%94%84%EB%A1%A0%ED%8A%B8%EC%97%90%EC%84%9C-%EB%A1%9C%EA%B7%B8%EC%9D%B8%EC%9D%84-%EC%B2%98%EB%A6%AC%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95) --- ### Spring Security + JWT 로그인 구현 -[참고](https://samtao.tistory.com/65) +- [Java에서 JJWT(Java JSON Web Token)를 이용한 JWT(JSON Web Token) 사용방법](https://samtao.tistory.com/65) **1. JWT dependency 추가** - `build.gradle` 파일에 jwt 구현을 위해 필요한 의존성을 추가한다. @@ -96,7 +97,7 @@ runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' ``` **2. JWT secretKey 관리** -- ``JwtConfig`` 는 JWT AccessToken 발급에 사용되는 비밀키를 싱글톤 빈으로 등록하여 관리한다. +- ``JwtConfig`` 는 JWT AccessToken 발급에 사용되는 `secretKey` 를 싱글톤 빈으로 등록하여 관리한다. ```java @Configuration public class JwtConfig { @@ -114,12 +115,19 @@ public class JwtConfig { - secretKey(원문)은 ``application.yml`` 파일에서 관리한다. **3. JWT 토큰(AccessToken) 발급** -- ``JwtProvider`` 은 JWT 토큰을 발급하는 역할을 하고 비밀키를 이용해 토큰을 생성한다. +- `JwtProvider` 은 JWT 토큰을 발급하는 역할을 하고 `secretKey` 를 이용해 토큰을 생성한다. ```java +private final SecretKey jwtSecretKey; // 비밀키 +private long ACCESS_TOKEN_VALIDATION_SECOND = 60 * 60 * 24 * 365 * 100L; // accessToken 유효시간(100년) + +private SecretKey getSecretKey() { + return jwtSecretKey; +} + // JWT Access Token 발급 -public String generateAccessToken(Map claims, int seconds) { +public String generateAccessToken(Map claims) { long now = new Date().getTime(); - Date accessTokenExpiresIn = new Date(now + 1000L * seconds); + Date accessTokenExpiresIn = new Date(now + 1000L * ACCESS_TOKEN_VALIDATION_SECOND); return Jwts.builder() .claim("body", Ut.json.toStr(claims)) // Claims 정보 설정 @@ -160,6 +168,7 @@ public boolean verify(String accessToken) { **5. JWT 토큰(AccessToken) 으로부터 Claim 정보 가져오기** - ``JwtProvider`` 은 JWT 토큰으로부터 Claim 정보를 가져오는 역할을 한다. +- `JwtAuthorizationFilter` 에서 API 요청이 들어왔을 때 토큰을 검증하고 난 후, Claim 에서 얻은 username 으로 member 객체를 조회해 로그인 처리(세션값 강제 수정)을 하는데 사용된다. ```java // accessToken 으로부터 Claim 정보 얻기 public Map getClaims(String accessToken) { @@ -177,12 +186,24 @@ public Map getClaims(String accessToken) { 4. `getBody()` 로 claim 정보를 가져온다. **6. REST API 요청 Security 설정** -- REST API 요청이 들어왔을 때는 JWT 방식으로 인증을 수행해야하므로 `ApiSecurityConfig` 에 관련 설정을 추가한다. +- [Spring Security, JWT, 인증, 인가](https://hipopatamus.tistory.com/72) +- REST API 요청이 들어왔을 때는 JWT 방식으로 인증을 수행해야하므로 `ApiSecurityConfig` 에 관련 설정을 추가한다. ```java - @Bean + @Bean public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception { http - ... + .antMatcher("/api/**") + // jwt 사용 기본 설정 + .httpBasic().disable() + .formLogin().disable() + .csrf().disable() + .sessionManagement(sessionManagement -> sessionManagement + .sessionCreationPolicy(STATELESS) + ) + // cors 허용 설정 + .cors(cors -> cors + .configurationSource(corsConfigurationSource()) + ) .authorizeRequests( authorizeRequests -> authorizeRequests // 로그인 요청 외 모든 요청은 로그인 필수 @@ -190,74 +211,72 @@ public Map getClaims(String accessToken) { .anyRequest() .authenticated() // 최소자격 : 로그인 ) - .sessionManagement(sessionManagement -> sessionManagement - .sessionCreationPolicy(STATELESS) - ) - .addFilterBefore( + // 필터 설정 + .addFilterBefore( jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class ) - ... + .logout().disable(); + return http.build(); + } + + // cors 허용 정책 설정 + @Bean + public CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration corsConfiguration = new CorsConfiguration(); + + corsConfiguration.addAllowedOrigin("*"); // 모든 URL 허용 + corsConfiguration.addAllowedHeader("*"); // 모든 Header 허용 + corsConfiguration.addAllowedMethod("*"); // 모든 HTTP METHOD 허용 + + UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); + urlBasedCorsConfigurationSource.registerCorsConfiguration("/api/**", corsConfiguration); + return urlBasedCorsConfigurationSource; } ``` - +- jwt 방식 로그인을 위해 `formLogin.disable()` 설정을 해주어야 한다. +- 타도메인에서 API 호출을 하기 위해 `cors 허용` 설정을 해주어야 한다. - `/api/*/member/login` 요청 외 모든 `/api/**` 요청은 인증된 사용자여야 한다. - 지정된 필터보다 먼저 실행되도록 `jwtAuthorizationFilter` (커스텀 필터) 를 추가한다. **7. jwtAuthorizationFilter 추가** -- REST API 요청이 Controller 에 도달하기 이전에 앞 단(Filter 혹은 Interceptor)에서 인증/인가를 수행한다. +- REST API 요청이 Controller 에 도달하기 이전에 앞 단(Filter 혹은 Interceptor)에서 인증/인가를 수행한다. ```java -@Slf4j -@Component -@RequiredArgsConstructor -public class JwtAuthorizationFilter extends OncePerRequestFilter { - private final JwtProvider jwtProvider; - private final MemberService memberService; - - @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - String barerToken = request.getHeader("Authorization"); - // 1. 1차 체크(정보가 변조되지 않았는지 검증) - if(barerToken != null) { - // accessToken에서 회원 정보 가져오려면 Authentication에서 Bearer 제거 필요 - String token = barerToken.substring("Bearer ".length()); - // 토큰이 유효하면 회원 정보 얻어서 강제 로그인 처리 - if(jwtProvider.verify(token)) { - Map claims = jwtProvider.getClaims(token); - String username = (String) claims.get("username"); - Member member = memberService.findByUsername(username); - - // 2. 2차 체크(해당 엑세스 토큰이 화이트 리스트에 포함되는지 검증) - if (memberService.verifyWithWhiteList(member, token)) { - // 강제 로그인 처리 - forceAuthentication(member); - } - } - } - filterChain.doFilter(request, response); - } - - // 강제 로그인 처리 - private void forceAuthentication(Member member) { - MemberContext memberContext = new MemberContext(member); - - UsernamePasswordAuthenticationToken authentication = - UsernamePasswordAuthenticationToken.authenticated( - memberContext, - null, - member.getAuthorities() - ); - - // 이후 컨트롤러 단에서 MemberContext 객체 사용O - SecurityContext context = SecurityContextHolder.createEmptyContext(); - context.setAuthentication(authentication); - SecurityContextHolder.setContext(context); - } +@Slf4j +@Component +@RequiredArgsConstructor +public class JwtAuthorizationFilter extends OncePerRequestFilter { + private final JwtProvider jwtProvider; + private final MemberService memberService; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + String bearerToken = request.getHeader("Authorization"); + // 1. 1차 체크(정보가 변조되지 않았는지 검증) + if(bearerToken != null) { + // accessToken 에서 회원 정보 가져오려면 Authorization 에서 Bearer 제거 필요 + String token = bearerToken.split(" ")[1]; + // 토큰이 유효하면 회원 정보 얻어서 강제 로그인 처리 + if(jwtProvider.verify(token)) { + Map claims = jwtProvider.getClaims(token); + String username = (String) claims.get("username"); + Member member = memberService.findByUsername(username); + + // 2. 2차 체크(해당 엑세스 토큰이 화이트 리스트에 포함되는지 검증) + if (memberService.verifyWithWhiteList(member, token)) { + // 강제 로그인 처리 + forceAuthentication(member); + } + } + } + filterChain.doFilter(request, response); + } ``` 1. 요청 헤더의 `Access Token` 을 검증한다. 2. 토큰으로부터 `claim(회원 정보)` 를 얻어 DB에서 Member 객체 조회한다. -3. 해당 AccessToken 이 화이트 리스트에 포함되는지 검증한다. +3. 해당 `Access Token` 이 화이트 리스트에 포함되는지 검증한다. +- 최초에 발급된 accessToken 을 DB(Member 테이블)에 기록해두고 요청 헤더의 accessToken 과 일치하는지 비교한다. 4. 해당 회원 강제 로그인 처리한다.(`MemberContext` 세션 등록) --- ### Spring Doc API 문서화 @@ -266,11 +285,37 @@ public class JwtAuthorizationFilter extends OncePerRequestFilter { implementation 'org.springdoc:springdoc-openapi-ui:1.6.11' ``` 2. SpringDocConfig 추가 - +```java +@Configuration +public class SpringDocConfig { + @Bean + public OpenAPI springShopOpenAPI() { + return new OpenAPI() + .info(new Info().title("SpringShop API") + .description("Spring shop sample application") + .version("v0.0.1") + .license(new License().name("Apache 2.0").url("http://springdoc.org"))) + .externalDocs(new ExternalDocumentation() + .description("SpringShop Wiki Documentation") + .url("https://springshop.wiki.github.org/docs")); + } +} +``` +3. SecurityConfig 설정 추가 +```java +.authorizeRequests( + authorizeRequests -> authorizeRequests + // spring doc 관리자 회원만 허용 + .antMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html") + .hasAuthority("ADMIN") + .anyRequest() + .permitAll() +) +``` +- 관리자 회원만 접근하도록 설정한다. --- 궁금했던 점 -- api 패키지 위치 어디에 해야하는가? -- AuthLevel 같은 enum 클래스는 어느 패키지의 하위에 생성해야는가? +- AuthLevel 같은 enum 클래스는 어느 패키지에 위치해야하는가? (현재는 entity 패키지 내부에 entity 클래스와 같은 layer 에 위치함) Refactoring - 토스 카드 결제 환불 처리 구현 From 2b18a0a9f0700099ec1fd262a59a603ab4136550 Mon Sep 17 00:00:00 2001 From: HanSeungYeon <48237976+ahah525@users.noreply.github.com> Date: Fri, 11 Nov 2022 00:32:08 +0900 Subject: [PATCH 37/39] =?UTF-8?q?#31=20-=20Docs:=204Week=5FRecord=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- "4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" | 2 ++ 1 file changed, 2 insertions(+) diff --git "a/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" "b/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" index b3dad81..b3e345b 100644 --- "a/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" +++ "b/4Week_Record/4Week_\355\225\234\354\212\271\354\227\260.md" @@ -77,6 +77,7 @@ ### 🙈 요구사항 및 접근방법 정리 🙈 ### JWT 프로세스 + 1. 사용자가 `username, password` 를 입력하고 서버로 로그인 요청을 보낸다. 2. 로그인 성공시 서버는 비밀키로 서명을 하고 공개키로 암호화 하여 `Access Token` 을 발급한다. 3. `응답 Header` 에 `Access Token` 을 담아 클라이언트에게 보낸다. @@ -237,6 +238,7 @@ public Map getClaims(String accessToken) { ``` - jwt 방식 로그인을 위해 `formLogin.disable()` 설정을 해주어야 한다. - 타도메인에서 API 호출을 하기 위해 `cors 허용` 설정을 해주어야 한다. + - [cors 오류 해결](https://github.com/likelion-backendschool/FinalProject_JuMinJi_team7/pull/25) - `/api/*/member/login` 요청 외 모든 `/api/**` 요청은 인증된 사용자여야 한다. - 지정된 필터보다 먼저 실행되도록 `jwtAuthorizationFilter` (커스텀 필터) 를 추가한다. From 588b51bc96694cd1e126e8d26ed04bbf9b0ca978 Mon Sep 17 00:00:00 2001 From: HanSeungYeon <48237976+ahah525@users.noreply.github.com> Date: Thu, 17 Nov 2022 22:12:31 +0900 Subject: [PATCH 38/39] =?UTF-8?q?#41=20-=20Docs:=20README.md=20=EC=9E=91?= =?UTF-8?q?=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 364 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 362 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 639bec7..3abe028 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,362 @@ -# [멋쟁이 사자처럼 백엔드 스쿨 1기] 종합 프로젝트 "멋북스" -본 서비스는 eBook 마켓과 eBook리더로 이루어진 서비스입니다. +# MUT Books + + + +## 프로젝트 소개 + +- Mut Books 는 eBook 마켓과 eBook리더로 이루어진 서비스입니다. + + + +## 🕰개발 기간 + +- 22.10.17 ~ 22.11.11(4주) : 1차 프로젝트 개발 + +- 22.11.14 ~ 22.12.16(5주) : 1차 프로젝트 리팩토링 및 2차 프로젝트 개발(진행중) + + + +## 🛠Stack + +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +## ⚙️개발 환경 + +- Language: Java 17(JDK 17.0.3) + +- Build: Gradle + +- IDE: Intellij + +- Framework: SrpingBoot 2.7.4 + +- Database: MariaDB + +- ORM: JPA + + + +## Git Convention + +### Branch +|이름 |설명 | +|----------------|-------------------------------| +|`main` |배포용 메인 브랜치 | +|`devbranch` |배포 전 개발 브랜치 | + +### Commit +`#이슈번호 - Type : 내용` 형태로 커밋 메시지 작성 +|Type |설명 | +|----------------|-------------------------------| +|`Feat` |기능개발 | +|`Fix` |버그수정 | +|`Docs` |문서수정 | +|`Style` |스타일수정 (들여쓰기, 세미콜론 등) | +|`Refactor` |리팩토링 | +|`Test` |테스트 코드 | +|`Chore` |빌드, 패키지매니저 수정 (gitignore 등) | + + + + + + +## ERD 설계 + + + + +## 🔍Preview + + +## 🛠Features +### 회원 +- 회원가입 + - 가입 완료시 축하메일 발송 + - Gmail SMTP 메일 발송 + - 가입 완료시 자동 로그인 처리 ([참고](https://coding-nyan.tistory.com/122)) +- 로그인/로그아웃 + - Spring Security 사용 + - 로그인: `/member/login` + - 로그아웃: `/member/logout` +- 내 프로필 조회 + - 회원 기본정보 조회(아이디, 이메일, 작가명) +- 회원 기본정보 수정 + - 이메일, 작가명 수정 가능 + - 수정 완료 후, 세션값(MemberContext) 강제 수정 +- 비밀번호 변경 + - 현재 비밀번호, 새 비밀번호, 새 비밀번호 확인 입력폼 유효성 검증 +- 아이디 찾기 + - `이메일` 로 아이디 찾기 + - 결과 페이지에서 아이디 확인 가능 +- 비밀번호 찾기 + - `아이디 + 이메일` 로 비밀번호 찾기 + - 해당 계정의 이메일로 임시 비밀번호 발급 -> 발급된 임시 비밀번호로 계정 비밀번호 수정 처리(DB 반영) + - 임시 비밀번호: UUID 10자리 랜덤 + +### 글 +- 글 작성 + - Toast UI Editor 적용하여 내용 입력 + - 마크다운 원문, 렌더링 결과(HTML) 모두 DB에 저장([참고](http://forward.nhnent.com/hands-on-labs/toastui.editor-ext/05.html)) +- 글 리스트 조회 + - 번호, 제목, 해시태그, 작성자, 작성날짜, 수정날짜 표시 + - QueryDSL 이용 + 1. 내 글 모두 조회 + - 메뉴바 "내 글" 클릭 -> 1번 페이지로 이동 + 2. 해시태그(키워드)와 관련된 내 글 모두 조회 + - 1번 페이지의 게시글 "해시태그" 클릭 -> 2번 페이지로 이동 +- 글 상세조회 + - 제목, 내용, 해시태그 표시 + - Toast UI Viewer 적용하여 내용 출력 +- 글 수정 + - 제목, 내용, 해시태그 수정 가능 + - Toast UI Editor 적용하여 내용 입력 + - 수정 완료시 현재시간으로 수정날짜 변경 +- 글 삭제 + - 글 삭제시 관련 해시태그도 자동 삭제 처리 + +### 도서(상품) +- 도서 등록/수정/삭제 기능은 작가 회원만 이용O(수정/삭제는 본인만 가능) +- 도서 리스트/상세조회 기능은 모두 이용O + +---------- + +- 도서 등록 + - 글 해시태그를 선택하면 내 글 중 해당 해시태그가 붙은 모든 글을 자동으로 1개의 상품으로 등록 + - [폼] 상품명, 설명, 권장 판매가, 글 해시태그 키워드(id), 도서 해시태그 키워드 + - 설명 부분에 ToastUI Editor 적용X + - 글 해시태그 키워드는 1개만 선택 가능 + - 여러 개의 도서 해시태그 키워드 등록 가능 + - 해시태그 키워드 & 관련 게시글 개수 표시 + - QueryDSL 이용 + - 다른 엔티티의 여러 컬럼 값을 select 하기 때문에, List로 반환 불가 → PostKeywordDto를 정의해 List 반환([참고](https://wildeveloperetrain.tistory.com/94)) + - 등록 완료시 도서 상세 페이지로 리다이렉트 +- 도서 수정 + - 글 키워드 수정 X + - 상품명, 가격, 설명, 도서 해시태그 수정 O + - 수정 완료시 도서 상세페이지로 리다이렉트 +- 도서 상세조회 + - [UI] 상품 랜덤 이미지, 상품명, 작가명, 등록일자, 판매가, 설명, 도서 해시태그 키워드 표시 + - 랜덤 이미지 표시 Unsplash 사용([참고](https://wallel.com/unsplash-%EB%9E%9C%EB%8D%A4-%EC%9D%B4%EB%AF%B8%EC%A7%80-url-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0/)) + - 설명 부분에 ToastUI Editor Viwer 적용X + - [UI] 작가 본인에게만 수정, 삭제 버튼 표시 + - 미리보기 구현X +- 도서 리스트 + - [UI] 모든 상품 정보(상품 랜덤 이미지, 상품명, 등록 일자, 작가명, 판매가, 해시태그) 최신순 리스팅 + - 랜덤 이미지 표시 Unsplash 사용 + - 상품명 클릭시 해당 상품 상세조회 페이지로 이동 + - 장바구니 버튼 표시 +- 도서 삭제 + - 삭제 버튼 클릭시 confirm 창으로 삭제 여부를 한 번 더 체크 + - 삭제 완료시 상품 리스트로 리다이렉트 + +### 장바구니 +- 장바구니 기능은 로그인한 회원만 이용O + +---------- + +- 품목 리스트 + - 메뉴바의 장바구니 메뉴를 클릭해 장바구니 페이지로 이동 + - [UI] 상품 정보(상품 랜덤 이미지, 상품명, 작가명, 등록일자, 가격) 표시 + - 랜덤 이미지 표시 Unsplash 사용 + - 장바구니에 담긴 상품이 없을 때는 상품 없음 안내 문구 표시 + - [UI] 전체 선택 체크박스, 품목 개별 체크박스, 품목 삭제 개별 버튼, 주문하기 버튼 표시 + - Javascript 로 전체 선택 체크박스와 개별 체크박스 연동 + - 이미지 클릭시 해당 상품 상세조회 페이지로 이동 +- 품목 추가 + - 도서 목록 페이지의 각 상품의 장바구니 버튼을 클릭해 장바구니에 품목 추가 + - 회원은 같은 상품 1개만 장바구니에 추가 가능(계속 담아도 최대 수량 = 1개) + - 품목 추가 완료시 품목 리스트 페이지로 리다이렉트 +- 품목 삭제 + - 품목 삭제 버튼 클릭시 confirm 으로 확인 후 삭제 + - 품목 삭제 완료시 품목 리스트 페이지로 리다이렉트 + +### 주문/결제 +- 주문/결제 기능은 로그인한 회원만 이용O +- 주문 리스트/상세조회/취소/결제/환불 처리는 주문자 본인 것만 가능 +---------- +- 주문 생성 + - 장바구니 페이지에서 주문할 품목을 선택 → 주문하기 버튼을 클릭 → 주문 생성(단일 주문 미지원) + - 선택한 cartItemId 들을 String 으로 만들어 주문 생성 폼 발송 + - ‘,’ 기준으로 분리한 CartItemIds String[] → List 으로 변환([참고](https://velog.io/@jwkim/java-arraylist-array-type-conversion)) +- 주문 리스트 + - 회원 본인의 주문 내역 최신순 리스팅 + - [UI] 주문일자, 주문 상태, 주문 품목들 정보(상품 랜덤 이미지, 상품명, 가격) 표시 +- 주문 상세 + - [UI] 주문 상품 정보(상품 랜덤 이미지, 상품명, 가격), 주문 정보(회원 id, 총 상품수, 총 상품금액), 결제 정보(총 상품금액, 캐시 사용금액, pg 결제 금액), 환불 규정 표시 + - 접근 방식 2가지 + 1. 장바구니 페이지에서 주문하기 버튼 클릭 + 2. 주문내역 페이지에서 상세보기 버튼 클릭 + - 주문 완료 상태 + - [UI] 보유 예치금, 사용할 예치금 입력폼 표시 + - [UI] 주문 취소 버튼, 결제 하기 버튼 표시 + - 결제 완료 상태 + - [UI] 환불요청 버튼 표시 + - [UI] 표시 + - 취소 완료/환불 완료 상태 + - 정보 외에 아무것도 표시X +- 주문 취소 + - 주문 완료 상태일 때만 주문 취소 요청 가능 + - 해당 주문 건에 포함된 주문 품목 전체 취소 방식 지원 + - 취소 완료시 주문 내역 페이지로 리다이렉트 +- 결제 처리 + - 주문 상세페이지에서 결제 버튼 클릭시 결제 요청(주문 생성후 미결제상태일 때만 요청 가능, 취소/환불 시 요청 불가) + - Toss Payments 연동([참고](https://docs.tosspayments.com/guides/windows/card)) + - 3가지 결제 방식 지원(1과 2, 3 방식으로 처리) + - 예치금 전액 결제(PG 결제 skip) + - Toss Payments 카드 전액 결제(예치금 충전 기록 보존) + - 예치금 + Toss Payments 카드 결제(혼합 방식) +- 환불 처리 + - 주문 전체 환불 방식 지원(부분 환불 미지원) + - 환불 규정: 결제 완료 후 10분 이내 & 도서 열람 하지 않았을 경우(1개라도 환불 규정에 어긋나면 환불 불가) + - 3가지 환불 방식 지원(1과 2,3 방식으로 처리) + 1. 예치금 전액 환불 + 2. Toss Payments 카드 전액 환불(예치금 환불 기록 보존) + 3. 예치금 환불 + Toss Payments 카드 환불(혼합 방식) + - 환불 완료시 MyBook 에서 구매 상품 삭제 + + ### 관리자 + - username 이 admin 인 회원 1명을 관리자(authLevel 7)로 지정 +---------- +- 관리자 홈 + - 관리자 권한을 가진 회원만 관리자 페이지 접속 가능 + +### 정산 +- 정산 데이터 생성폼 + - select box 년, 월 선택 후 폼 전송([참고](https://jh91.tistory.com/entry/JS-select-box%EC%97%90-%EC%83%9D%EB%85%84%EC%9B%94%EC%9D%BC-%EC%83%9D%EC%84%B1%ED%95%98%EB%8A%94-%ED%95%A8%EC%88%98)) + - 정산데이터 생성, 조회 2가지 폼 전송 처리 +- 정산 데이터 생성 + + - 관리자가 월 단위로 정산 데이터 생성 + - 정산 데이터 생성 완료 후, 정산 데이터 리스트 페이지로 리다이렉트 + + 1. select box로 년/월을 선택 후 정산 데이터 수동 생성 + + 1. 현재 날짜가 선택한 년/월의 정산 데이터를 생성가능한 날짜인지 검증 + - 2022년 9월 정산 데이터는 2022년 10월 15일 새벽 4시 이후 생성 가능 + - LocalDateTime → String 으로 출력([참고](https://krksap.tistory.com/1158)) + 2. 정산 데이터를 생성할 날짜 범위 구하기 + - Calendar 를 이용해 해당 년, 월의 말일 구하기([참고](https://dpdpwl.tistory.com/111)) + - LocalDateTime 하루의 시작, 종료시각 구하기([참고](https://mamoruoppa.tistory.com/60)) + 3. 해당 날짜 범위의 주문 품목(OrderItem) 데이터 조회 + 4. 주문 품목 데이터(OrderItem) -> 정산 데이터(RebateOrderItem) 변환 + 5. 정산 데이터 생성 및 DB에 저장 + 2. Spring Batch + Scheduler 를 이용한 정산 데이터 자동 생성 + + - 참고 + - [Spring batch+Scheduler 구현 예제](https://dalgun.dev/blog/2019-10-30/spring-batch) + - ‣ + - [Spring-boot Scheduler](https://velog.io/@rivernine/Spring-boot-Scheduler#11-enable-scheduling) + - [cron 표현식](https://itworldyo.tistory.com/40) + + [Spring Batch 개념 정리](https://www.notion.so/Spring-Batch-9fe550049da34243a8d93f34b495a79c) + + - 매달 15일 오전 4시 0분 0초에 저번 달(1일~말일)의 정산 데이터를 생성하는 배치 실행 + - Spring Batch + 1. spring-batch 의존성 추가(build.gradle), batch 설정 추가(application.yml) + 2. 앱에 `@EnableBatchProcessing` 추가 + 3. 저번 달(1일~말일)의 정산 데이터를 생성 Job, Step 추가 + - Chunk size 100 으로 지정([참고](https://jojoldu.tistory.com/331)) + - Scheduler + - Spring-boot Framework Scheduler(내장 스케쥴러)의 `@EnableScheduling`, `@Scheduled` 를 이용 + - 장애가 발생하여 배치가 15일 오전 4시에 실행되지 못할 경우를 고려하여 매일 오전 4시에 배치가 실행되도록 함(장애가 발생하면 해당 JobParameter 로 배치 다시 실행) + - `@Scheduled(cron = "0 0 4 15 * *")` : 매달 15일 오전 4시 0분 0초 실행 + - `@Scheduled(cron = "0 0 4 * * *")` : 매일 오전 4시 0분 0초 실행 + - JobParameters 에 year, month 값을 담아 JobLauncher로 Job 실행 + - JobParameter 에서는 날짜 → String 으로 변환하여 사용([참고](https://jojoldu.tistory.com/490)) +- 정산 데이터 리스트 + - [UI] 정산번호, 품목번호, 상품명, 결제일시, 결제금액, PG 수수료, 도매가, 환불일시, 환불금액, 판매자, 예상정산금액, 정산 예치금 내역번호, 비고 표시 + - 정산 상태에 따른 정산 완료/환불 완료 표시, 건별 정산 신청 버튼 표시 + - 2가지 방식 + - 전체 정산 데이터 리스트 조회 + - year, month 에 해당하는 월별 정산 데이터 리스트 조회 +- 정산 처리 + + - 전액 환불건, 정산 완료건은 정산 불가 + - 예상 정산 금액 = 도매가 - PG 수수료 + - PG 수수료는 0원으로 가정 + - 판매자 : MUT Books = 5 : 5 로 정산 → 도매가 = 판매가 * 0.5 + - 관리자는 각 월의 15일에 지난달 정산액을 작가(회원)들에게 송금하여 정산 처리 + - 판매자에게 예치금으로 정산금액 지급 + - 정산 완료 후, 전체 정산 데이터 리스트 페이지로 리다이렉트 + + 1. 전체 정산(선택 방식) + - 여러 개의 정산 건을 선택하여 한번에 정산 처리 + 2. 건별 정산(단건 방식) + +### 출금 +- 로그인한 회원만 출금 기능 사용 가능 +- 신청 완료/출금 완료/취소 완료 3가지 상태 + +---------- + +- MemberExtra 엔티티 추가 + - 은행명, 계좌번호 컬럼 + - 대상 테이블(member_extra)에 외래 키가 있는 경우 일대일 양방향([참고](https://blog.advenoh.pe.kr/database/JPA-%EC%9D%BC%EB%8C%80%EC%9D%BC-One-To-One-%EC%97%B0%EA%B4%80%EA%B4%80%EA%B3%84/)) + - memberExtra 엔티티에 @OneToOne 설정 + - member 엔티티에 @OneToOne(mappedBy=”member”) 설정 +- 출금 계좌 관리 + - [UI] 출금 계좌 정보(은행명, 계좌 번호), 출금 계좌 등록 버튼 표시 + - 내 프로필 > 출금계좌 관리 접속 +- 출금 계좌 등록 + - 출금 계좌 정보(은행명, 계좌 번호) 입력 후, 등록 + - 등록 완료시 출금 계좌 관리 페이지로 리다이렉트 +- 출금 신청폼 + - [UI] 출금 계좌 정보(은행명, 계좌번호), 캐시 잔액 표시 + - Form : price + - 전액 checkbox 선택 시 자동 값 입력, 최소/최대 입력값 제한 + - 내 프로필 > 출금신청 or 내 프로필 > 출금계좌 관리 > 출금 신청 접속 + - 출금 계좌 정보가 존재하지 않으면, 출금계좌 관리 페이지로 리다이렉트 +- 출금 신청(사용자 기능) + - 작가 회원이 정산받은 금액 or 본인이 충전한 금액 + - 최소 출금 신청 금액 = 1,000원 + - 최대 출금 금액 = 본인이 보유한 예치금 +- 출금 신청 내역 리스트 + + - [UI] 은행명, 계좌번호, 금액, 신청 일시, 출금 일시, 취소 일시, 처리 상태 + + 1. 사용자 기능 + - 본인의 출금 신청 내역을 최신순으로 조회 + 2. 관리자 기능 + - 모든 회원의 출금 신청 내역을 최신순으로 조회 + - *신청 완료 상태 건을 맨 위로 리스팅 +- 출금 처리(관리자 기능) + - 관리자 출금 신청 내역 페이지에서 건별로 출금 처리 요청 + - 출금 수수료 없다고 가정 +- 출금 신청 취소 + + - 출금 취소 사유: 사용자 요청/관리자 요청(2가지) + - enum, converter 관리 + + 1. 사용자 기능 + - 본인의 출금 신청 건만 취소 가능 + 2. 관리자 기능 + - 모든 회원의 출금 신청 건에 대해 취소 가능 From d6c753e6016fdcc0039dfa935e709717b6b78c5d Mon Sep 17 00:00:00 2001 From: ahah525 Date: Thu, 17 Nov 2022 22:29:34 +0900 Subject: [PATCH 39/39] =?UTF-8?q?Feat:=202=EC=B0=A8=20=ED=94=84=EB=A1=9C?= =?UTF-8?q?=EC=A0=9D=ED=8A=B8=20=EA=B0=9C=EB=B0=9C=EC=9D=84=20=EC=9C=84?= =?UTF-8?q?=ED=95=9C=20=EC=84=B8=ED=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mutbooks/.DS_Store | Bin 0 -> 6148 bytes mutbooks/.gitignore | 38 ++ mutbooks/build.gradle | 91 +++++ mutbooks/db/init.sql | 9 + mutbooks/gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 60756 bytes .../gradle/wrapper/gradle-wrapper.properties | 5 + mutbooks/gradlew | 240 ++++++++++++ mutbooks/gradlew.bat | 91 +++++ mutbooks/settings.gradle | 1 + mutbooks/src/.DS_Store | Bin 0 -> 6148 bytes .../example/mutbooks/MutbooksApplication.java | 26 ++ .../com/example/mutbooks/app/AppConfig.java | 79 ++++ .../mutbooks/app/RestTemplateConfig.java | 35 ++ .../controller/MemberApiController.java | 70 ++++ .../app/api/member/dto/request/LoginDto.java | 17 + .../api/member/dto/response/MemberDto.java | 34 ++ .../app/api/myBooks/MyBooksApiController.java | 46 +++ .../mutbooks/app/base/SpringDocConfig.java | 23 ++ .../example/mutbooks/app/base/dto/RsData.java | 40 ++ .../mutbooks/app/base/entity/BaseEntity.java | 31 ++ .../app/base/initData/DevInitData.java | 37 ++ .../app/base/initData/InitDataBefore.java | 84 ++++ .../app/base/initData/TestInitData.java | 38 ++ .../app/cart/controller/CartController.java | 72 ++++ .../mutbooks/app/cart/entity/CartItem.java | 28 ++ .../exception/CartItemNotFoundException.java | 7 + .../cart/repository/CartItemRepository.java | 17 + .../app/cart/service/CartService.java | 80 ++++ .../mutbooks/app/cash/entity/CashLog.java | 27 ++ .../cash/repository/CashLogRepository.java | 7 + .../app/cash/service/CashService.java | 28 ++ .../home/controller/AdminHomeController.java | 23 ++ .../app/home/controller/HomeController.java | 12 + .../app/mail/service/MailService.java | 75 ++++ .../member/controller/MemberController.java | 219 +++++++++++ .../mutbooks/app/member/entity/AuthLevel.java | 27 ++ .../app/member/entity/AuthLevelConverter.java | 28 ++ .../mutbooks/app/member/entity/Member.java | 100 +++++ .../app/member/entity/MemberExtra.java | 23 ++ .../PasswordNotMatchedException.java | 7 + .../mutbooks/app/member/form/JoinForm.java | 26 ++ .../mutbooks/app/member/form/ModifyForm.java | 17 + .../app/member/form/PwdModifyForm.java | 24 ++ .../app/member/form/WithdrawAccountForm.java | 15 + .../member/repository/MemberRepository.java | 14 + .../app/member/service/MemberService.java | 185 +++++++++ .../validator/PwdModifyFormValidator.java | 26 ++ .../mybook/dto/response/MyBookDetailDto.java | 36 ++ .../app/mybook/dto/response/MyBookDto.java | 34 ++ .../mutbooks/app/mybook/entity/MyBook.java | 29 ++ .../exception/MyBookNotFoundException.java | 7 + .../mybook/repository/MyBookRepository.java | 18 + .../app/mybook/service/MyBookService.java | 98 +++++ .../app/order/controller/OrderController.java | 236 +++++++++++ .../mutbooks/app/order/entity/Order.java | 190 +++++++++ .../mutbooks/app/order/entity/OrderItem.java | 65 ++++ .../exception/OrderIdNotMatchedException.java | 7 + .../exception/OrderNotFoundException.java | 7 + ...aymentFailByInsufficientCashException.java | 8 + .../order/repository/OrderItemRepository.java | 14 + .../app/order/repository/OrderRepository.java | 10 + .../app/order/service/OrderService.java | 197 ++++++++++ .../app/post/controller/PostController.java | 122 ++++++ .../app/post/dto/response/PostDetailDto.java | 38 ++ .../mutbooks/app/post/entity/Post.java | 46 +++ .../post/exception/PostNotFoundException.java | 4 + .../mutbooks/app/post/form/WriteForm.java | 17 + .../app/post/repository/PostRepository.java | 11 + .../post/repository/PostRepositoryCustom.java | 10 + .../post/repository/PostRepositoryImpl.java | 43 ++ .../app/post/service/PostService.java | 92 +++++ .../app/postHashTag/entity/PostHashTag.java | 36 ++ .../repository/PostHashTagRepository.java | 17 + .../service/PostHashTagService.java | 85 ++++ .../app/postKeyword/dto/PostKeywordDto.java | 12 + .../app/postKeyword/entity/PostKeyword.java | 22 ++ .../PostKeywordNotFoundException.java | 7 + .../repository/PostKeywordRepository.java | 10 + .../PostKeywordRepositoryCustom.java | 9 + .../repository/PostKeywordRepositoryImpl.java | 34 ++ .../service/PostKeywordService.java | 52 +++ .../product/controller/ProductController.java | 131 +++++++ .../dto/response/ProductDetailDto.java | 40 ++ .../app/product/dto/response/ProductDto.java | 33 ++ .../mutbooks/app/product/entity/Product.java | 65 ++++ .../exception/ProductNotFoundException.java | 7 + .../app/product/form/ProductForm.java | 27 ++ .../app/product/form/ProductModifyForm.java | 24 ++ .../product/repository/ProductRepository.java | 10 + .../app/product/service/ProductService.java | 86 ++++ .../productHashTag/entity/ProductHashTag.java | 32 ++ .../repository/ProductHashTagRepository.java | 13 + .../service/ProductHashTagService.java | 84 ++++ .../productKeyword/entity/ProductKeyword.java | 22 ++ .../repository/ProductKeywordRepository.java | 10 + .../service/ProductKeywordService.java | 36 ++ .../controller/AdmRebateController.java | 93 +++++ .../app/rebate/entity/RebateOrderItem.java | 139 +++++++ .../RebateOrderItemNotFoundException.java | 7 + .../app/rebate/form/RebateDataForm.java | 15 + .../repository/RebateOrderItemRepository.java | 16 + .../app/rebate/service/RebateService.java | 120 ++++++ .../app/security/ApiSecurityConfig.java | 70 ++++ .../mutbooks/app/security/SecurityConfig.java | 46 +++ .../app/security/dto/MemberContext.java | 80 ++++ .../filter/JwtAuthorizationFilter.java | 74 ++++ .../mutbooks/app/security/jwt/JwtConfig.java | 26 ++ .../app/security/jwt/JwtProvider.java | 69 ++++ .../service/CustomUserDetailsService.java | 28 ++ .../controller/AdmWithdrawController.java | 54 +++ .../controller/WithdrawController.java | 81 ++++ .../app/withdraw/entity/CancelType.java | 28 ++ .../withdraw/entity/CancelTypeConverter.java | 28 ++ .../app/withdraw/entity/WithdrawApply.java | 77 ++++ .../WithdrawApplyNotFoundException.java | 7 + .../app/withdraw/form/WithdrawApplyForm.java | 16 + .../repository/WithdrawApplyRepository.java | 10 + .../app/withdraw/service/WithdrawService.java | 104 +++++ .../MakeRebateOrderItemJobConfig.java | 114 ++++++ .../mutbooks/scheduler/JobScheduler.java | 65 ++++ .../java/com/example/mutbooks/util/Ut.java | 135 +++++++ .../src/main/resources/application-dev.yml | 18 + .../src/main/resources/application-test.yml | 8 + mutbooks/src/main/resources/application.yml | 41 ++ .../static/resource/common/common.css | 55 +++ .../static/resource/common/common.js | 368 ++++++++++++++++++ .../resources/templates/adm/home/main.html | 14 + .../templates/adm/layout/layout.html | 92 +++++ .../templates/adm/rebate/makeData.html | 91 +++++ .../adm/rebate/rebateOrderItemList.html | 115 ++++++ .../templates/adm/withdraw/apply_list.html | 70 ++++ .../main/resources/templates/cart/list.html | 149 +++++++ .../main/resources/templates/home/main.html | 14 + .../resources/templates/layout/layout.html | 212 ++++++++++ .../templates/member/confirm_password.html | 43 ++ .../templates/member/confirm_username.html | 43 ++ .../templates/member/find_password.html | 73 ++++ .../templates/member/find_username.html | 57 +++ .../main/resources/templates/member/join.html | 114 ++++++ .../resources/templates/member/login.html | 86 ++++ .../member/manage_withdraw_account.html | 49 +++ .../resources/templates/member/modify.html | 70 ++++ .../templates/member/modify_password.html | 93 +++++ .../resources/templates/member/profile.html | 65 ++++ .../member/register_withdraw_account.html | 87 +++++ .../resources/templates/order/detail.html | 265 +++++++++++++ .../main/resources/templates/order/fail.html | 24 ++ .../main/resources/templates/order/list.html | 53 +++ .../resources/templates/order/success.html | 21 + .../main/resources/templates/post/detail.html | 65 ++++ .../main/resources/templates/post/list.html | 56 +++ .../main/resources/templates/post/modify.html | 92 +++++ .../main/resources/templates/post/write.html | 92 +++++ .../resources/templates/product/create.html | 122 ++++++ .../resources/templates/product/detail.html | 83 ++++ .../resources/templates/product/list.html | 60 +++ .../resources/templates/product/modify.html | 117 ++++++ .../resources/templates/withdraw/apply.html | 157 ++++++++ .../templates/withdraw/apply_list.html | 67 ++++ .../mutbooks/MutbooksApplicationTests.java | 13 + .../controller/MemberApiControllerTest.java | 163 ++++++++ .../app/post/service/PostServiceTest.java | 88 +++++ .../service/PostHashTagServiceTest.java | 65 ++++ .../com/example/mutbooks/util/UtTest.java | 21 + 164 files changed, 9518 insertions(+) create mode 100644 mutbooks/.DS_Store create mode 100644 mutbooks/.gitignore create mode 100644 mutbooks/build.gradle create mode 100644 mutbooks/db/init.sql create mode 100644 mutbooks/gradle/wrapper/gradle-wrapper.jar create mode 100644 mutbooks/gradle/wrapper/gradle-wrapper.properties create mode 100755 mutbooks/gradlew create mode 100644 mutbooks/gradlew.bat create mode 100644 mutbooks/settings.gradle create mode 100644 mutbooks/src/.DS_Store create mode 100644 mutbooks/src/main/java/com/example/mutbooks/MutbooksApplication.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/AppConfig.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/RestTemplateConfig.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/api/member/controller/MemberApiController.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/request/LoginDto.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/response/MemberDto.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/base/SpringDocConfig.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/base/entity/BaseEntity.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/base/initData/DevInitData.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/base/initData/InitDataBefore.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/base/initData/TestInitData.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/cart/controller/CartController.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/cart/entity/CartItem.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/cart/exception/CartItemNotFoundException.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/cart/repository/CartItemRepository.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/cart/service/CartService.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/cash/entity/CashLog.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/cash/repository/CashLogRepository.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/cash/service/CashService.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/home/controller/AdminHomeController.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/home/controller/HomeController.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/mail/service/MailService.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/member/controller/MemberController.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/member/entity/AuthLevel.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/member/entity/AuthLevelConverter.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/member/entity/MemberExtra.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/member/exception/PasswordNotMatchedException.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/member/form/JoinForm.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/member/form/ModifyForm.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/member/form/PwdModifyForm.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/member/form/WithdrawAccountForm.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/member/repository/MemberRepository.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/member/validator/PwdModifyFormValidator.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDetailDto.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDto.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/mybook/entity/MyBook.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/mybook/exception/MyBookNotFoundException.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/mybook/repository/MyBookRepository.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/order/controller/OrderController.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/order/entity/Order.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/order/entity/OrderItem.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/order/exception/OrderIdNotMatchedException.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/order/exception/OrderNotFoundException.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/order/exception/PaymentFailByInsufficientCashException.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/order/repository/OrderItemRepository.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/order/repository/OrderRepository.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/order/service/OrderService.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/post/controller/PostController.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/post/dto/response/PostDetailDto.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/post/entity/Post.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/post/exception/PostNotFoundException.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/post/form/WriteForm.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/post/repository/PostRepository.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/post/repository/PostRepositoryCustom.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/post/repository/PostRepositoryImpl.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/post/service/PostService.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/entity/PostHashTag.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/repository/PostHashTagRepository.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/service/PostHashTagService.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/dto/PostKeywordDto.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/entity/PostKeyword.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/exception/PostKeywordNotFoundException.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/repository/PostKeywordRepository.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/repository/PostKeywordRepositoryCustom.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/repository/PostKeywordRepositoryImpl.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/service/PostKeywordService.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/product/controller/ProductController.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDetailDto.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDto.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/product/entity/Product.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/product/exception/ProductNotFoundException.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/product/form/ProductForm.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/product/form/ProductModifyForm.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/product/repository/ProductRepository.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/product/service/ProductService.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/productHashTag/entity/ProductHashTag.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/productHashTag/repository/ProductHashTagRepository.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/productHashTag/service/ProductHashTagService.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/productKeyword/entity/ProductKeyword.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/productKeyword/repository/ProductKeywordRepository.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/productKeyword/service/ProductKeywordService.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/rebate/controller/AdmRebateController.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/rebate/entity/RebateOrderItem.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/rebate/exception/RebateOrderItemNotFoundException.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/rebate/form/RebateDataForm.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/rebate/repository/RebateOrderItemRepository.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/rebate/service/RebateService.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/security/ApiSecurityConfig.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/security/SecurityConfig.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/security/dto/MemberContext.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtConfig.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/security/service/CustomUserDetailsService.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/AdmWithdrawController.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/WithdrawController.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/withdraw/entity/CancelType.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/withdraw/entity/CancelTypeConverter.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/withdraw/entity/WithdrawApply.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/withdraw/exception/WithdrawApplyNotFoundException.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/withdraw/form/WithdrawApplyForm.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/withdraw/repository/WithdrawApplyRepository.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/app/withdraw/service/WithdrawService.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/job/makeRebateOrderItem/MakeRebateOrderItemJobConfig.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/scheduler/JobScheduler.java create mode 100644 mutbooks/src/main/java/com/example/mutbooks/util/Ut.java create mode 100644 mutbooks/src/main/resources/application-dev.yml create mode 100644 mutbooks/src/main/resources/application-test.yml create mode 100644 mutbooks/src/main/resources/application.yml create mode 100644 mutbooks/src/main/resources/static/resource/common/common.css create mode 100644 mutbooks/src/main/resources/static/resource/common/common.js create mode 100644 mutbooks/src/main/resources/templates/adm/home/main.html create mode 100644 mutbooks/src/main/resources/templates/adm/layout/layout.html create mode 100644 mutbooks/src/main/resources/templates/adm/rebate/makeData.html create mode 100644 mutbooks/src/main/resources/templates/adm/rebate/rebateOrderItemList.html create mode 100644 mutbooks/src/main/resources/templates/adm/withdraw/apply_list.html create mode 100644 mutbooks/src/main/resources/templates/cart/list.html create mode 100644 mutbooks/src/main/resources/templates/home/main.html create mode 100644 mutbooks/src/main/resources/templates/layout/layout.html create mode 100644 mutbooks/src/main/resources/templates/member/confirm_password.html create mode 100644 mutbooks/src/main/resources/templates/member/confirm_username.html create mode 100644 mutbooks/src/main/resources/templates/member/find_password.html create mode 100644 mutbooks/src/main/resources/templates/member/find_username.html create mode 100644 mutbooks/src/main/resources/templates/member/join.html create mode 100644 mutbooks/src/main/resources/templates/member/login.html create mode 100644 mutbooks/src/main/resources/templates/member/manage_withdraw_account.html create mode 100644 mutbooks/src/main/resources/templates/member/modify.html create mode 100644 mutbooks/src/main/resources/templates/member/modify_password.html create mode 100644 mutbooks/src/main/resources/templates/member/profile.html create mode 100644 mutbooks/src/main/resources/templates/member/register_withdraw_account.html create mode 100644 mutbooks/src/main/resources/templates/order/detail.html create mode 100644 mutbooks/src/main/resources/templates/order/fail.html create mode 100644 mutbooks/src/main/resources/templates/order/list.html create mode 100644 mutbooks/src/main/resources/templates/order/success.html create mode 100644 mutbooks/src/main/resources/templates/post/detail.html create mode 100644 mutbooks/src/main/resources/templates/post/list.html create mode 100644 mutbooks/src/main/resources/templates/post/modify.html create mode 100644 mutbooks/src/main/resources/templates/post/write.html create mode 100644 mutbooks/src/main/resources/templates/product/create.html create mode 100644 mutbooks/src/main/resources/templates/product/detail.html create mode 100644 mutbooks/src/main/resources/templates/product/list.html create mode 100644 mutbooks/src/main/resources/templates/product/modify.html create mode 100644 mutbooks/src/main/resources/templates/withdraw/apply.html create mode 100644 mutbooks/src/main/resources/templates/withdraw/apply_list.html create mode 100644 mutbooks/src/test/java/com/example/mutbooks/MutbooksApplicationTests.java create mode 100644 mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java create mode 100644 mutbooks/src/test/java/com/example/mutbooks/app/post/service/PostServiceTest.java create mode 100644 mutbooks/src/test/java/com/example/mutbooks/app/postHashTag/service/PostHashTagServiceTest.java create mode 100644 mutbooks/src/test/java/com/example/mutbooks/util/UtTest.java diff --git a/mutbooks/.DS_Store b/mutbooks/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..b28523ed91c4035cb7b6165aec3096d49e0d17a6 GIT binary patch literal 6148 zcmeHKPfNov6i>G4GKSED!j1v21Gg~`!%M091+3^nWwv%`u{NXa++hrQ)-U8I@$>jz zl7hpYMcjLk{NCTB`9brCF~+?`G-S+Sj0tFn9F-bDcWtO)lMy+Nk_k!#OtxKhnu+oF@DxNK; z&i<)Niy%&CnJ$Q<8Km4^$7!UNo?4_)u4{c05FOE(I=$6uI6m&n(RjG-%hhBw=*#hB zv|e|_!Qs)##q>FON!6R7lLOmY_AFNL4vJmPtDmKbN*}>fWmj2*!~iis3=jj`&44`@ zM0dMspw$xt#6S%LxIai}h_1!bpx!#5!|OA~TZky2<68nzT68Uz1|b5%O(~!$<@Sle zO*#0b&2uf522DBRdS)2M&RjiSxSk#SQl~TS8l;{WAO^6;#c(C(q3U|xv|2FJ<}OVlCHwOAU&QP8i; Q0qG*3389V{_yq>O0KI5QfB*mh literal 0 HcmV?d00001 diff --git a/mutbooks/.gitignore b/mutbooks/.gitignore new file mode 100644 index 0000000..5ecac44 --- /dev/null +++ b/mutbooks/.gitignore @@ -0,0 +1,38 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ +application-base-addi.yml \ No newline at end of file diff --git a/mutbooks/build.gradle b/mutbooks/build.gradle new file mode 100644 index 0000000..15ce448 --- /dev/null +++ b/mutbooks/build.gradle @@ -0,0 +1,91 @@ +// querydsl 추가 +buildscript { + ext { + queryDslVersion = "5.0.0" + } +} + +plugins { + id 'org.springframework.boot' version '2.7.4' + id 'io.spring.dependency-management' version '1.0.14.RELEASE' + id 'java' + + //querydsl 추가 + id "com.ewerk.gradle.plugins.querydsl" version "1.0.10" +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '17' + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5' + compileOnly 'org.projectlombok:lombok' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + runtimeOnly 'org.mariadb.jdbc:mariadb-java-client' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.security:spring-security-test' + // thymeleaf layout + implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:3.1.0' + // validation 유효성 검증 + implementation 'org.springframework.boot:spring-boot-starter-validation' + // Gmail SMTP + implementation 'org.springframework.boot:spring-boot-starter-mail' + + //querydsl 추가 + implementation "com.querydsl:querydsl-jpa:${queryDslVersion}" + annotationProcessor "com.querydsl:querydsl-apt:${queryDslVersion}" + + // spring batch + implementation 'org.springframework.boot:spring-boot-starter-batch' + testImplementation 'org.springframework.batch:spring-batch-test' + // apache httpclient + implementation 'org.apache.httpcomponents:httpclient:4.5' + + // jwt + implementation 'io.jsonwebtoken:jjwt-api:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' + + // spring doc + implementation 'org.springdoc:springdoc-openapi-ui:1.6.11' +} + +tasks.named('test') { + useJUnitPlatform() +} + +//querydsl 추가 시작 +def querydslDir = "$buildDir/generated/querydsl" + +querydsl { + jpa = true + querydslSourcesDir = querydslDir +} + +sourceSets { + main.java.srcDir querydslDir +} + +configurations { + querydsl.extendsFrom compileClasspath +} + +compileQuerydsl { + options.annotationProcessorPath = configurations.querydsl +} \ No newline at end of file diff --git a/mutbooks/db/init.sql b/mutbooks/db/init.sql new file mode 100644 index 0000000..31cf086 --- /dev/null +++ b/mutbooks/db/init.sql @@ -0,0 +1,9 @@ +# 테스트 DB 생성 +DROP DATABASE IF EXISTS mut_books__test; +CREATE DATABASE mut_books__test; +USE mut_books__test; + +# 개발 DB 생성 +DROP DATABASE IF EXISTS mut_books__dev; +CREATE DATABASE mut_books__dev; +USE mut_books__dev; \ No newline at end of file diff --git a/mutbooks/gradle/wrapper/gradle-wrapper.jar b/mutbooks/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..249e5832f090a2944b7473328c07c9755baa3196 GIT binary patch literal 60756 zcmb5WV{~QRw(p$^Dz@00IL3?^hro$gg*4VI_WAaTyVM5Foj~O|-84 z$;06hMwt*rV;^8iB z1~&0XWpYJmG?Ts^K9PC62H*`G}xom%S%yq|xvG~FIfP=9*f zZoDRJBm*Y0aId=qJ?7dyb)6)JGWGwe)MHeNSzhi)Ko6J<-m@v=a%NsP537lHe0R* z`If4$aaBA#S=w!2z&m>{lpTy^Lm^mg*3?M&7HFv}7K6x*cukLIGX;bQG|QWdn{%_6 zHnwBKr84#B7Z+AnBXa16a?or^R?+>$4`}{*a_>IhbjvyTtWkHw)|ay)ahWUd-qq$~ zMbh6roVsj;_qnC-R{G+Cy6bApVOinSU-;(DxUEl!i2)1EeQ9`hrfqj(nKI7?Z>Xur zoJz-a`PxkYit1HEbv|jy%~DO^13J-ut986EEG=66S}D3!L}Efp;Bez~7tNq{QsUMm zh9~(HYg1pA*=37C0}n4g&bFbQ+?-h-W}onYeE{q;cIy%eZK9wZjSwGvT+&Cgv z?~{9p(;bY_1+k|wkt_|N!@J~aoY@|U_RGoWX<;p{Nu*D*&_phw`8jYkMNpRTWx1H* z>J-Mi_!`M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v8-N||+XL=O*%3+y)oI(HbM)Ds?q8~HPzIP(vs*G`iddbWq}! z(2!VjP&{Z1w+%eUq^ '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/mutbooks/gradlew.bat b/mutbooks/gradlew.bat new file mode 100644 index 0000000..f127cfd --- /dev/null +++ b/mutbooks/gradlew.bat @@ -0,0 +1,91 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/mutbooks/settings.gradle b/mutbooks/settings.gradle new file mode 100644 index 0000000..c4383d6 --- /dev/null +++ b/mutbooks/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'mutbooks' diff --git a/mutbooks/src/.DS_Store b/mutbooks/src/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..3e1b68e84c7102f16d0efa9b8e45c0b5d407bde8 GIT binary patch literal 6148 zcmeHKPfNov6i>G5GKSED!j1v21Gg~`!%M091+3^nWwvx^v1`WKxx*OrtY64a;^*AbZ-pRY%(IpF``92jZzhX{bpl- z9q`*7Hen%4SoZb%qiLGtMYsFTYjtO5w;>v$CGLVpwFru^nCE^tyFu$xsWhteFuF>{ zi;=s3smZd6t0AH0~hZ$$?BJI=opH|~^~3-%u+Bi;m@c0G=kUvHeB`f} zkVOm-1OJQx?wkc@J}k2c1XRU;G4-EzLN>o5VU%Lc=f%`~X2Tfd}4tbu%(jbn4 Seq9bo7XeKOb;Q6gFz^9%dP+k8 literal 0 HcmV?d00001 diff --git a/mutbooks/src/main/java/com/example/mutbooks/MutbooksApplication.java b/mutbooks/src/main/java/com/example/mutbooks/MutbooksApplication.java new file mode 100644 index 0000000..fe951b6 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/MutbooksApplication.java @@ -0,0 +1,26 @@ +package com.example.mutbooks; + +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@SpringBootApplication +@EnableJpaAuditing +@EnableScheduling // Schedule 기능 켜기 +@EnableBatchProcessing // 배치앱 +public class MutbooksApplication { + + public static void main(String[] args) { + SpringApplication.run(MutbooksApplication.class, args); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/AppConfig.java b/mutbooks/src/main/java/com/example/mutbooks/app/AppConfig.java new file mode 100644 index 0000000..e62a32c --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/AppConfig.java @@ -0,0 +1,79 @@ +package com.example.mutbooks.app; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.querydsl.jpa.impl.JPAQueryFactory; +import lombok.Getter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.persistence.EntityManager; + +@Configuration +public class AppConfig { + @Getter + private static ApplicationContext context; + private static String activeProfile; + @Getter + private static String siteName; + @Getter + private static String siteBaseUrl; + + @Autowired + public void setContext(ApplicationContext context) { + AppConfig.context = context; + } + + @Value("${spring.profiles.active:}") + public void setActiveProfile(String value) { + activeProfile = value; + } + + @Value("${custom.site.name}") + public void setSiteName(String siteName) { + AppConfig.siteName = siteName; + } + + @Value("${custom.site.baseUrl}") + public void setSiteBaseUrl(String siteBaseUrl) { + AppConfig.siteBaseUrl = siteBaseUrl; + } + + public static boolean isNotProd() { + return isProd() == false; + } + + public static boolean isProd() { + return activeProfile.equals("prod"); + } + + public static boolean isNotDev() { + return isLocal() == false; + } + + public static boolean isLocal() { + return activeProfile.equals("local"); + } + + public static boolean isNotTest() { + return isLocal() == false; + } + + public static boolean isTest() { + return activeProfile.equals("test"); + } + + @Bean + public ObjectMapper objectMapper() { + // LocalDateTime 관련 직렬화/역직렬화 오류시, new JavaTimeModule() 추가 + return new ObjectMapper().registerModule(new JavaTimeModule()); + } + + @Bean + public JPAQueryFactory jpaQueryFactory(EntityManager entityManager) { + return new JPAQueryFactory(entityManager); + } +} \ No newline at end of file diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/RestTemplateConfig.java b/mutbooks/src/main/java/com/example/mutbooks/app/RestTemplateConfig.java new file mode 100644 index 0000000..acc80b1 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/RestTemplateConfig.java @@ -0,0 +1,35 @@ +package com.example.mutbooks.app; + +import org.apache.http.client.HttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +/** + * 다른 서버에 Rest 요청을 할 때 필요한 설정을 하는 클래스 + */ +@Configuration +public class RestTemplateConfig { + private final int READ_TIMEOUT = 5000; // 읽기시간초과(ms) + private final int CONNECT_TIMEOUT = 5000; // 연결시간초과(ms) + private final int MAX_CONN_TOTAL = 100; // 최대 오픈되는 커넥션 수 + private final int MAX_CONN_PER_ROUTE = 5; // IP, 포트 1쌍에 수행할 커넥션 수 + + @Bean + public RestTemplate restTemplate() { + HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); + factory.setReadTimeout(READ_TIMEOUT); + factory.setConnectTimeout(CONNECT_TIMEOUT); + + HttpClient httpClient = HttpClientBuilder.create() + .setMaxConnTotal(MAX_CONN_TOTAL) + .setMaxConnPerRoute(MAX_CONN_PER_ROUTE) + .build(); + + factory.setHttpClient(httpClient); + + return new RestTemplate(factory); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/api/member/controller/MemberApiController.java b/mutbooks/src/main/java/com/example/mutbooks/app/api/member/controller/MemberApiController.java new file mode 100644 index 0000000..a857618 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/api/member/controller/MemberApiController.java @@ -0,0 +1,70 @@ +package com.example.mutbooks.app.api.member.controller; + +import com.example.mutbooks.app.api.member.dto.response.MemberDto; +import com.example.mutbooks.app.base.dto.RsData; +import com.example.mutbooks.app.api.member.dto.request.LoginDto; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.member.service.MemberService; +import com.example.mutbooks.app.security.dto.MemberContext; +import com.example.mutbooks.util.Ut; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/api/v1/member") +@RequiredArgsConstructor +@Slf4j +public class MemberApiController { + private final MemberService memberService; + private final PasswordEncoder passwordEncoder; + + @PostMapping("/login") + public ResponseEntity login(@RequestBody LoginDto loginDto) { + log.info("로그인"); + // 입력 데이터 유효성 검증 + if(loginDto.isNotValid()) { + return Ut.spring.responseEntityOf(RsData.of("F-1", "로그인 정보가 올바르지 않습니다..")); + } + + Member member = memberService.findByUsername(loginDto.getUsername()); + // 1. 존재하지 않는 회원 + if(member == null) { + log.info("존재하지 않는 회원"); + return Ut.spring.responseEntityOf(RsData.of("F-2", "일치하는 회원이 존재하지 않습니다.")); + } + // 2. 올바르지 않은 비밀번호 + // matches(비밀번호 원문, 암호화된 비밀번호) + if(!passwordEncoder.matches(loginDto.getPassword(), member.getPassword())) { + log.info("비밀번호 틀림"); + return Ut.spring.responseEntityOf(RsData.of("F-3", "비밀번호가 일치하지 않습니다.")); + } + + log.debug("Ut.json.toStr(member.getAccessTokenClaims()) : " + Ut.json.toStr(member.getAccessTokenClaims())); + // accessToken 발급 + String accessToken = memberService.genAccessToken(member); + // 응답 헤더, 바디에 accessToken 담기 + return Ut.spring.responseEntityOf( + RsData.of( + "S-1", + "로그인 성공, Access Token을 발급합니다.", + Ut.mapOf("accessToken", accessToken) + ), + Ut.spring.httpHeadersOf("Authentication", accessToken) + ); + } + + // 회원 정보 + @GetMapping("/me") + public ResponseEntity test(@AuthenticationPrincipal MemberContext memberContext) { + if(memberContext == null) { + return Ut.spring.responseEntityOf(RsData.failOf(null)); + } + MemberDto memberDto = MemberDto.toDto(memberContext.getMember()); + + return Ut.spring.responseEntityOf(RsData.successOf(Ut.mapOf("member", memberDto))); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/request/LoginDto.java b/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/request/LoginDto.java new file mode 100644 index 0000000..06f5c7a --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/request/LoginDto.java @@ -0,0 +1,17 @@ +package com.example.mutbooks.app.api.member.dto.request; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +@Data +public class LoginDto { + @NotBlank(message = "username 을(를) 입력해주세요.") + private String username; + @NotBlank(message = "password 을(를) 입력해주세요.") + private String password; + + public boolean isNotValid() { + return username == null || password == null || username.trim().length() == 0 || password.trim().length() == 0; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/response/MemberDto.java b/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/response/MemberDto.java new file mode 100644 index 0000000..355db95 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/api/member/dto/response/MemberDto.java @@ -0,0 +1,34 @@ +package com.example.mutbooks.app.api.member.dto.response; + +import com.example.mutbooks.app.member.entity.Member; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@Builder +@AllArgsConstructor +public class MemberDto { + private Long id; + private LocalDateTime createDate; + private LocalDateTime modifyDate; + private String username; + private String email; + private boolean emailVerified; + private String nickname; + + public static MemberDto toDto(Member member) { + return MemberDto.builder() + .id(member.getId()) + .createDate(member.getCreateDate()) + .modifyDate(member.getUpdateDate()) + .username(member.getUsername()) + .email(member.getEmail()) + .nickname(member.getNickname()) + .build(); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java b/mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java new file mode 100644 index 0000000..07207bb --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/api/myBooks/MyBooksApiController.java @@ -0,0 +1,46 @@ +package com.example.mutbooks.app.api.myBooks; + +import com.example.mutbooks.app.base.dto.RsData; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.mybook.dto.response.MyBookDetailDto; +import com.example.mutbooks.app.mybook.dto.response.MyBookDto; +import com.example.mutbooks.app.mybook.service.MyBookService; +import com.example.mutbooks.app.security.dto.MemberContext; +import com.example.mutbooks.util.Ut; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api/v1/myBooks") +@RequiredArgsConstructor +public class MyBooksApiController { + private final MyBookService myBookService; + + // 내 도서 리스트 + @GetMapping("") + public ResponseEntity list(@AuthenticationPrincipal MemberContext memberContext) { + Member member = memberContext.getMember(); + List myBookDtos = myBookService.findAllByOwner(member); + + return Ut.spring.responseEntityOf( + RsData.successOf(Ut.mapOf("myBooks", myBookDtos)) + ); + } + + // 도서 상세 조회 + @GetMapping("/{myBookId}") + public ResponseEntity detail(@PathVariable long myBookId, @AuthenticationPrincipal MemberContext memberContext) { + MyBookDetailDto myBookDetailDto = myBookService.findByIdForDetail(myBookId, memberContext.getId()); + + return Ut.spring.responseEntityOf( + RsData.successOf(Ut.mapOf("myBook", myBookDetailDto)) + ); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/base/SpringDocConfig.java b/mutbooks/src/main/java/com/example/mutbooks/app/base/SpringDocConfig.java new file mode 100644 index 0000000..80273a5 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/base/SpringDocConfig.java @@ -0,0 +1,23 @@ +package com.example.mutbooks.app.base; + +import io.swagger.v3.oas.models.ExternalDocumentation; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.info.License; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SpringDocConfig { + @Bean + public OpenAPI springShopOpenAPI() { + return new OpenAPI() + .info(new Info().title("SpringShop API") + .description("Spring shop sample application") + .version("v0.0.1") + .license(new License().name("Apache 2.0").url("http://springdoc.org"))) + .externalDocs(new ExternalDocumentation() + .description("SpringShop Wiki Documentation") + .url("https://springshop.wiki.github.org/docs")); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java b/mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java new file mode 100644 index 0000000..71be8ec --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/base/dto/RsData.java @@ -0,0 +1,40 @@ +package com.example.mutbooks.app.base.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor +public class RsData { + private String resultCode; + private String msg; + private T data; + + public static RsData of(String resultCode, String msg, T data) { + return new RsData<>(resultCode, msg, data); + } + + public static RsData of(String resultCode, String msg) { + return of(resultCode, msg, null); + } + + // 성공 응답 + public static RsData successOf(T data) { + return of("S-1", "성공", data); + } + + // 실패 응답 + public static RsData failOf(T data) { + return of("F-1", "실패", data); + } + + public boolean isSuccess() { + return resultCode.startsWith("S-1"); + } + + public boolean isFail() { + return isSuccess() == false; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/base/entity/BaseEntity.java b/mutbooks/src/main/java/com/example/mutbooks/app/base/entity/BaseEntity.java new file mode 100644 index 0000000..010ee93 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/base/entity/BaseEntity.java @@ -0,0 +1,31 @@ +package com.example.mutbooks.app.base.entity; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.ToString; +import lombok.experimental.SuperBuilder; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Getter +@SuperBuilder +@MappedSuperclass +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@EntityListeners(AuditingEntityListener.class) +@ToString +public class BaseEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @CreatedDate + private LocalDateTime createDate; + + @LastModifiedDate + private LocalDateTime updateDate; +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/base/initData/DevInitData.java b/mutbooks/src/main/java/com/example/mutbooks/app/base/initData/DevInitData.java new file mode 100644 index 0000000..c71a3cf --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/base/initData/DevInitData.java @@ -0,0 +1,37 @@ +package com.example.mutbooks.app.base.initData; + +import com.example.mutbooks.app.cart.service.CartService; +import com.example.mutbooks.app.member.service.MemberService; +import com.example.mutbooks.app.order.service.OrderService; +import com.example.mutbooks.app.post.service.PostService; +import com.example.mutbooks.app.product.service.ProductService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.CommandLineRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +@Configuration +@Profile("dev") +@Slf4j +public class DevInitData implements InitDataBefore { + // initData 실행 여부(2번 생성되는 것을 막기 위함) + private boolean initDataDone = false; + + @Bean + CommandLineRunner initData( + MemberService memberService, + PostService postService, + ProductService productService, + CartService cartService, + OrderService orderService + ) { + return args -> { + if(initDataDone) return; + initDataDone = true; + + log.info("DevInitData 실행"); + before(memberService, postService, productService, cartService, orderService); + }; + } +} \ No newline at end of file diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/base/initData/InitDataBefore.java b/mutbooks/src/main/java/com/example/mutbooks/app/base/initData/InitDataBefore.java new file mode 100644 index 0000000..6249d13 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/base/initData/InitDataBefore.java @@ -0,0 +1,84 @@ +package com.example.mutbooks.app.base.initData; + +import com.example.mutbooks.app.cart.service.CartService; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.member.form.JoinForm; +import com.example.mutbooks.app.member.service.MemberService; +import com.example.mutbooks.app.order.entity.Order; +import com.example.mutbooks.app.order.service.OrderService; +import com.example.mutbooks.app.post.form.WriteForm; +import com.example.mutbooks.app.post.service.PostService; +import com.example.mutbooks.app.product.entity.Product; +import com.example.mutbooks.app.product.form.ProductForm; +import com.example.mutbooks.app.product.service.ProductService; + +public interface InitDataBefore { + default void before( + MemberService memberService, + PostService postService, + ProductService productService, + CartService cartService, + OrderService orderService + ) { + // 1번 회원(일반, 작가) + Member member1 = memberService.join(new JoinForm("user1", "1234", "딸기", "user1@test.com")); + // 2번 회원(일반, 작가) + Member member2 = memberService.join(new JoinForm("user2", "1234", "초코", "user2@test.com")); + // 3번 회원(일반) + Member member3 = memberService.join(new JoinForm("user3", "1234", null, "user3@test.com")); + // 4번 회원(일반, 관리자) + Member member4 = memberService.join(new JoinForm("admin", "1234", null, "admin@test.com")); + + // 1번 회원 캐시 50,000원 충전 + memberService.addCash(member1, 50_000, "충전"); + // 3번 회원 캐시 100,000원 충전 + memberService.addCash(member3, 100_000, "충전"); + + // 1번 회원 글 작성 + postService.write(member1, new WriteForm("해리포터1-1", "판타지 소설입니다.", "

  • 판타지 소설입니다.

","#해리포터1")); + postService.write(member1, new WriteForm("해리포터1-2", "판타지 소설입니다.", "
  • 판타지 소설입니다.

", "#해리포터1")); + postService.write(member1, new WriteForm("해리포터1-3", "판타지 소설입니다.", "
  • 판타지 소설입니다.

", "#해리포터1")); + postService.write(member1, new WriteForm("해리포터2-1", "판타지 소설입니다.", "
  • 판타지 소설입니다.

", "#해리포터2")); + postService.write(member1, new WriteForm("해리포터2-2", "판타지 소설입니다.", "
  • 판타지 소설입니다.

", "#해리포터2")); + postService.write(member1, new WriteForm("해리포터2-3", "판타지 소설입니다.", "
  • 판타지 소설입니다.

", "#해리포터2")); + postService.write(member1, new WriteForm("해리포터3-1", "판타지 소설입니다.", "
  • 판타지 소설입니다.

", "#해리포터3")); + postService.write(member1, new WriteForm("해리포터3-2", "판타지 소설입니다.", "
  • 판타지 소설입니다.

", "#해리포터3")); + + // 1번 회원이 1번(해리포터1) 글 키워드 선택 -> 1, 2, 3번 글 도서 등록(1번 도서) + Product product1 = productService.create(member1, new ProductForm("해리포터1", "판타지 소설입니다.", 18_000, 1L, "#판타지 #소설")); + // 1번 회원이 2번(해리포터2) 글 키워드 선택 -> 4, 5, 6번 글 도서 등록(2번 도서) + Product product2 = productService.create(member1, new ProductForm("해리포터2", "판타지 소설입니다.", 20_000, 1L, "#판타지 #소설")); + // 1번 회원이 3번(해리포터3) 글 키워드 선택 -> 7, 8번 글 도서 등록(3번 도서) + Product product3 = productService.create(member1, new ProductForm("해리포터3", "판타지 소설입니다.", 22_000, 1L, "#판타지 #소설")); + + // 2번 회원 글 작성 + postService.write(member2, new WriteForm("하트모양 크래커1", "로맨스 소설입니다.", "
  • 로맨스 소설입니다.

","#하트모양_크래커")); + postService.write(member2, new WriteForm("하트모양 크래커2", "로맨스 소설입니다.", "
  • 로맨스 소설입니다.

", "#하트모양_크래커")); + + // 2번 회원이 4번(하트모양_크래커) 글 키워드 선택 -> 9, 10번 글 도서 등록(4번 도서) + Product product4 = productService.create(member2, new ProductForm("하트모양 크래커", "로맨스 소설입니다.", 15000, 3L, "#로맨스 #소설")); + + // 1번 회원이 4번 도서 장바구니 품목 추가(1번 CartItem) + cartService.addCartItem(member1, product4); + + // 3번 회원이 1, 2, 3, 4번 도서 장바구니 품목 추가(2, 3, 4, 5번 CartItem) + cartService.addCartItem(member3, product1); + cartService.addCartItem(member3, product2); + cartService.addCartItem(member3, product3); + cartService.addCartItem(member3, product4); + + // 1번 회원 1번 주문 생성 + Order order1 = orderService.createOrder(member1, "1"); + // 3번 회원 2, 3, 4번 주문 생성 + Order order2 = orderService.createOrder(member3, "2,3"); + Order order3 = orderService.createOrder(member3, "4"); + Order order4 = orderService.createOrder(member3, "5"); + + // 1번 회원 1번 주문 결제 + orderService.payByRestCashOnly(order1); + // 3번 회원 2번 주문 결제, 3번 주문 결제 후 환불 + orderService.payByRestCashOnly(order2); + orderService.payByRestCashOnly(order3); + orderService.refundByRestCashOnly(order3); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/base/initData/TestInitData.java b/mutbooks/src/main/java/com/example/mutbooks/app/base/initData/TestInitData.java new file mode 100644 index 0000000..ff66b7c --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/base/initData/TestInitData.java @@ -0,0 +1,38 @@ +package com.example.mutbooks.app.base.initData; + +import com.example.mutbooks.app.cart.service.CartService; +import com.example.mutbooks.app.member.service.MemberService; +import com.example.mutbooks.app.order.service.OrderService; +import com.example.mutbooks.app.post.service.PostService; +import com.example.mutbooks.app.product.service.ProductService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.CommandLineRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +@Configuration +@Profile("test") +@Slf4j +public class TestInitData implements InitDataBefore { + // initData 실행 여부(2번 생성되는 것을 막기 위함) + private boolean initDataDone = false; + + @Bean + CommandLineRunner initData( + MemberService memberService, + PostService postService, + ProductService productService, + CartService cartService, + OrderService orderService + ) { + return args -> { + if(initDataDone) return; + initDataDone = true; + + log.info("TestInitData 실행"); + + before(memberService, postService, productService, cartService, orderService); + }; + } +} \ No newline at end of file diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/cart/controller/CartController.java b/mutbooks/src/main/java/com/example/mutbooks/app/cart/controller/CartController.java new file mode 100644 index 0000000..3251a1e --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/cart/controller/CartController.java @@ -0,0 +1,72 @@ +package com.example.mutbooks.app.cart.controller; + +import com.example.mutbooks.app.security.dto.MemberContext; +import com.example.mutbooks.app.cart.entity.CartItem; +import com.example.mutbooks.app.cart.service.CartService; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.product.entity.Product; +import com.example.mutbooks.app.product.service.ProductService; +import lombok.RequiredArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import java.util.List; + +@Controller +@RequiredArgsConstructor +@RequestMapping("/cart") +public class CartController { + private final CartService cartService; + private final ProductService productService; + + // 장바구니 품목 추가 + @PreAuthorize("isAuthenticated()") + @PostMapping("/add/{productId}") + public String addCartItem(@PathVariable long productId, @AuthenticationPrincipal MemberContext memberContext) { + Member buyer = memberContext.getMember(); + Product product = productService.findById(productId); + + cartService.addCartItem(buyer, product); + + return "redirect:/cart/list"; + } + + // 장바구니 품목 리스트 조회 + @PreAuthorize("isAuthenticated()") + @GetMapping("/list") + public String list(@AuthenticationPrincipal MemberContext memberContext, Model model) { + List cartItems = cartService.findAllByBuyerIdOrderByIdDesc(memberContext.getId()); + + model.addAttribute("cartItems", cartItems); + + return "cart/list"; + } + + // 장바구니 품목 단건 삭제 + @PreAuthorize("isAuthenticated()") + @PostMapping("/delete/{productId}") + public String deleteCartItem(@PathVariable long productId, @AuthenticationPrincipal MemberContext memberContext) { + Member buyer = memberContext.getMember(); + Product product = productService.findById(productId); + + cartService.deleteCartItem(buyer, product); + + return "redirect:/cart/list"; + } + + // 장바구니 품목 선택 삭제 + @PreAuthorize("isAuthenticated()") + @PostMapping("/deleteItems") + public String deleteCartItems(@AuthenticationPrincipal MemberContext memberContext, String ids) { + Member buyer = memberContext.getMember(); + cartService.deleteCartItems(buyer, ids); + + return "redirect:/cart/list"; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/cart/entity/CartItem.java b/mutbooks/src/main/java/com/example/mutbooks/app/cart/entity/CartItem.java new file mode 100644 index 0000000..05b5dd9 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/cart/entity/CartItem.java @@ -0,0 +1,28 @@ +package com.example.mutbooks.app.cart.entity; + +import com.example.mutbooks.app.base.entity.BaseEntity; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.product.entity.Product; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.SuperBuilder; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.ManyToOne; + +@Entity +@Getter +@Setter +@SuperBuilder +@NoArgsConstructor +@ToString(callSuper = true) +public class CartItem extends BaseEntity { + @ManyToOne(fetch= FetchType.LAZY) + private Member buyer; + + @ManyToOne(fetch = FetchType.LAZY) + private Product product; +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/cart/exception/CartItemNotFoundException.java b/mutbooks/src/main/java/com/example/mutbooks/app/cart/exception/CartItemNotFoundException.java new file mode 100644 index 0000000..9a50e22 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/cart/exception/CartItemNotFoundException.java @@ -0,0 +1,7 @@ +package com.example.mutbooks.app.cart.exception; + +public class CartItemNotFoundException extends RuntimeException { + public CartItemNotFoundException(String message) { + super(message); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/cart/repository/CartItemRepository.java b/mutbooks/src/main/java/com/example/mutbooks/app/cart/repository/CartItemRepository.java new file mode 100644 index 0000000..f96a0eb --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/cart/repository/CartItemRepository.java @@ -0,0 +1,17 @@ +package com.example.mutbooks.app.cart.repository; + +import com.example.mutbooks.app.cart.entity.CartItem; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; +import java.util.Optional; + +public interface CartItemRepository extends JpaRepository { + Optional findByBuyerIdAndProductId(Long buyerId, Long productId); + + List findAllByBuyerIdOrderByIdDesc(Long buyerId); + + List findByBuyerIdAndIdInOrderByIdDesc(Long buyerId, List cartItemIds); + + void deleteAllByBuyerIdAndIdIn(Long buyerId, List cartItemIds); +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/cart/service/CartService.java b/mutbooks/src/main/java/com/example/mutbooks/app/cart/service/CartService.java new file mode 100644 index 0000000..a79971d --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/cart/service/CartService.java @@ -0,0 +1,80 @@ +package com.example.mutbooks.app.cart.service; + +import com.example.mutbooks.app.cart.entity.CartItem; +import com.example.mutbooks.app.cart.exception.CartItemNotFoundException; +import com.example.mutbooks.app.cart.repository.CartItemRepository; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.product.entity.Product; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class CartService { + private final CartItemRepository cartItemRepository; + + @Transactional + public CartItem addCartItem(Member buyer, Product product) { + // 이미 장바구니에 담겼는지 검사 + CartItem oldCartItem = cartItemRepository.findByBuyerIdAndProductId(buyer.getId(), product.getId()) + .orElse(null); + + if(oldCartItem != null) { + return oldCartItem; + } + + CartItem cartItem = CartItem.builder() + .buyer(buyer) + .product(product) + .build(); + + cartItemRepository.save(cartItem); + + return cartItem; + } + + public List findAllByBuyerIdOrderByIdDesc(Long buyerId) { + return cartItemRepository.findAllByBuyerIdOrderByIdDesc(buyerId); + } + + @Transactional + public void deleteCartItem(Member buyer, Product product) { + CartItem cartItem = findByBuyerIdAndProductId(buyer.getId(), product.getId()); + + cartItemRepository.delete(cartItem); + } + + public CartItem findByBuyerIdAndProductId(Long buyerId, Long productId) { + return cartItemRepository.findByBuyerIdAndProductId(buyerId, productId).orElseThrow( + () -> { + throw new CartItemNotFoundException("장바구니 품목이 존재하지 않습니다."); + }); + } + + public CartItem findById(long id) { + return cartItemRepository.findById(id).orElse(null); + } + + public List findByBuyerAndIdInOrderByIdDesc(Member buyer, List cartItemIds) { + return cartItemRepository.findByBuyerIdAndIdInOrderByIdDesc(buyer.getId(), cartItemIds); + } + + @Transactional + public void deleteCartItems(Member buyer, String ids) { + // 장바구니에서 삭제해야하는 cartItem id 리스트 + String[] idsArr = ids.split(","); + // Array -> List + List cartItemIds = Arrays.stream(idsArr) + .mapToLong(Long::parseLong) + .boxed() + .collect(Collectors.toList()); + + cartItemRepository.deleteAllByBuyerIdAndIdIn(buyer.getId(), cartItemIds); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/cash/entity/CashLog.java b/mutbooks/src/main/java/com/example/mutbooks/app/cash/entity/CashLog.java new file mode 100644 index 0000000..0ddd87c --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/cash/entity/CashLog.java @@ -0,0 +1,27 @@ +package com.example.mutbooks.app.cash.entity; + +import com.example.mutbooks.app.base.entity.BaseEntity; +import com.example.mutbooks.app.member.entity.Member; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.SuperBuilder; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.ManyToOne; + +@Entity +@Getter +@Setter +@SuperBuilder +@NoArgsConstructor +@ToString(callSuper = true) +public class CashLog extends BaseEntity { + @ManyToOne(fetch = FetchType.LAZY) + private Member member; + + private int price; // 변동 금액 + private String eventType; // 변동 사유 +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/cash/repository/CashLogRepository.java b/mutbooks/src/main/java/com/example/mutbooks/app/cash/repository/CashLogRepository.java new file mode 100644 index 0000000..44960ea --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/cash/repository/CashLogRepository.java @@ -0,0 +1,7 @@ +package com.example.mutbooks.app.cash.repository; + +import com.example.mutbooks.app.cash.entity.CashLog; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface CashLogRepository extends JpaRepository { +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/cash/service/CashService.java b/mutbooks/src/main/java/com/example/mutbooks/app/cash/service/CashService.java new file mode 100644 index 0000000..79f087b --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/cash/service/CashService.java @@ -0,0 +1,28 @@ +package com.example.mutbooks.app.cash.service; + +import com.example.mutbooks.app.cash.entity.CashLog; +import com.example.mutbooks.app.cash.repository.CashLogRepository; +import com.example.mutbooks.app.member.entity.Member; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class CashService { + private final CashLogRepository cashLogRepository; + + @Transactional + public CashLog addCash(Member member, int price, String eventType) { + CashLog cashLog = CashLog.builder() + .member(member) + .price(price) + .eventType(eventType) + .build(); + + cashLogRepository.save(cashLog); + + return cashLog; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/home/controller/AdminHomeController.java b/mutbooks/src/main/java/com/example/mutbooks/app/home/controller/AdminHomeController.java new file mode 100644 index 0000000..21b6469 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/home/controller/AdminHomeController.java @@ -0,0 +1,23 @@ +package com.example.mutbooks.app.home.controller; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/adm") +public class AdminHomeController { + @GetMapping("") + @PreAuthorize("hasAuthority('ADMIN')") + public String showIndex() { + return "redirect:/adm/home/main"; + } + + // 관리자 메인페이지 + @GetMapping("/home/main") + @PreAuthorize("hasAuthority('ADMIN')") + public String showMain() { + return "adm/home/main"; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/home/controller/HomeController.java b/mutbooks/src/main/java/com/example/mutbooks/app/home/controller/HomeController.java new file mode 100644 index 0000000..d0d7acc --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/home/controller/HomeController.java @@ -0,0 +1,12 @@ +package com.example.mutbooks.app.home.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class HomeController { + @GetMapping("/") + public String showMain() { + return "home/main"; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/mail/service/MailService.java b/mutbooks/src/main/java/com/example/mutbooks/app/mail/service/MailService.java new file mode 100644 index 0000000..1f959e9 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/mail/service/MailService.java @@ -0,0 +1,75 @@ +package com.example.mutbooks.app.mail.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; + +@Service +@RequiredArgsConstructor +public class MailService { + private final JavaMailSender javaMailSender; + + public void sendJoinCongrats(String username, String email) { + // 수신 대상을 담을 ArrayList 생성 + ArrayList toUserList = new ArrayList<>(); + + // 수신 대상 추가 + toUserList.add(email); + + // 수신 대상 개수 + int toUserSize = toUserList.size(); + + // SimpleMailMessage (단순 텍스트 구성 메일 메시지 생성할 때 이용) + SimpleMailMessage simpleMessage = new SimpleMailMessage(); + + // 수신자 설정 + simpleMessage.setTo((String[]) toUserList.toArray(new String[toUserSize])); + + // 메일 제목 + String title = "[MUTBooks] %s 회원님 환영합니다.".formatted(username); + simpleMessage.setSubject(title); + + // 메일 내용 + String content = """ + %S 님의 MUTBooks 가입을 축하합니다. + """.formatted(username); + simpleMessage.setText(content); + + // 메일 발송 + javaMailSender.send(simpleMessage); + } + + // 임시 비밀번호 발급 메일 전송 + public void sendTempPassword(String username, String email, String tempPwd) { + // 수신 대상을 담을 ArrayList 생성 + ArrayList toUserList = new ArrayList<>(); + + // 수신 대상 추가 + toUserList.add(email); + + // 수신 대상 개수 + int toUserSize = toUserList.size(); + + // SimpleMailMessage (단순 텍스트 구성 메일 메시지 생성할 때 이용) + SimpleMailMessage simpleMessage = new SimpleMailMessage(); + + // 수신자 설정 + simpleMessage.setTo((String[]) toUserList.toArray(new String[toUserSize])); + + // 메일 제목 + String title = "[MUTBooks] 회원님의 임시 비밀번호입니다."; + simpleMessage.setSubject(title); + + // 메일 내용 + String content = """ + %S 님의 임시 비밀번호는 %s 입니다. + """.formatted(username, tempPwd); + simpleMessage.setText(content); + + // 메일 발송 + javaMailSender.send(simpleMessage); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/member/controller/MemberController.java b/mutbooks/src/main/java/com/example/mutbooks/app/member/controller/MemberController.java new file mode 100644 index 0000000..2d85d6c --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/member/controller/MemberController.java @@ -0,0 +1,219 @@ +package com.example.mutbooks.app.member.controller; + +import com.example.mutbooks.app.security.dto.MemberContext; +import com.example.mutbooks.app.mail.service.MailService; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.member.form.JoinForm; +import com.example.mutbooks.app.member.form.WithdrawAccountForm; +import com.example.mutbooks.app.member.form.ModifyForm; +import com.example.mutbooks.app.member.form.PwdModifyForm; +import com.example.mutbooks.app.member.service.MemberService; +import com.example.mutbooks.app.member.validator.PwdModifyFormValidator; +import lombok.RequiredArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; + +@Controller +@RequiredArgsConstructor +@RequestMapping("/member") +public class MemberController { + private final MemberService memberService; + private final MailService mailService; + private final PwdModifyFormValidator pwdModifyFormValidator; + + // 회원가입 폼 + @PreAuthorize("isAnonymous()") + @GetMapping("/join") + public String showJoin(JoinForm joinForm) { + return "member/join"; + } + + // 회원가입 + @PreAuthorize("isAnonymous()") + @PostMapping("/join") + public String join(@Valid JoinForm joinForm, BindingResult bindingResult, HttpServletRequest request) throws ServletException { + // 아이디 중복 검사 + Member oldMember = memberService.findByUsername(joinForm.getUsername()); + if (oldMember != null) { + bindingResult.rejectValue("username", "duplicated username", "중복된 아이디 입니다."); + return "member/join"; + } + // 이메일 중복 검사 + oldMember = memberService.findByEmail(joinForm.getEmail()); + if(oldMember != null) { + bindingResult.rejectValue("email", "duplicated email", "중복된 이메일 입니다."); + return "member/join"; + } + + Member member = memberService.join(joinForm); + // TODO: 테스트를 위해 잠시 주석 처리 + // 가입 축하 이메일 전송 +// mailService.sendJoinCongrats(member.getUsername(), member.getEmail()); + + // 회원가입 완료 후, 자동 로그인 처리 + try { + request.login(joinForm.getUsername(), joinForm.getPassword()); + } catch (ServletException e) { + throw new RuntimeException(e); + } + + return "redirect:/"; + } + + // 로그인 폼 + @PreAuthorize("isAnonymous()") + @GetMapping("/login") + public String showLogin() { + return "member/login"; + } + + // 회원정보 수정폼 + @PreAuthorize("isAuthenticated()") + @GetMapping("/modify") + public String showModify(@AuthenticationPrincipal MemberContext memberContext, ModifyForm modifyForm, Model model) { + Member member = memberContext.getMember(); + + model.addAttribute("member", member); + + return "member/modify"; + } + + // 회원정보 수정 + @PreAuthorize("isAuthenticated()") + @PostMapping("/modify") + public String modifyProfile(@AuthenticationPrincipal MemberContext memberContext, + @Valid ModifyForm modifyForm, BindingResult bindingResult) { + if(bindingResult.hasErrors()) { + return "member/modify"; + } + + Member member = memberService.findByUsername(memberContext.getUsername()); + memberService.modifyProfile(member, modifyForm); + + return "redirect:/member/profile"; + } + + // 비밀번호 수정폼 + @PreAuthorize("isAuthenticated()") + @GetMapping("/modifyPassword") + public String modifyPassword(PwdModifyForm pwdModifyForm) { + return "member/modify_password"; + } + + // 비밀번호 수정 + @PreAuthorize("isAuthenticated()") + @PostMapping("/modifyPassword") + public String modifyProfile(@AuthenticationPrincipal MemberContext memberContext, + @Valid PwdModifyForm pwdModifyForm, BindingResult bindingResult, + HttpServletRequest request) { + // 유효성 검증 추가 + pwdModifyFormValidator.validate(pwdModifyForm, bindingResult); + + if(bindingResult.hasErrors()) { + System.out.println("bindingResult = " + bindingResult.getErrorCount()); + return "member/modify_password"; + } + + Member member = memberService.findByUsername(memberContext.getUsername()); + memberService.modifyPassword(member, pwdModifyForm); + + // 강제 로그아웃 처리 후 로그인 페이지로 리다이렉트 + try { + request.logout(); + } catch (ServletException e) { + throw new RuntimeException(e); + } + return "redirect:/member/login"; + } + + // 회원정보 조회 + @PreAuthorize("isAuthenticated()") + @GetMapping("/profile") + public String showProfile(@AuthenticationPrincipal MemberContext memberContext, Model model) { + Member member = memberContext.getMember(); + + model.addAttribute("member", member); + + return "member/profile"; + } + + // 아이디 찾기 폼 + @PreAuthorize("isAnonymous") + @GetMapping("/findUsername") + public String showFindUsername() { + return "member/find_username"; + } + + // 이메일로 아이디 찾기 + @PreAuthorize("isAnonymous()") + @PostMapping("/findUsername") + public String findUsername(@Valid String email, Model model) { + Member member = memberService.findByEmail(email); + + model.addAttribute("member", member); + + return "member/confirm_username"; + } + + // 비밀번호 찾기 폼 + @PreAuthorize("isAnonymous") + @GetMapping("/findPassword") + public String showFindPassword() { + return "member/find_password"; + } + + // 아이디 + 이메일로 임시 비밀번호 발급하기 + @PreAuthorize("isAnonymous()") + @PostMapping("/findPassword") + public String findPassword(@Valid String username, String email, Model model) { + Member member = memberService.findByUsernameAndEmail(username, email); + + model.addAttribute("member", member); + + return "member/confirm_password"; + } + + // 출금 계좌 관리 + @PreAuthorize("isAuthenticated()") + @GetMapping("/manageWithdrawAccount") + public String manageWithdrawAccount(@AuthenticationPrincipal MemberContext memberContext, Model model) { + Member member = memberService.findByUsername(memberContext.getUsername()); + model.addAttribute("member", member); + + return "member/manage_withdraw_account"; + } + + // 출금 계좌 등록폼 + @PreAuthorize("isAuthenticated()") + @GetMapping("/registerWithdrawAccount") + public String showRegisterWithdrawAccount(WithdrawAccountForm withDrawAccountForm) { + return "member/register_withdraw_account"; + } + + // 출금 계좌 등록 + @PreAuthorize("isAuthenticated()") + @PostMapping("/registerWithdrawAccount") + public String registerWithdrawAccount( + @AuthenticationPrincipal MemberContext memberContext, + @Valid WithdrawAccountForm withDrawAccountForm, BindingResult bindingResult + ) { + if(bindingResult.hasErrors()) { + return "member/register_withdraw_account"; + } + Member member = memberService.findByUsername(memberContext.getUsername()); + memberService.createBankInfo(member, withDrawAccountForm); + + // 출금 게좌 관리 페이지로 리다이렉트 + return "redirect:/member/manageWithdrawAccount"; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/AuthLevel.java b/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/AuthLevel.java new file mode 100644 index 0000000..52f5be4 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/AuthLevel.java @@ -0,0 +1,27 @@ +package com.example.mutbooks.app.member.entity; + +import lombok.Getter; + +import java.util.Arrays; + +@Getter +public enum AuthLevel { + USER(3, "USER"), + ADMIN(7, "ADMIN"); + + private final int code; + private final String value; + + AuthLevel(int code, String value) { + this.code = code; + this.value = value; + } + + // Enum 에서 code 값으로 해당 Enum 을 찾는 메서드 + public static AuthLevel ofCode(Integer code) { + return Arrays.stream(AuthLevel.values()) + .filter(v -> v.getCode() == code) + .findFirst() + .orElseThrow(() -> new RuntimeException(String.format("code=[%d]가 존재하지 않습니다.", code))); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/AuthLevelConverter.java b/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/AuthLevelConverter.java new file mode 100644 index 0000000..97a8fe7 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/AuthLevelConverter.java @@ -0,0 +1,28 @@ +package com.example.mutbooks.app.member.entity; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; + +/** + * AttributeConverter X, Y + * X : 엔티티의 속성에 대응하는 타입 + * Y : DB 에 대응하는 타입 + */ +@Converter +public class AuthLevelConverter implements AttributeConverter { + + // Enum -> db 데이터(code:Integer) + @Override + public Integer convertToDatabaseColumn(AuthLevel attribute) { + if(attribute == null) + return null; + + return attribute.getCode(); + } + + // db 데이터(code:Integer) -> Enum + @Override + public AuthLevel convertToEntityAttribute(Integer dbData) { + return AuthLevel.ofCode(dbData); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java b/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java new file mode 100644 index 0000000..a2ea20e --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/Member.java @@ -0,0 +1,100 @@ +package com.example.mutbooks.app.member.entity; + +import com.example.mutbooks.app.base.entity.BaseEntity; +import com.example.mutbooks.util.Ut; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.*; +import lombok.experimental.SuperBuilder; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.util.StringUtils; + +import javax.persistence.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@Entity +@Getter +@Setter +@SuperBuilder +@AllArgsConstructor +@NoArgsConstructor +@ToString(callSuper = true) +public class Member extends BaseEntity { + @Column(unique = true) + private String username; + @JsonIgnore + private String password; + private String nickname; + @Column(unique = true) + private String email; + + @Convert(converter = AuthLevelConverter.class) + private AuthLevel authLevel; // 권한레벨(3 = 일반, 7 = 관리자) + + private int restCash; // 예치금 + + // accessToken + @Column(columnDefinition = "TEXT") + private String accessToken; + + // Member 의 memberExtra 에 값이 저장될 때, MemberExtra 도 같이 저장되도록 + @OneToOne(mappedBy = "member", cascade = CascadeType.ALL) + private MemberExtra memberExtra; + + // 비밀번호 수정 + public void modifyPassword(String newPassword) { + this.password = newPassword; + } + + // 기본정보 수정 + public void modifyInfo(String email, String nickname) { + this.email = email; + this.nickname = nickname; + } + + // 추가정보 수정 + public void modifyMemberExtra(MemberExtra memberExtra) { + this.memberExtra = memberExtra; + } + + // 출금 계좌 정보 등록 여부 + public boolean hasBankInfo() { + if(memberExtra == null) return false; + if(memberExtra.getBankName() == null) return false; + if(memberExtra.getBankAccountNo() == null) return false; + return true; + } + + // 권한 부여 + public List getAuthorities() { + List authorities = new ArrayList<>(); + // 모든 로그인한 회원에게는 USER 권한 부여 + authorities.add(new SimpleGrantedAuthority(AuthLevel.USER.getValue())); // 일반 회원 + + // nickname 이 있으면 AUTHOR 권한 부여 + if (StringUtils.hasText(nickname)) { + authorities.add(new SimpleGrantedAuthority("AUTHOR")); // 작가 회원 + } + + // authLevel 이 7이면 ADMIN 권한 부여 + if (this.authLevel == AuthLevel.ADMIN) { + authorities.add(new SimpleGrantedAuthority(AuthLevel.ADMIN.getValue())); // 관리자 회원 + } + + return authorities; + } + + // AccessToken 발급을 위해 회원 정보를 바탕으로 claim map 객체 만들어 반환 + public Map getAccessTokenClaims() { + return Ut.mapOf( + "id", getId(), + "createDate", getCreateDate(), + "updateDate", getUpdateDate(), + "username", getUsername(), + "email", getEmail(), + "authorities", getAuthorities() + ); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/MemberExtra.java b/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/MemberExtra.java new file mode 100644 index 0000000..a15f8e2 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/member/entity/MemberExtra.java @@ -0,0 +1,23 @@ +package com.example.mutbooks.app.member.entity; + +import com.example.mutbooks.app.base.entity.BaseEntity; +import lombok.*; +import lombok.experimental.SuperBuilder; + +import javax.persistence.Entity; +import javax.persistence.OneToOne; + +@Entity +@Getter +@Setter +@SuperBuilder +@AllArgsConstructor +@NoArgsConstructor +@ToString(callSuper = true) +public class MemberExtra extends BaseEntity { + @OneToOne + private Member member; // 관련 회원 + + private String bankName; // 출금 은행명 + private String bankAccountNo; // 출금 계좌번호 +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/member/exception/PasswordNotMatchedException.java b/mutbooks/src/main/java/com/example/mutbooks/app/member/exception/PasswordNotMatchedException.java new file mode 100644 index 0000000..974019e --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/member/exception/PasswordNotMatchedException.java @@ -0,0 +1,7 @@ +package com.example.mutbooks.app.member.exception; + +public class PasswordNotMatchedException extends RuntimeException { + public PasswordNotMatchedException(String message) { + super(message); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/member/form/JoinForm.java b/mutbooks/src/main/java/com/example/mutbooks/app/member/form/JoinForm.java new file mode 100644 index 0000000..3ffc53b --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/member/form/JoinForm.java @@ -0,0 +1,26 @@ +package com.example.mutbooks.app.member.form; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.Size; + +@Data +@AllArgsConstructor +public class JoinForm { + @Size(min = 5, max = 20, message = "id는 5 ~ 20자리로 입력해주세요.") + @NotEmpty(message = "아이디를 입력해주세요.") + private String username; + + @Size(min = 8, max = 16, message = "비밀번호는 8 ~ 16자리로 입력해주세요.") + @NotEmpty(message = "비밀번호를 입력해주세요.") + private String password; + + private String nickname; + + @Email(message = "이메일 형식이 올바르지 않습니다.") + @NotEmpty(message = "이메일을 입력해주세요.") + private String email; +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/member/form/ModifyForm.java b/mutbooks/src/main/java/com/example/mutbooks/app/member/form/ModifyForm.java new file mode 100644 index 0000000..e35de3f --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/member/form/ModifyForm.java @@ -0,0 +1,17 @@ +package com.example.mutbooks.app.member.form; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotEmpty; + +@Data +@AllArgsConstructor +public class ModifyForm { + private String nickname; + + @Email(message = "이메일 형식이 올바르지 않습니다.") + @NotEmpty(message = "이메일을 입력해주세요.") + private String email; +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/member/form/PwdModifyForm.java b/mutbooks/src/main/java/com/example/mutbooks/app/member/form/PwdModifyForm.java new file mode 100644 index 0000000..9b56121 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/member/form/PwdModifyForm.java @@ -0,0 +1,24 @@ +package com.example.mutbooks.app.member.form; + +import lombok.Getter; +import lombok.Setter; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.Size; + +@Getter +@Setter +public class PwdModifyForm { + //TODO: 테스트 편의를 위해 잠시 주석처리 + //@Size(min = 8, max = 16, message = "비밀번호는 8 ~ 16자리로 입력해주세요.") + @NotEmpty(message = "현재 비밀번호를 입력해주세요.") + private String password; // 현재 비밀번호 + + @Size(min = 8, max = 16, message = "비밀번호는 8 ~ 16자리로 입력해주세요.") + @NotEmpty(message = "새 비밀번호를 입력해주세요.") + private String newPassword; // 새 비밀번호 + + @Size(min = 8, max = 16, message = "비밀번호는 8 ~ 16자리로 입력해주세요.") + @NotEmpty(message = "새 비밀번호 확인을 입력해주세요.") + private String newPasswordConfirm; // 새 비밀번호 확인 +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/member/form/WithdrawAccountForm.java b/mutbooks/src/main/java/com/example/mutbooks/app/member/form/WithdrawAccountForm.java new file mode 100644 index 0000000..cf74132 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/member/form/WithdrawAccountForm.java @@ -0,0 +1,15 @@ +package com.example.mutbooks.app.member.form; + +import lombok.Getter; +import lombok.Setter; + +import javax.validation.constraints.NotBlank; + +@Getter +@Setter +public class WithdrawAccountForm { + @NotBlank(message = "은행을 선택해주세요.") + private String bankName; // 은행명 + @NotBlank(message = "계좌번호를 입력해주세요.") + private String bankAccountNo; // 계좌번호 +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/member/repository/MemberRepository.java b/mutbooks/src/main/java/com/example/mutbooks/app/member/repository/MemberRepository.java new file mode 100644 index 0000000..0c02e32 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/member/repository/MemberRepository.java @@ -0,0 +1,14 @@ +package com.example.mutbooks.app.member.repository; + +import com.example.mutbooks.app.member.entity.Member; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface MemberRepository extends JpaRepository { + Optional findByUsername(String username); + + Optional findByEmail(String email); + + Optional findByUsernameAndEmail(String username, String email); +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java b/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java new file mode 100644 index 0000000..955b536 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/member/service/MemberService.java @@ -0,0 +1,185 @@ +package com.example.mutbooks.app.member.service; + +import com.example.mutbooks.app.cash.entity.CashLog; +import com.example.mutbooks.app.cash.service.CashService; +import com.example.mutbooks.app.mail.service.MailService; +import com.example.mutbooks.app.member.entity.AuthLevel; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.member.entity.MemberExtra; +import com.example.mutbooks.app.member.exception.PasswordNotMatchedException; +import com.example.mutbooks.app.member.form.JoinForm; +import com.example.mutbooks.app.member.form.ModifyForm; +import com.example.mutbooks.app.member.form.PwdModifyForm; +import com.example.mutbooks.app.member.form.WithdrawAccountForm; +import com.example.mutbooks.app.member.repository.MemberRepository; +import com.example.mutbooks.app.security.dto.MemberContext; +import com.example.mutbooks.app.security.jwt.JwtProvider; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.Map; +import java.util.UUID; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class MemberService { + private final MemberRepository memberRepository; + private final PasswordEncoder passwordEncoder; + private final MailService mailService; + private final CashService cashService; + private final JwtProvider jwtProvider; + + @Transactional + public Member join(JoinForm joinForm) { + AuthLevel authLevel = AuthLevel.USER; // 디폴트 USER 권한 + // username 이 admin 인 회원을 관리자 회원으로 설정 + if(joinForm.getUsername().equals("admin")) { + authLevel = AuthLevel.ADMIN; + } + + // 기본 권한 = 일반 + Member member = Member.builder() + .username(joinForm.getUsername()) + .password(passwordEncoder.encode(joinForm.getPassword())) + .email(joinForm.getEmail()) + .nickname(joinForm.getNickname()) + .authLevel(authLevel) + .build(); + + memberRepository.save(member); + + return member; + } + + // 회원기본 정보 수정 + @Transactional + public void modifyProfile(Member member, ModifyForm modifyForm) { + // TODO : 작가->일반 회원 될 수 있는지 고민(글 작성자 이름 표시 문제) + member.modifyInfo(modifyForm.getEmail(), modifyForm.getNickname().trim()); + + forceAuthentication(member); + } + + // 세션에 담긴 회원 기본정보 강제 수정 + public void forceAuthentication(Member member) { + MemberContext memberContext = new MemberContext(member, member.getAuthorities()); + + UsernamePasswordAuthenticationToken authentication = + UsernamePasswordAuthenticationToken.authenticated( + memberContext, + member.getPassword(), + memberContext.getAuthorities() + ); + SecurityContext context = SecurityContextHolder.createEmptyContext(); + context.setAuthentication(authentication); + SecurityContextHolder.setContext(context); + } + + // 이메일로 아이디 조회 + public Member findByEmail(String email) { + return memberRepository.findByEmail(email).orElse(null); + } + + // 아이디로 회원조회 + public Member findByUsername(String username) { + return memberRepository.findByUsername(username).orElse(null); + } + + // 아이디 + 이메일 회원 조회 + @Transactional + public Member findByUsernameAndEmail(String username, String email) { + Member member = memberRepository.findByUsernameAndEmail(username, email).orElse(null); + // 임시 비번 발급 후, 비밀번호 업데이트 + if(member != null) { + // 1. 임시 비밀번호 생성(UUID이용) + String tempPwd= UUID.randomUUID().toString().replace("-", "");//-를 제거 + tempPwd = tempPwd.substring(0,10); //tempPwd를 앞에서부터 10자리 잘라줌 + // 2. 메일 전송 + mailService.sendTempPassword(username, email, tempPwd); + // 3. 회원 비밀번호 -> 임시 비밀번호로 변경 + modifyPassword(member, tempPwd); + } + return member; + } + + @Transactional + public void modifyPassword(Member member, String password) { + String newPassword = passwordEncoder.encode(password); + member.modifyPassword(newPassword); + } + + // 비밀번호 수정 + @Transactional + public void modifyPassword(Member member, PwdModifyForm pwdModifyForm) { + // 기존 비밀번호가 맞는지 검증 후 수정 + if(!passwordEncoder.matches(pwdModifyForm.getPassword(), member.getPassword())) { + throw new PasswordNotMatchedException("기존 비밀번호와 일치하지 않습니다."); + } + + String newPassword = passwordEncoder.encode(pwdModifyForm.getNewPassword()); + member.modifyPassword(newPassword); + } + + // 회원의 남은 예치금 잔액 조회 + public int getRestCash(Member member) { + return findByUsername(member.getUsername()).getRestCash(); + } + + // 예치금 변동(넣기, 빼기) + @Transactional + public CashLog addCash(Member member, int price, String eventType) { + CashLog cashLog = cashService.addCash(member, price, eventType); + + // 예치금 변동 금액 반영 + int newRestCash = member.getRestCash() + cashLog.getPrice(); + member.setRestCash(newRestCash); + memberRepository.save(member); + // TODO: 관리자 회원이 정산 처리를 할 경우, 정산 대상 회원으로 강제 로그인 되는 문제때문에 잠시 주석 처리 + // addCash() 를 사용하는 메서드 내에서 forceAuthentication()을 호출해야하는지 고민해보기 + // 세션값 강제 수정 + //forceAuthentication(member); + + return cashLog; + } + + // 계좌 등록 + @Transactional + public void createBankInfo(Member member, WithdrawAccountForm withDrawAccountForm) { + MemberExtra memberExtra = MemberExtra.builder() + .member(member) + .bankName(withDrawAccountForm.getBankName()) + .bankAccountNo(withDrawAccountForm.getBankAccountNo()) + .build(); + member.modifyMemberExtra(memberExtra); + // TODO: 계좌 정보는 memberContext 값에 담겨있지 않으므로 세션값 강제 수정할 필요X + //forceAuthentication(member); + } + + // AccessToken 발급(발급된게 있으면 바로 리턴) + @Transactional + public String genAccessToken(Member member) { + // 1. DB에서 AccessToken 조회 + String accessToken = member.getAccessToken(); + // 2. 만료시, 토큰 새로 발급 + if (StringUtils.hasLength(accessToken) == false) { + // 지금으로부터 100년간의 유효기간을 가지는 토큰을 생성, DB에 토큰 저장 + Map claims = member.getAccessTokenClaims(); + accessToken = jwtProvider.generateAccessToken(claims); + member.setAccessToken(accessToken); + } + + return accessToken; + } + + // 해당 토큰이 화이트 리스트에 있는지 검증 + public boolean verifyWithWhiteList(Member member, String token) { + return member.getAccessToken().equals(token); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/member/validator/PwdModifyFormValidator.java b/mutbooks/src/main/java/com/example/mutbooks/app/member/validator/PwdModifyFormValidator.java new file mode 100644 index 0000000..0e02b4f --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/member/validator/PwdModifyFormValidator.java @@ -0,0 +1,26 @@ +package com.example.mutbooks.app.member.validator; + +import com.example.mutbooks.app.member.form.PwdModifyForm; +import org.springframework.stereotype.Component; +import org.springframework.validation.Errors; +import org.springframework.validation.Validator; + +@Component +public class PwdModifyFormValidator implements Validator { + @Override + public boolean supports(Class clazz) { + return PwdModifyForm.class.isAssignableFrom(clazz); + } + + @Override + public void validate(Object target, Errors errors) { + PwdModifyForm pwdModifyForm = (PwdModifyForm) target; + if(!pwdModifyForm.getNewPassword().equals(pwdModifyForm.getNewPasswordConfirm())) { + errors.rejectValue("newPasswordConfirm", "notMatchNewPasswordAndNewPasswordConfirm", "입력한 새 비밀번호가 일치하지 않습니다."); + } + + if(pwdModifyForm.getNewPassword().equals(pwdModifyForm.getPassword())) { + errors.rejectValue("newPassword", "samePassword", "기존 비밀번호와 일치합니다."); + } + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDetailDto.java b/mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDetailDto.java new file mode 100644 index 0000000..58d82e3 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDetailDto.java @@ -0,0 +1,36 @@ +package com.example.mutbooks.app.mybook.dto.response; + +import com.example.mutbooks.app.mybook.entity.MyBook; +import com.example.mutbooks.app.post.entity.Post; +import com.example.mutbooks.app.product.dto.response.ProductDetailDto; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; +import java.util.List; + +@Getter +@Setter +@Builder +@AllArgsConstructor +public class MyBookDetailDto { + private Long id; + private LocalDateTime createDate; + private LocalDateTime modifyDate; + private Long ownerId; + private ProductDetailDto product; + + public static MyBookDetailDto toDto(MyBook myBook, List posts) { + ProductDetailDto productDetailDto = ProductDetailDto.toDto(myBook.getProduct(), posts); + + return MyBookDetailDto.builder() + .id(myBook.getId()) + .createDate(myBook.getCreateDate()) + .modifyDate(myBook.getUpdateDate()) + .ownerId(myBook.getOwner().getId()) + .product(productDetailDto) + .build(); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDto.java b/mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDto.java new file mode 100644 index 0000000..e07b4e4 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/mybook/dto/response/MyBookDto.java @@ -0,0 +1,34 @@ +package com.example.mutbooks.app.mybook.dto.response; + +import com.example.mutbooks.app.mybook.entity.MyBook; +import com.example.mutbooks.app.product.dto.response.ProductDto; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@Builder +@AllArgsConstructor +public class MyBookDto { + private Long id; + private LocalDateTime createDate; + private LocalDateTime modifyDate; + private Long ownerId; + private ProductDto product; + + public static MyBookDto toDto(MyBook myBook) { + ProductDto productDto = ProductDto.toDto(myBook.getProduct()); + + return MyBookDto.builder() + .id(myBook.getId()) + .createDate(myBook.getCreateDate()) + .modifyDate(myBook.getUpdateDate()) + .ownerId(myBook.getOwner().getId()) + .product(productDto) + .build(); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/mybook/entity/MyBook.java b/mutbooks/src/main/java/com/example/mutbooks/app/mybook/entity/MyBook.java new file mode 100644 index 0000000..bda2be4 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/mybook/entity/MyBook.java @@ -0,0 +1,29 @@ +package com.example.mutbooks.app.mybook.entity; + +import com.example.mutbooks.app.base.entity.BaseEntity; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.product.entity.Product; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.SuperBuilder; + +import javax.persistence.*; + +@Entity +@Getter +@Setter +@SuperBuilder +@NoArgsConstructor +@ToString(callSuper = true) +@Table(indexes = @Index(name="idx__owner_id__product_id", columnList = "owner_id, product_id")) +public class MyBook extends BaseEntity { + @ManyToOne(fetch = FetchType.LAZY) + private Member owner; // 소유주 + + @ManyToOne(fetch = FetchType.LAZY) + private Product product; // 상품 + + private boolean isRead; // 읽었는지 여부 +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/mybook/exception/MyBookNotFoundException.java b/mutbooks/src/main/java/com/example/mutbooks/app/mybook/exception/MyBookNotFoundException.java new file mode 100644 index 0000000..9a33311 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/mybook/exception/MyBookNotFoundException.java @@ -0,0 +1,7 @@ +package com.example.mutbooks.app.mybook.exception; + +public class MyBookNotFoundException extends RuntimeException { + public MyBookNotFoundException(String message) { + super(message); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/mybook/repository/MyBookRepository.java b/mutbooks/src/main/java/com/example/mutbooks/app/mybook/repository/MyBookRepository.java new file mode 100644 index 0000000..3d90f54 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/mybook/repository/MyBookRepository.java @@ -0,0 +1,18 @@ +package com.example.mutbooks.app.mybook.repository; + +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.mybook.entity.MyBook; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; +import java.util.Optional; + +public interface MyBookRepository extends JpaRepository { + Optional findByProductIdAndOwnerId(Long productId, Long ownerId); + + void deleteByProductIdAndOwnerId(Long productId, Long ownerId); + + List findByOwner(Member owner); + + Optional findByIdAndOwnerId(long myBookId, long ownerId); +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java b/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java new file mode 100644 index 0000000..22feec4 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/mybook/service/MyBookService.java @@ -0,0 +1,98 @@ +package com.example.mutbooks.app.mybook.service; + +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.mybook.dto.response.MyBookDetailDto; +import com.example.mutbooks.app.mybook.dto.response.MyBookDto; +import com.example.mutbooks.app.mybook.entity.MyBook; +import com.example.mutbooks.app.mybook.exception.MyBookNotFoundException; +import com.example.mutbooks.app.mybook.repository.MyBookRepository; +import com.example.mutbooks.app.order.entity.Order; +import com.example.mutbooks.app.order.entity.OrderItem; +import com.example.mutbooks.app.post.entity.Post; +import com.example.mutbooks.app.postHashTag.entity.PostHashTag; +import com.example.mutbooks.app.postHashTag.service.PostHashTagService; +import com.example.mutbooks.app.postKeyword.entity.PostKeyword; +import com.example.mutbooks.app.product.entity.Product; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class MyBookService { + private final MyBookRepository myBookRepository; + private final PostHashTagService postHashTagService; + + // MyBook 추가 + @Transactional + public void add(Order order) { + for(OrderItem orderItem : order.getOrderItems()) { + Product product = orderItem.getProduct(); + Member buyer = order.getBuyer(); + + MyBook oldMyBook = myBookRepository.findByProductIdAndOwnerId(product.getId(), buyer.getId()) + .orElse(null); + // (ownerId + productId) DB에 없을 때만 저장(중복 저장 막기) + if(oldMyBook == null) { + MyBook myBook = MyBook.builder() + .owner(buyer) + .product(product) + .build(); + + myBookRepository.save(myBook); + } + } + } + + // MyBook 삭제 + @Transactional + public void remove(Order order) { + for(OrderItem orderItem : order.getOrderItems()) { + Product product = orderItem.getProduct(); + Member buyer = order.getBuyer(); + + myBookRepository.deleteByProductIdAndOwnerId(product.getId(), buyer.getId()); + } + } + + public MyBook findByProductIdAndOwnerId(long productId, long ownerId) { + return myBookRepository.findByProductIdAndOwnerId(productId, ownerId).orElse(null); + } + + public List findAllByOwner(Member owner) { + List myBooks = myBookRepository.findByOwner(owner); + + List myBookDtos = myBooks.stream() + .map(myBook -> MyBookDto.toDto(myBook)) + .collect(Collectors.toList()); + + return myBookDtos; + } + + public MyBook findByIdAndOwnerId(long myBookId, long ownerId) { + return myBookRepository.findByIdAndOwnerId(myBookId, ownerId).orElseThrow(() -> { + throw new MyBookNotFoundException("해당 상품 구매 이력이 존재하지 않습니다."); + }); + } + + public MyBookDetailDto findByIdForDetail(long myBookId, long ownerId) { + // 본인이 소유한 도서로 조회 + MyBook myBook = findByIdAndOwnerId(myBookId, ownerId); + + PostKeyword postKeyword = myBook.getProduct().getPostKeyword(); + Member author = myBook.getProduct().getAuthor(); + + // 해당 작가, 키워드와 관련된 글만 조회 + List postHashTags = postHashTagService.findByPostKeywordAndMember(postKeyword, author); + + List posts = postHashTags.stream() + .map(postHashTag -> postHashTag.getPost()) + .collect(Collectors.toList()); + + return MyBookDetailDto.toDto(myBook, posts); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/order/controller/OrderController.java b/mutbooks/src/main/java/com/example/mutbooks/app/order/controller/OrderController.java new file mode 100644 index 0000000..0684414 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/order/controller/OrderController.java @@ -0,0 +1,236 @@ +package com.example.mutbooks.app.order.controller; + +import com.example.mutbooks.app.security.dto.MemberContext; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.member.service.MemberService; +import com.example.mutbooks.app.order.entity.Order; +import com.example.mutbooks.app.order.exception.OrderIdNotMatchedException; +import com.example.mutbooks.app.order.exception.PaymentFailByInsufficientCashException; +import com.example.mutbooks.app.order.service.OrderService; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.*; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.client.ResponseErrorHandler; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.server.ResponseStatusException; + +import javax.annotation.PostConstruct; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequiredArgsConstructor +@RequestMapping("/order") +public class OrderController { + private final OrderService orderService; + private final MemberService memberService; + private final RestTemplate restTemplate; + private final ObjectMapper objectMapper; // Ut + + // 주문 생성 + @PreAuthorize("isAuthenticated()") + @PostMapping("/create") + public String createOrder(@AuthenticationPrincipal MemberContext memberContext, String ids) { + Member buyer = memberContext.getMember(); + + Order order = orderService.createOrder(buyer, ids); + + // 주문 상세 페이지로 리다이렉트 + return "redirect:/order/%d".formatted(order.getId()); + } + + // 내 주문 리스트 조회 + @PreAuthorize("isAuthenticated()") + @GetMapping("/list") + public String list(@AuthenticationPrincipal MemberContext memberContext, Model model) { + Member buyer = memberContext.getMember(); + List orders = orderService.findByBuyer(buyer); + + model.addAttribute("orders", orders); + + return "order/list"; + } + + // 주문 상세조회 + @PreAuthorize("isAuthenticated()") + @GetMapping("/{id}") + public String detail(@PathVariable long id, @AuthenticationPrincipal MemberContext memberContext, Model model) { + Order order = orderService.findById(id); + Member member = memberContext.getMember(); + long restCash = memberService.getRestCash(member); + + // TODO: 예외 처리 + // 주문 조회 권한 검사 + if(orderService.canSelect(member, order) == false) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } + model.addAttribute("order", order); + model.addAttribute("restCash", restCash); + + return "order/detail"; + } + + // 주문 취소 + @PreAuthorize("isAuthenticated()") + @PostMapping("/{id}/cancel") + public String cancel(@PathVariable long id, @AuthenticationPrincipal MemberContext memberContext) { + Order order = orderService.findById(id); + Member member = memberContext.getMember(); + + if(!order.isCancellable()) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } + + if(orderService.canCancel(member, order) == false) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } + orderService.cancel(order); + + // 주문 내역 페이지로 리다이렉트 + return "redirect:/order/list"; + } + + // 캐시 전액 결제 + @PreAuthorize("isAuthenticated()") + @PostMapping("/{id}/pay") + public String payByRestCashOnly(@AuthenticationPrincipal MemberContext memberContext, @PathVariable long id){ + Order order = orderService.findById(id); + Member member = memberContext.getMember(); + int restCash = memberService.getRestCash(member); + + // 보유 캐시 < 결제 금액, 예외처리 + if(restCash < order.calcPayPrice()) { + throw new PaymentFailByInsufficientCashException("보유 캐시 금액보다 사용 캐시 금액이 더 많습니다."); + } + + if(!order.isPayable()) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } + + if(orderService.canPayment(member, order) == false) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } + + orderService.payByRestCashOnly(order); + + return "redirect:/order/%d".formatted(order.getId()); + } + + // 캐시 전액 환불 처리 + @PreAuthorize("isAuthenticated()") + @PostMapping("/{id}/refund") + public String refund(@PathVariable long id, @AuthenticationPrincipal MemberContext memberContext) { + Order order = orderService.findById(id); + Member member = memberContext.getMember(); + + if(orderService.canRefund(member, order) == false) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } + + orderService.refundByRestCashOnly(order); + + return "redirect:/order/%d".formatted(id); + } + + + // Toss Payments 시작 + @PostConstruct + private void init() { + restTemplate.setErrorHandler(new ResponseErrorHandler() { + @Override + public boolean hasError(ClientHttpResponse response) { + return false; + } + + @Override + public void handleError(ClientHttpResponse response) { + } + }); + } + + @Value("${custom.tossPayments.secretKey}") + private String SECRET_KEY; + + // 결제 성공 리다이렉트 URL + @RequestMapping("/{id}/success") + public String confirmPayment( + @PathVariable long id, // orderId + @RequestParam String paymentKey, // 결제 건에 대한 고유한 키 값 + @RequestParam String orderId, // 상점에서 주문 건 구분을 위해 발급한 고유ID + @RequestParam Integer amount, // 실 결제 금액 + Model model, + @AuthenticationPrincipal MemberContext memberContext + ) throws Exception { + // TODO: id 와 orderId 무결성 검증하는 이유 + Order order = orderService.findById(id); + long realOrderId = Long.parseLong(orderId.split("__")[1]); + + if(id != realOrderId) { + throw new OrderIdNotMatchedException(""); + } + + HttpHeaders headers = new HttpHeaders(); + // headers.setBasicAuth(SECRET_KEY, ""); // spring framework 5.2 이상 버전에서 지원 + headers.set("Authorization", "Basic " + Base64.getEncoder().encodeToString((SECRET_KEY + ":").getBytes())); + headers.setContentType(MediaType.APPLICATION_JSON); + + Map payloadMap = new HashMap<>(); + payloadMap.put("orderId", orderId); + payloadMap.put("amount", String.valueOf(amount)); + + // 주문 금액 검증 로직 추가 + Member member = memberContext.getMember(); + int restCash = memberService.getRestCash(member); // 보유 캐시 + // 캐시 결제 금액 = 결제 금액 - pg 결제 금액 + int cashPayPrice = order.calcPayPrice() - amount; + // 캐시 결제 금액 > 보유 캐시 이면, 캐시 부족 예외 + if(cashPayPrice > restCash) { + throw new PaymentFailByInsufficientCashException("보유 캐시 금액보다 사용 캐시 금액이 더 많습니다."); + } + + // 1. 결제 승인 API 요청 + HttpEntity request = new HttpEntity<>(objectMapper.writeValueAsString(payloadMap), headers); + + ResponseEntity responseEntity = restTemplate.postForEntity( + "https://api.tosspayments.com/v1/payments/" + paymentKey, request, JsonNode.class); + + // 2. 응답받은 승인 결과가 성공이면 결제완료 처리 + if (responseEntity.getStatusCode() == HttpStatus.OK) { + // 2-1. 결제 완료 처리(캐시, 카드 결제 CashLog 기록 남기기) + orderService.payByTossPayments(order, cashPayPrice); + + // 2-2. 주문 상세조회로 리다이렉트 + return "redirect:/order/%d".formatted(order.getId()); + } else { + JsonNode failNode = responseEntity.getBody(); + model.addAttribute("message", failNode.get("message").asText()); + model.addAttribute("code", failNode.get("code").asText()); + return "order/fail"; + } + } + + // 결제 실패 리다패렉트 URL + @RequestMapping("/{id}/fail") + public String failPayment( + @RequestParam String message, // 에러 메시지 + @RequestParam String code, // 에러 코드 + @RequestParam String orderId, // 상점에서 주문 건 구분을 위해 발급한 고유ID + Model model) { + model.addAttribute("message", message); + model.addAttribute("code", code); + model.addAttribute("orderId", orderId); + + return "order/fail"; + } + // Toss Payments 끝 +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/order/entity/Order.java b/mutbooks/src/main/java/com/example/mutbooks/app/order/entity/Order.java new file mode 100644 index 0000000..b560b33 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/order/entity/Order.java @@ -0,0 +1,190 @@ +package com.example.mutbooks.app.order.entity; + +import com.example.mutbooks.app.base.entity.BaseEntity; +import com.example.mutbooks.app.member.entity.Member; +import lombok.*; +import lombok.experimental.SuperBuilder; + +import javax.persistence.*; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Setter +@SuperBuilder +@NoArgsConstructor +@ToString(callSuper = true) +@Table(name = "product_order") +public class Order extends BaseEntity { + @ManyToOne(fetch = FetchType.LAZY) + private Member buyer; // 구매자 + + private String name; // 주문명 + + private LocalDateTime payDate; // 결제 일시 + private LocalDateTime cancelDate; // 주문 취소 일시 + private LocalDateTime refundDate; // 환불 일시 + + private int payPrice; // 총 주문 결제 금액 + private int pgPayPrice; // 총 pg 결제 금액 + private int cashPayPrice; // 총 캐시 결제 금액 + + private boolean readyStatus; // 주문완료 여부 + private boolean isPaid; // 결제완료 여부 + private boolean isCanceled; // 주문취소 여부 + private boolean isRefunded; // 환불 여부 + + + @Builder.Default + @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true) + private List orderItems = new ArrayList<>(); // 주문 품목 리스트 + + // 해당 주문에 주문 품목 추가 + public void addOrderItem(OrderItem orderItem) { + // 주문 품목이 속해있는 주문 지정 + orderItem.setOrder(this); + orderItems.add(orderItem); + } + + // 주문명 네이밍 + public void makeName() { + String name = orderItems.get(0).getProduct().getSubject(); + // 2건 이상일 경우 1번 주문 품목 제목 외 ?건 형식으로 + if(orderItems.size() > 1) { + name += " 외 %d개".formatted(orderItems.size() - 1); + } + this.name = name; + } + + // 주문 완료 처리 + public void setOrderDone() { + this.readyStatus = true; + } + + // 주문 취소 처리 + public void setCancelDone() { + this.cancelDate = LocalDateTime.now(); + this.isCanceled = true; + // TODO: 주문완료 여부를 false 로 다시 바꾸는게 맞는지 + this.readyStatus = false; + } + + // 캐시 전액 결제 완료 처리 + public void setPaymentDone(int payPrice) { + this.payDate = LocalDateTime.now(); + // 총 결제 금액 == 캐시 결제 금액 + this.payPrice = payPrice; + this.cashPayPrice = payPrice; + // 주문 품목 결제 완료 처리 + for(OrderItem orderItem : orderItems) { + orderItem.setPaymentDone(); + } + this.isPaid = true; + } + + // TossPayments 결제 완료 처리 + public void setPaymentDone(int payPrice, int pgPayPrice) { + this.payDate = LocalDateTime.now(); + // 총 결제 금액 == pg 결제 금액 + 캐시 결제 금액 + this.payPrice = payPrice; + this.pgPayPrice = pgPayPrice; + this.cashPayPrice = payPrice - pgPayPrice; + // 주문 품목 결제 완료 처리 + for(OrderItem orderItem : orderItems) { + orderItem.setPaymentDone(); + } + this.isPaid = true; + } + + // 환불 완료 처리 + public void setRefundDone() { + this.refundDate = LocalDateTime.now(); + // 주문 품목 환불 완료 처리 + for(OrderItem orderItem : orderItems) { + orderItem.setRefundDone(); + } + this.isRefunded = true; + } + + // 총 주문(상품) 금액 + public int calcPayPrice() { + // 상품들의 실제 판매가의 총합 + int payPrice = 0; + for(OrderItem orderItem : orderItems) { + payPrice += orderItem.getSalePrice(); + } + return payPrice; + } + + // 주문 취소 가능 여부 + public boolean isCancellable() { + if(!readyStatus) return false; + if(isPaid) return false; + + return true; + } + + // 결제 가능 여부 + public boolean isPayable() { + if(!readyStatus) return false; + if(isPaid) return false; + if(isCanceled) return false; + + return true; + } + + // 환불 가능 여부 + public boolean isRefundable() { + if(!isPaidStatus()) return false; + if(isAfterRefundDeadline()) return false; + return true; + } + + // 환불 기한이 지났는지 여부 + public boolean isAfterRefundDeadline() { + if(payDate != null) { + // 현재 일시가 결제 일시보다 10분 이후이면 + LocalDateTime refundDeadline = payDate.plusMinutes(10); // 환불 마감 기한 + if(LocalDateTime.now().isAfter(refundDeadline)) return true; + } + return false; + } + + // 주문 완료 상태 + public boolean isOrderedStatus() { + if(!readyStatus) return false; + if(isPaid) return false; + if(isCanceled) return false; + if(isRefunded) return false; + return true; + } + + // 주문 취소 완료 상태 + public boolean isCanceledStatus() { + if(readyStatus) return false; + if(isPaid) return false; + if(!isCanceled) return false; + if(isRefunded) return false; + return true; + } + + // 결제 완료 상태 + public boolean isPaidStatus() { + if(!readyStatus) return false; + if(!isPaid) return false; + if(isCanceled) return false; + if(isRefunded) return false; + return true; + } + + // 환불 완료 상태 + public boolean isRefundedStatus() { + if(!readyStatus) return false; + if(!isPaid) return false; + if(isCanceled) return false; + if(!isRefunded) return false; + return true; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/order/entity/OrderItem.java b/mutbooks/src/main/java/com/example/mutbooks/app/order/entity/OrderItem.java new file mode 100644 index 0000000..1c15e58 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/order/entity/OrderItem.java @@ -0,0 +1,65 @@ +package com.example.mutbooks.app.order.entity; + +import com.example.mutbooks.app.base.entity.BaseEntity; +import com.example.mutbooks.app.product.entity.Product; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.SuperBuilder; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.ManyToOne; +import java.time.LocalDateTime; + +@Entity +@Getter +@Setter +@SuperBuilder +@NoArgsConstructor +@ToString(callSuper = true) +public class OrderItem extends BaseEntity { + @ManyToOne(fetch = FetchType.LAZY) + private Order order; // 주문번호 + + @ManyToOne(fetch = FetchType.LAZY) + private Product product; // 상품번호 + + private LocalDateTime payDate; // 결제 일시 + private LocalDateTime refundDate; // 환불 일시 + + private int price; // 권장 판매가 + private int salePrice; // 실제 판매가 + private int wholesalePrice; // 도매가 + private int pgFee; // 결제대행사 수수료 + private int payPrice; // 결제 금액 + private int refundPrice; // 환불 금액 + + private boolean isPaid; // 결제 여부 + private boolean isRefunded; // 환불 여부 + + + public OrderItem(Product product) { + // product 로 부터 가져온 값 + this.product = product; + this.price = product.getPrice(); + this.salePrice = product.getSalePrice(); + this.wholesalePrice = product.getWholesalePrice(); + } + + // 결제 완료 처리 + public void setPaymentDone() { + this.pgFee = 0; + this.payPrice = salePrice; + this.payDate = LocalDateTime.now(); + this.isPaid = true; + } + + // 주문 품목 환불 처리 + public void setRefundDone() { + this.refundPrice = payPrice; + this.refundDate = LocalDateTime.now(); + this.isRefunded = true; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/order/exception/OrderIdNotMatchedException.java b/mutbooks/src/main/java/com/example/mutbooks/app/order/exception/OrderIdNotMatchedException.java new file mode 100644 index 0000000..a8ad754 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/order/exception/OrderIdNotMatchedException.java @@ -0,0 +1,7 @@ +package com.example.mutbooks.app.order.exception; + +public class OrderIdNotMatchedException extends RuntimeException { + public OrderIdNotMatchedException(String message) { + super(message); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/order/exception/OrderNotFoundException.java b/mutbooks/src/main/java/com/example/mutbooks/app/order/exception/OrderNotFoundException.java new file mode 100644 index 0000000..c2bc7f7 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/order/exception/OrderNotFoundException.java @@ -0,0 +1,7 @@ +package com.example.mutbooks.app.order.exception; + +public class OrderNotFoundException extends RuntimeException { + public OrderNotFoundException(String message) { + super(message); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/order/exception/PaymentFailByInsufficientCashException.java b/mutbooks/src/main/java/com/example/mutbooks/app/order/exception/PaymentFailByInsufficientCashException.java new file mode 100644 index 0000000..d29ef21 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/order/exception/PaymentFailByInsufficientCashException.java @@ -0,0 +1,8 @@ +package com.example.mutbooks.app.order.exception; + +public class PaymentFailByInsufficientCashException extends RuntimeException { + + public PaymentFailByInsufficientCashException(String message) { + super(message); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/order/repository/OrderItemRepository.java b/mutbooks/src/main/java/com/example/mutbooks/app/order/repository/OrderItemRepository.java new file mode 100644 index 0000000..4baf8da --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/order/repository/OrderItemRepository.java @@ -0,0 +1,14 @@ +package com.example.mutbooks.app.order.repository; + +import com.example.mutbooks.app.order.entity.OrderItem; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.time.LocalDateTime; +import java.util.List; + +public interface OrderItemRepository extends JpaRepository { + List findAllByPayDateBetweenOrderByIdAsc(LocalDateTime startOfDay, LocalDateTime endOfDay); + Page findAllByPayDateBetween(LocalDateTime startOfDay, LocalDateTime endOfDay, Pageable pageable); +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/order/repository/OrderRepository.java b/mutbooks/src/main/java/com/example/mutbooks/app/order/repository/OrderRepository.java new file mode 100644 index 0000000..f7fe3f6 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/order/repository/OrderRepository.java @@ -0,0 +1,10 @@ +package com.example.mutbooks.app.order.repository; + +import com.example.mutbooks.app.order.entity.Order; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface OrderRepository extends JpaRepository { + List findByBuyerIdOrderByIdDesc(Long buyerId); +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/order/service/OrderService.java b/mutbooks/src/main/java/com/example/mutbooks/app/order/service/OrderService.java new file mode 100644 index 0000000..2471a57 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/order/service/OrderService.java @@ -0,0 +1,197 @@ +package com.example.mutbooks.app.order.service; + +import com.example.mutbooks.app.cart.entity.CartItem; +import com.example.mutbooks.app.cart.service.CartService; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.member.service.MemberService; +import com.example.mutbooks.app.mybook.entity.MyBook; +import com.example.mutbooks.app.mybook.service.MyBookService; +import com.example.mutbooks.app.order.entity.Order; +import com.example.mutbooks.app.order.entity.OrderItem; +import com.example.mutbooks.app.order.exception.OrderNotFoundException; +import com.example.mutbooks.app.order.repository.OrderItemRepository; +import com.example.mutbooks.app.order.repository.OrderRepository; +import com.example.mutbooks.app.product.entity.Product; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class OrderService { + private final CartService cartService; + private final MemberService memberService; + private final MyBookService myBookService; + private final OrderRepository orderRepository; + private final OrderItemRepository orderItemRepository; + + // 선택한 장바구니 품목으로부터 주문 생성 + @Transactional + public Order createOrder(Member buyer, String ids) { + // 주문 생성해야하는 cartItem id 리스트 + String[] idsArr = ids.split(","); + // Array -> List + List cartItemIds = Arrays.stream(idsArr) + .mapToLong(Long::parseLong) + .boxed() + .collect(Collectors.toList()); + // 1. 주문 생성해야하는 CartItem 조회 + List cartItems = cartService.findByBuyerAndIdInOrderByIdDesc(buyer, cartItemIds); + + // 2. 주문 품목 리스트 생성 + List orderItems = new ArrayList<>(); + for(CartItem cartItem : cartItems) { + // 2-1. 상품으로부터 주문 품목 생성 + Product product = cartItem.getProduct(); + orderItems.add(new OrderItem(product)); // Order 정보는 비어있는 상태에서 먼저 생성 + // 2-2. 장바구니 품목 삭제 + cartService.deleteCartItem(buyer, product); + } + + // 3. 주문 생성 + return create(buyer, orderItems); + } + + @Transactional + public Order create(Member buyer, List orderItems) { + Order order = Order.builder() + .buyer(buyer) + .build(); + + for(OrderItem orderItem : orderItems) { + order.addOrderItem(orderItem); + } + order.makeName(); + order.setOrderDone(); + orderRepository.save(order); + + return order; + } + + public List findByBuyer(Member buyer) { + return orderRepository.findByBuyerIdOrderByIdDesc(buyer.getId()); + } + + public Order findById(long id) { + return orderRepository.findById(id).orElseThrow(() -> { + throw new OrderNotFoundException("해당 주문은 존재하지 않습니다."); + }); + } + + // 주문 취소 + @Transactional + public void cancel(Order order) { + order.setCancelDone(); + } + + // 1. 캐시 전액 결제 + @Transactional + public void payByRestCashOnly(Order order) { + Member buyer = order.getBuyer(); // 구매자 + int payPrice = order.calcPayPrice(); // 결제 금액 + int restCash = buyer.getRestCash(); // 예치금 잔액 + + // 예치금 잔액 < 결제 금액 이면, 결제 거절 + if(restCash < payPrice) { + throw new RuntimeException("보유 캐시가 부족합니다."); + } + // 예치금 차감 처리 + memberService.addCash(buyer, payPrice * -1, "상품결제__캐시__주문__%d".formatted(order.getId())); + // 결제 완료 처리 + order.setPaymentDone(payPrice); + orderRepository.save(order); + // 내 도서에 추가 + myBookService.add(order); + } + + // 2. TossPayments 결제(TossPayments 전액 결제, 캐시 + TossPayments 혼합 결제) + @Transactional + public void payByTossPayments(Order order, int cashPayPrice) { + Member buyer = order.getBuyer(); + int payPrice = order.calcPayPrice(); + int pgPayPrice = payPrice - cashPayPrice; + + // 캐시 결제 내역 CashLog 추가 + if(cashPayPrice > 0) { + memberService.addCash(buyer, cashPayPrice * -1, "상품결제__캐시__주문__%d".formatted(order.getId())); + } + + // 카드 결제 내역 CashLog 추가 + memberService.addCash(buyer, pgPayPrice, "상품결제충전__토스페이먼츠"); + memberService.addCash(buyer, pgPayPrice * -1, "상품결제__토스페이먼츠__주문__%d".formatted(order.getId())); + // 결제 완료 처리 + order.setPaymentDone(payPrice, pgPayPrice); + orderRepository.save(order); + // 내 도서에 추가 + myBookService.add(order); + } + + // 캐시 전액 환불 + @Transactional + public void refundByRestCashOnly(Order order) { + Member buyer = order.getBuyer(); + int payPrice = order.calcPayPrice(); // 총 결제 금액 +// int pgPayPrice = order.getPgPayPrice(); // pg 결제 금액 +// int cashPayPrice = payPrice - pgPayPrice; // 캐시 결제 금액 + + memberService.addCash(buyer, payPrice, "상품환불충전__캐시__주문__%d".formatted(order.getId())); + + order.setRefundDone(); + orderRepository.save(order); + // 내 도서에서 삭제 + myBookService.remove(order); + } + + // 주문 정보 조회 권한 검증 + public boolean canSelect(Member member, Order order) { + return member.getId().equals(order.getBuyer().getId()); + } + + // 주문 취소 권한 검증 + public boolean canCancel(Member member, Order order) { + // TODO: 단순히 권한 체크만 할거면 주문 취소 가능 상태 체크는 빼기 + // 주문 완료 상태가 아니면 주문 취소 불가 + if(!order.isCancellable()) return false; + return canSelect(member, order); + } + + // 결제 권한 검증 + public boolean canPayment(Member member, Order order) { + return canSelect(member, order); + } + + // 환불 할 수 있는지 검증 + public boolean canRefund(Member member, Order order) { + // 권한 검증 + if(!canSelect(member, order)) { + throw new RuntimeException("환불 권한이 없습니다."); + } + // 해당 주문 상품들이 결제 후 10분이내이고 모두 읽지 않은 상태일 때만 환불 가능 + if(!order.isRefundable()) { + throw new RuntimeException("환불 기한이 지났습니다."); + } + + List orderItems = order.getOrderItems(); + for(OrderItem orderItem : orderItems) { + Long productId = orderItem.getProduct().getId(); + Long ownerId = order.getBuyer().getId(); + MyBook myBook = myBookService.findByProductIdAndOwnerId(productId, ownerId); + + if(myBook.isRead()) { + throw new RuntimeException("[%s] 상품이 개봉되어 환불할 수 없습니다.".formatted(orderItem.getProduct().getSubject())); + } + } + return true; + } + + public List findAllByPayDateBetweenOrderByIdAsc(LocalDateTime startOfDay, LocalDateTime endOfDay) { + return orderItemRepository.findAllByPayDateBetweenOrderByIdAsc(startOfDay, endOfDay); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/post/controller/PostController.java b/mutbooks/src/main/java/com/example/mutbooks/app/post/controller/PostController.java new file mode 100644 index 0000000..128e14a --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/post/controller/PostController.java @@ -0,0 +1,122 @@ +package com.example.mutbooks.app.post.controller; + +import com.example.mutbooks.app.security.dto.MemberContext; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.post.entity.Post; +import com.example.mutbooks.app.post.form.WriteForm; +import com.example.mutbooks.app.post.service.PostService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.server.ResponseStatusException; + +import javax.validation.Valid; +import java.util.List; + +@Controller +@RequiredArgsConstructor +@RequestMapping("/post") +public class PostController { + private final PostService postService; + + // 글 작성폼 + @PreAuthorize("isAuthenticated()") + @GetMapping("/write") + public String showWrite() { + return "post/write"; + } + + // 글 작성 + @PreAuthorize("isAuthenticated()") + @PostMapping("/write") + public String write(@AuthenticationPrincipal MemberContext memberContext, @Valid WriteForm writeForm) { + Member author = memberContext.getMember(); + + Post post = postService.write(author, writeForm); + + return "redirect:/post/%d".formatted(post.getId()); + } + + // 내글 상세조회 + @PreAuthorize("isAuthenticated()") + @GetMapping("/{id}") + public String showDetail(@AuthenticationPrincipal MemberContext memberContext, @PathVariable long id, Model model) { + Member member = memberContext.getMember(); + Post post = postService.findById(id); + + // 조회권한 검사 + if(!postService.canSelect(member, post)) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } + model.addAttribute("post", post); + + return "post/detail"; + } + + // 내글 리스트 조회 + @PreAuthorize("isAuthenticated()") + @GetMapping("/list") + public String showList(@RequestParam(defaultValue = "postHashTag") String kwType, @RequestParam(defaultValue = "") String kw + , @AuthenticationPrincipal MemberContext memberContext, Model model) { + Member author = memberContext.getMember(); + + List posts = postService.search(author, kwType, kw); + + model.addAttribute("posts", posts); + + return "post/list"; + } + + // 글 수정폼 + @PreAuthorize("isAuthenticated()") + @GetMapping("/{id}/modify") + public String showModify(@PathVariable long id, @AuthenticationPrincipal MemberContext memberContext, Model model) { + Member member = memberContext.getMember(); + Post post = postService.findById(id); + + // 수정권한 검사 + if(!postService.canModify(member, post)) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } + model.addAttribute("post", post); + + return "post/modify"; + } + + // 글 수정 + @PreAuthorize("isAuthenticated()") + @PostMapping("/{id}/modify") + public String modify(@PathVariable long id, @AuthenticationPrincipal MemberContext memberContext, @Valid WriteForm writeForm) { + Member member = memberContext.getMember(); + Post post = postService.findById(id); + + // 수정권한 검사 + if(!postService.canModify(member, post)) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } + postService.modify(post, writeForm); + + return "redirect:/post/%d".formatted(post.getId()); + } + + // 글 삭제 + @PreAuthorize("isAuthenticated()") + @PostMapping("/{id}/delete") + public String delete(@PathVariable long id, @AuthenticationPrincipal MemberContext memberContext) { + Member member = memberContext.getMember(); + Post post = postService.findById(id); + + // TODO : 예외 처리 + if(!postService.canDelete(member, post)) { + throw new RuntimeException(); + } + postService.delete(post); + + // 글 리스트 페이지로 리다이렉트 + return "redirect:/post/list"; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/post/dto/response/PostDetailDto.java b/mutbooks/src/main/java/com/example/mutbooks/app/post/dto/response/PostDetailDto.java new file mode 100644 index 0000000..3bac035 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/post/dto/response/PostDetailDto.java @@ -0,0 +1,38 @@ +package com.example.mutbooks.app.post.dto.response; + +import com.example.mutbooks.app.post.entity.Post; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +import java.util.List; +import java.util.stream.Collectors; + +@Getter +@Setter +@Builder +@AllArgsConstructor +public class PostDetailDto { + private Long id; + private String subject; + private String content; + private String contentHtml; + + public static PostDetailDto toDto(Post post) { + return PostDetailDto.builder() + .id(post.getId()) + .subject(post.getSubject()) + .content(post.getContent()) + .contentHtml(post.getContentHtml()) + .build(); + } + + public static List toDtos(List posts) { + List postDetailDtos = posts.stream() + .map(post -> PostDetailDto.toDto(post)) + .collect(Collectors.toList()); + + return postDetailDtos; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/post/entity/Post.java b/mutbooks/src/main/java/com/example/mutbooks/app/post/entity/Post.java new file mode 100644 index 0000000..b077820 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/post/entity/Post.java @@ -0,0 +1,46 @@ +package com.example.mutbooks.app.post.entity; + +import com.example.mutbooks.app.base.entity.BaseEntity; +import com.example.mutbooks.app.postHashTag.entity.PostHashTag; +import com.example.mutbooks.app.member.entity.Member; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.experimental.SuperBuilder; + +import javax.persistence.*; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +@Entity +@Getter +@Setter +@SuperBuilder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Post extends BaseEntity { + private String subject; // 제목 + private String content; // 내용(마크다운 원문) + private String contentHtml; // HTML 내용(토스트에디터의 렌더링 결과) + + @ManyToOne(fetch = FetchType.LAZY) + private Member author; // 글쓴이 + + @OneToMany(mappedBy = "post", cascade = {CascadeType.ALL}) + private List hashTags = new ArrayList<>(); + + // 해당 게시글의 해시태그들을 한 문장으로 반환 + public String getHashTagString() { + if(hashTags.isEmpty()) { + return ""; + } + + return "#" + hashTags + .stream() + .map(hashTag -> hashTag.getPostKeyword().getContent()) + .sorted() + .collect(Collectors.joining(" #")) + .trim(); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/post/exception/PostNotFoundException.java b/mutbooks/src/main/java/com/example/mutbooks/app/post/exception/PostNotFoundException.java new file mode 100644 index 0000000..1625c2c --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/post/exception/PostNotFoundException.java @@ -0,0 +1,4 @@ +package com.example.mutbooks.app.post.exception; + +public class PostNotFoundException extends RuntimeException { +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/post/form/WriteForm.java b/mutbooks/src/main/java/com/example/mutbooks/app/post/form/WriteForm.java new file mode 100644 index 0000000..76b9894 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/post/form/WriteForm.java @@ -0,0 +1,17 @@ +package com.example.mutbooks.app.post.form; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import javax.validation.constraints.NotEmpty; + +@Data +@AllArgsConstructor +public class WriteForm { + @NotEmpty + private String subject; // 제목 + @NotEmpty + private String content; // 마크다운 원문 + private String contentHtml; // 렌더링 결과 HTML + private String keywords; // 해시태그 +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/post/repository/PostRepository.java b/mutbooks/src/main/java/com/example/mutbooks/app/post/repository/PostRepository.java new file mode 100644 index 0000000..17cf746 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/post/repository/PostRepository.java @@ -0,0 +1,11 @@ +package com.example.mutbooks.app.post.repository; + +import com.example.mutbooks.app.post.entity.Post; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface PostRepository extends JpaRepository, PostRepositoryCustom { + + List findAllByAuthorIdOrderByIdDesc(Long authorId); +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/post/repository/PostRepositoryCustom.java b/mutbooks/src/main/java/com/example/mutbooks/app/post/repository/PostRepositoryCustom.java new file mode 100644 index 0000000..2320900 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/post/repository/PostRepositoryCustom.java @@ -0,0 +1,10 @@ +package com.example.mutbooks.app.post.repository; + +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.post.entity.Post; + +import java.util.List; + +public interface PostRepositoryCustom { + List searchQsl(Member author, String kwType, String kw); +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/post/repository/PostRepositoryImpl.java b/mutbooks/src/main/java/com/example/mutbooks/app/post/repository/PostRepositoryImpl.java new file mode 100644 index 0000000..e4d570b --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/post/repository/PostRepositoryImpl.java @@ -0,0 +1,43 @@ +package com.example.mutbooks.app.post.repository; + +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.post.entity.Post; +import com.querydsl.jpa.impl.JPAQuery; +import com.querydsl.jpa.impl.JPAQueryFactory; +import lombok.RequiredArgsConstructor; + +import java.util.List; + +import static com.example.mutbooks.app.postHashTag.entity.QPostHashTag.postHashTag; +import static com.example.mutbooks.app.postKeyword.entity.QPostKeyword.postKeyword; +import static com.example.mutbooks.app.post.entity.QPost.post; + +@RequiredArgsConstructor +public class PostRepositoryImpl implements PostRepositoryCustom{ + private final JPAQueryFactory jpaQueryFactory; + + @Override + public List searchQsl(Member author, String kwType, String kw) { + // 1. 전체 조회(키워드가 없거나 검색타입이 검색 타입이 postHashTag 가 아닌 경우) + JPAQuery jpqQuery = jpaQueryFactory + .select(post) + .where(post.author.id.eq(author.getId())) + .distinct() + .from(post); + + // 2. 키워드 기반 검색(키워드가 존재하고 키워드 타입이 해시태그인 경우) + if(!kw.equals("")) { + if(kwType.equals("postHashTag")) { + jpqQuery + .innerJoin(postHashTag) + .on(post.eq(postHashTag.post)) + .innerJoin(postKeyword) + .on(postKeyword.eq(postHashTag.postKeyword)) + .where(postKeyword.content.eq(kw)); + } + } + jpqQuery.orderBy(post.id.desc()); + + return jpqQuery.fetch(); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/post/service/PostService.java b/mutbooks/src/main/java/com/example/mutbooks/app/post/service/PostService.java new file mode 100644 index 0000000..5402cbd --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/post/service/PostService.java @@ -0,0 +1,92 @@ +package com.example.mutbooks.app.post.service; + +import com.example.mutbooks.app.postHashTag.service.PostHashTagService; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.post.exception.PostNotFoundException; +import com.example.mutbooks.app.post.entity.Post; +import com.example.mutbooks.app.post.form.WriteForm; +import com.example.mutbooks.app.post.repository.PostRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class PostService { + private final PostRepository postRepository; + private final PostHashTagService postHashTagService; + + public Post findById(long id) { + return postRepository.findById(id).orElseThrow(() -> { + throw new PostNotFoundException(); + }); + } + + // 내 글 전체조회 + public List findAllByAuthorIdOrderByIdDesc(Long authorId) { + return postRepository.findAllByAuthorIdOrderByIdDesc(authorId); + } + + // 내 글 전체/키워드 기반 겁색 조회 + public List search(Member author, String kwType, String kw) { + return postRepository.searchQsl(author, kwType, kw); + } + + @Transactional + public Post write(Member author, WriteForm writeForm) { + Post post = Post.builder() + .subject(writeForm.getSubject()) + .content(writeForm.getContent()) + .contentHtml(writeForm.getContentHtml()) + .author(author) + .build(); + + postRepository.save(post); + + // 해시태그 적용 + String keywords = writeForm.getKeywords(); + if(keywords != null) { + postHashTagService.apply(post, keywords); + } + + return post; + } + + @Transactional + public void modify(Post post, WriteForm writeForm) { + post.setSubject(writeForm.getSubject()); + post.setContent(writeForm.getContent()); + post.setContentHtml(writeForm.getContentHtml()); + + // 해시태그 적용 + String keywords = writeForm.getKeywords(); + if(keywords != null) { + postHashTagService.apply(post, keywords); + } + + postRepository.save(post); + } + + @Transactional + public void delete(Post post) { + postRepository.delete(post); + } + + // 글 수정 권한 여부 체크(수정 권한: 글쓴이 본인) + public boolean canModify(Member member, Post post) { + return member.getId().equals(post.getAuthor().getId()); + } + + // 글 삭제 권한 여부 체크(삭제 권한: 글쓴이 본인) + public boolean canDelete(Member member, Post post) { + return canModify(member, post); + } + + // 글 조회 권한 여부 체크(권한: 글쓴이 본인) + public boolean canSelect(Member member, Post post) { + return canModify(member, post); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/entity/PostHashTag.java b/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/entity/PostHashTag.java new file mode 100644 index 0000000..9e6d373 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/entity/PostHashTag.java @@ -0,0 +1,36 @@ +package com.example.mutbooks.app.postHashTag.entity; + +import com.example.mutbooks.app.base.entity.BaseEntity; +import com.example.mutbooks.app.postKeyword.entity.PostKeyword; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.post.entity.Post; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.SuperBuilder; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.ManyToOne; + +@Entity +@Getter +@Setter +@SuperBuilder +@NoArgsConstructor +@ToString(callSuper = true) +public class PostHashTag extends BaseEntity { + @ManyToOne(fetch = FetchType.LAZY) + private Member member; // 회원 + @ManyToOne(fetch = FetchType.LAZY) + private Post post; // 글 + @ManyToOne(fetch = FetchType.LAZY) + private PostKeyword postKeyword; // 키워드 + + // postHashTag 키워드로 게시글 검색 요청 url + public String getSearchUrl() { + String url = "/post/list?kwType=postHashTag&kw=%s".formatted(this.getPostKeyword().getContent()); + return url; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/repository/PostHashTagRepository.java b/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/repository/PostHashTagRepository.java new file mode 100644 index 0000000..2cc63ae --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/repository/PostHashTagRepository.java @@ -0,0 +1,17 @@ +package com.example.mutbooks.app.postHashTag.repository; + +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.postHashTag.entity.PostHashTag; +import com.example.mutbooks.app.postKeyword.entity.PostKeyword; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; +import java.util.Optional; + +public interface PostHashTagRepository extends JpaRepository { + Optional findByPostIdAndPostKeywordId(Long postId, Long postKeywordId); + + List findByPostId(Long postId); + + List findByPostKeywordAndMember(PostKeyword postKeyword, Member member); +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/service/PostHashTagService.java b/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/service/PostHashTagService.java new file mode 100644 index 0000000..978eefd --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/postHashTag/service/PostHashTagService.java @@ -0,0 +1,85 @@ +package com.example.mutbooks.app.postHashTag.service; + +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.post.entity.Post; +import com.example.mutbooks.app.postHashTag.entity.PostHashTag; +import com.example.mutbooks.app.postHashTag.repository.PostHashTagRepository; +import com.example.mutbooks.app.postKeyword.entity.PostKeyword; +import com.example.mutbooks.app.postKeyword.service.PostKeywordService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class PostHashTagService { + private final PostHashTagRepository postHashTagRepository; + private final PostKeywordService postKeywordService; + + // 게시글에 해시태그 반영 + public void apply(Post post, String keywords) { + // 1. 기존 해시태그 가져오기 + List oldHashTags = findByPostId(post.getId()); + + // 2. 새로운 해시태그 키워드 리스트 + List keywordContents = Arrays.stream(keywords.split("#")) + .map(String::trim) + .filter(s -> s.length() > 0) + .collect(Collectors.toList()); + + // 3. 삭제할 해시태그 구하기(기존 해시태그 리스트에서 새로운 해시태그 리스트에 없는 것) + List deleteHashTags = new ArrayList<>(); + for(PostHashTag oldHashTag : oldHashTags) { + // 기존에 등록된 해시태그가 새롭게 등록된 해시태그에 포함되었는지 여부 + boolean contains = keywordContents.stream().anyMatch(s -> s.equals(oldHashTag.getPostKeyword().getContent())); + + if(!contains) { + deleteHashTags.add(oldHashTag); + } + } + + // 4. 3번에서 구한 해시태그 삭제 + deleteHashTags.forEach(hashTag -> { + postHashTagRepository.delete(hashTag); + }); + + // 5. 나머지 해시태그는 저장 + keywordContents.forEach(keywordContent -> { + save(post, keywordContent); + }); + } + + // 해시태그 저장 + public PostHashTag save(Post post, String keywordContent) { + // 1. postKeyword 가져오기 + PostKeyword keyword = postKeywordService.save(keywordContent); + + // 2. (postId + keywordId) 가 DB에 있으면 바로 리턴 + PostHashTag hashTag = postHashTagRepository.findByPostIdAndPostKeywordId(post.getId(), keyword.getId()).orElse(null); + if(hashTag != null) { + return hashTag; + } + // 3. (postId + keywordId) 로 DB에 없으면 postHashTag 저장 + hashTag = PostHashTag.builder() + .member(post.getAuthor()) + .post(post) + .postKeyword(keyword) + .build(); + postHashTagRepository.save(hashTag); + + return hashTag; + } + + // postId로 postHashTag 조회 + public List findByPostId(long postId) { + return postHashTagRepository.findByPostId(postId); + } + + public List findByPostKeywordAndMember(PostKeyword postKeyword, Member member) { + return postHashTagRepository.findByPostKeywordAndMember(postKeyword, member); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/dto/PostKeywordDto.java b/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/dto/PostKeywordDto.java new file mode 100644 index 0000000..8d0b11d --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/dto/PostKeywordDto.java @@ -0,0 +1,12 @@ +package com.example.mutbooks.app.postKeyword.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class PostKeywordDto { + private Long id; + private String content; + private Long postCount; // 해당 해시태그 키워드와 관련 게시글 수 +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/entity/PostKeyword.java b/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/entity/PostKeyword.java new file mode 100644 index 0000000..9bbf239 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/entity/PostKeyword.java @@ -0,0 +1,22 @@ +package com.example.mutbooks.app.postKeyword.entity; + +import com.example.mutbooks.app.base.entity.BaseEntity; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.SuperBuilder; + +import javax.persistence.Column; +import javax.persistence.Entity; + +@Entity +@Getter +@Setter +@SuperBuilder +@NoArgsConstructor +@ToString(callSuper = true) +public class PostKeyword extends BaseEntity { + @Column(unique = true) + private String content; // 해시태그 +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/exception/PostKeywordNotFoundException.java b/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/exception/PostKeywordNotFoundException.java new file mode 100644 index 0000000..9600cae --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/exception/PostKeywordNotFoundException.java @@ -0,0 +1,7 @@ +package com.example.mutbooks.app.postKeyword.exception; + +public class PostKeywordNotFoundException extends RuntimeException { + public PostKeywordNotFoundException(String message) { + super(message); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/repository/PostKeywordRepository.java b/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/repository/PostKeywordRepository.java new file mode 100644 index 0000000..f8e3378 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/repository/PostKeywordRepository.java @@ -0,0 +1,10 @@ +package com.example.mutbooks.app.postKeyword.repository; + +import com.example.mutbooks.app.postKeyword.entity.PostKeyword; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface PostKeywordRepository extends JpaRepository, PostKeywordRepositoryCustom { + Optional findByContent(String content); +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/repository/PostKeywordRepositoryCustom.java b/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/repository/PostKeywordRepositoryCustom.java new file mode 100644 index 0000000..5cc5aa8 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/repository/PostKeywordRepositoryCustom.java @@ -0,0 +1,9 @@ +package com.example.mutbooks.app.postKeyword.repository; + +import com.example.mutbooks.app.postKeyword.dto.PostKeywordDto; + +import java.util.List; + +public interface PostKeywordRepositoryCustom { + List getQslAllByAuthorId(Long authorId); +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/repository/PostKeywordRepositoryImpl.java b/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/repository/PostKeywordRepositoryImpl.java new file mode 100644 index 0000000..b00f2ab --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/repository/PostKeywordRepositoryImpl.java @@ -0,0 +1,34 @@ +package com.example.mutbooks.app.postKeyword.repository; + +import com.example.mutbooks.app.postKeyword.dto.PostKeywordDto; +import com.querydsl.core.types.Projections; +import com.querydsl.jpa.impl.JPAQueryFactory; +import lombok.RequiredArgsConstructor; + +import java.util.List; + +import static com.example.mutbooks.app.postHashTag.entity.QPostHashTag.postHashTag; +import static com.example.mutbooks.app.postKeyword.entity.QPostKeyword.postKeyword; + +@RequiredArgsConstructor +public class PostKeywordRepositoryImpl implements PostKeywordRepositoryCustom { + private final JPAQueryFactory jpaQueryFactory; + + @Override + public List getQslAllByAuthorId(Long authorId) { + // 생성자를 이용해 List 로 반환 + return jpaQueryFactory + .select(Projections.constructor(PostKeywordDto.class, + postKeyword.id, + postKeyword.content, + postHashTag.count() + )) + .from(postKeyword) + .innerJoin(postHashTag) + .on(postKeyword.eq(postHashTag.postKeyword)) + .where(postHashTag.member.id.eq(authorId)) + .orderBy(postKeyword.content.asc()) // 키워드 명 오름차순 정렬 + .groupBy(postKeyword.id) // 키워드 중복 제거 + .fetch(); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/service/PostKeywordService.java b/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/service/PostKeywordService.java new file mode 100644 index 0000000..74a2cec --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/postKeyword/service/PostKeywordService.java @@ -0,0 +1,52 @@ +package com.example.mutbooks.app.postKeyword.service; + +import com.example.mutbooks.app.postKeyword.dto.PostKeywordDto; +import com.example.mutbooks.app.postKeyword.entity.PostKeyword; +import com.example.mutbooks.app.postKeyword.exception.PostKeywordNotFoundException; +import com.example.mutbooks.app.postKeyword.repository.PostKeywordRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class PostKeywordService { + private final PostKeywordRepository postKeywordRepository; + + // 키워드 저장 + @Transactional + public PostKeyword save(String content) { + PostKeyword keyword = findByContent(content); + + // 1. 해당 키워드(content)가 DB에 있으면 바로 리턴 + if(keyword != null) { + return keyword; + } + // 2. 해당 키워드(content)가 DB에 없으면 저장 + keyword = PostKeyword.builder() + .content(content) + .build(); + postKeywordRepository.save(keyword); + + return keyword; + } + + // 키워드 content 로 조회 + public PostKeyword findByContent(String content) { + return postKeywordRepository.findByContent(content).orElse(null); + } + + // 작가가 등록한 글과 관련된 모든 해시태그 키워드 조회 + public List findByMemberId(Long authorId) { + return postKeywordRepository.getQslAllByAuthorId(authorId); + } + + public PostKeyword findById(Long id) { + return postKeywordRepository.findById(id).orElseThrow(() -> { + throw new PostKeywordNotFoundException("해당 키워드는 존재하지 않습니다."); + }); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/product/controller/ProductController.java b/mutbooks/src/main/java/com/example/mutbooks/app/product/controller/ProductController.java new file mode 100644 index 0000000..1663d69 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/product/controller/ProductController.java @@ -0,0 +1,131 @@ +package com.example.mutbooks.app.product.controller; + +import com.example.mutbooks.app.security.dto.MemberContext; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.postKeyword.dto.PostKeywordDto; +import com.example.mutbooks.app.postKeyword.service.PostKeywordService; +import com.example.mutbooks.app.product.entity.Product; +import com.example.mutbooks.app.product.form.ProductForm; +import com.example.mutbooks.app.product.form.ProductModifyForm; +import com.example.mutbooks.app.product.service.ProductService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.server.ResponseStatusException; + +import javax.validation.Valid; +import java.util.List; + +@Controller +@RequestMapping("/product") +@RequiredArgsConstructor +public class ProductController { + private final ProductService productService; + private final PostKeywordService postKeywordService; + + // 도서 등록폼 + @PreAuthorize("isAuthenticated() and hasAuthority('AUTHOR')") + @GetMapping("/create") + public String showCreate(@AuthenticationPrincipal MemberContext memberContext, Model model) { + List postKeywords = postKeywordService.findByMemberId(memberContext.getId()); + model.addAttribute("postKeywords", postKeywords); + + return "/product/create"; + } + + // 도서 등록 + @PreAuthorize("isAuthenticated() and hasAuthority('AUTHOR')") + @PostMapping("/create") + public String create(@AuthenticationPrincipal MemberContext memberContext, + @Valid ProductForm productForm, BindingResult bindingResult) { + if(bindingResult.hasErrors()) { + return "/product/create"; + } + + Member author = memberContext.getMember(); + Product product = productService.create(author, productForm); + + return "redirect:/product/" + product.getId(); + } + + // 도서 상세조회 + @GetMapping("/{id}") + public String detail(@PathVariable long id, Model model) { + Product product = productService.findById(id); + model.addAttribute("product", product); + + return "product/detail"; + } + + // 도서 리스트 조회 + @GetMapping("/list") + public String list(Model model) { + List products = productService.findAllByOrderByIdDesc(); + model.addAttribute("products", products); + + return "product/list"; + } + + // 도서 수정폼 + @PreAuthorize("isAuthenticated() and hasAuthority('AUTHOR')") + @GetMapping("/{id}/modify") + public String showModify(@PathVariable long id, @AuthenticationPrincipal MemberContext memberContext, Model model) { + Product product = productService.findById(id); + Member member = memberContext.getMember(); + + // 수정 권한 검사 + if(productService.canModify(member, product) == false) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } + + model.addAttribute("product", product); + + return "/product/modify"; + } + + // 도서 수정 + @PreAuthorize("isAuthenticated() and hasAuthority('AUTHOR')") + @PostMapping("/{id}/modify") + public String modify(@PathVariable long id, + @AuthenticationPrincipal MemberContext memberContext, + @Valid ProductModifyForm productModifyForm, BindingResult bindingResult) { + if(bindingResult.hasErrors()) { + return "product/modify"; + } + + Product product = productService.findById(id); + Member member = memberContext.getMember(); + + // 수정 권한 검사 + if(productService.canModify(member, product) == false) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } + productService.modify(product, productModifyForm); + + return "redirect:/product/%d".formatted(product.getId()); + } + + // 도서 삭제 + @PreAuthorize("isAuthenticated() and hasAuthority('AUTHOR')") + @PostMapping("/{id}/delete") + public String delete(@PathVariable long id, @AuthenticationPrincipal MemberContext memberContext) { + Member member = memberContext.getMember(); + Product product = productService.findById(id); + + // 삭제 권한 검사 + if(productService.canDelete(member, product) == false) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } + productService.delete(product); + + return "redirect:/product/list"; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDetailDto.java b/mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDetailDto.java new file mode 100644 index 0000000..3bb4240 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDetailDto.java @@ -0,0 +1,40 @@ +package com.example.mutbooks.app.product.dto.response; + +import com.example.mutbooks.app.post.dto.response.PostDetailDto; +import com.example.mutbooks.app.post.entity.Post; +import com.example.mutbooks.app.product.entity.Product; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; +import java.util.List; + +@Getter +@Setter +@Builder +@AllArgsConstructor +public class ProductDetailDto { + private Long id; + private LocalDateTime createDate; + private LocalDateTime modifyDate; + private Long authorId; + private String authorName; + private String subject; + private List bookChapters; + + public static ProductDetailDto toDto(Product product, List posts) { + List postDetailDtos = PostDetailDto.toDtos(posts); + + return ProductDetailDto.builder() + .id(product.getId()) + .createDate(product.getCreateDate()) + .modifyDate(product.getUpdateDate()) + .authorId(product.getAuthor().getId()) + .authorName(product.getAuthor().getNickname()) + .subject(product.getSubject()) + .bookChapters(postDetailDtos) + .build(); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDto.java b/mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDto.java new file mode 100644 index 0000000..1db557e --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/product/dto/response/ProductDto.java @@ -0,0 +1,33 @@ +package com.example.mutbooks.app.product.dto.response; + +import com.example.mutbooks.app.product.entity.Product; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@Builder +@AllArgsConstructor +public class ProductDto { + private Long id; + private LocalDateTime createDate; + private LocalDateTime modifyDate; + private Long authorId; + private String authorName; + private String subject; + + public static ProductDto toDto(Product product) { + return ProductDto.builder() + .id(product.getId()) + .createDate(product.getCreateDate()) + .modifyDate(product.getUpdateDate()) + .authorId(product.getAuthor().getId()) + .authorName(product.getAuthor().getNickname()) + .subject(product.getSubject()) + .build(); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/product/entity/Product.java b/mutbooks/src/main/java/com/example/mutbooks/app/product/entity/Product.java new file mode 100644 index 0000000..0f8cfca --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/product/entity/Product.java @@ -0,0 +1,65 @@ +package com.example.mutbooks.app.product.entity; + +import com.example.mutbooks.app.base.entity.BaseEntity; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.postKeyword.entity.PostKeyword; +import com.example.mutbooks.app.productHashTag.entity.ProductHashTag; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.SuperBuilder; + +import javax.persistence.*; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +@Entity +@Getter +@Setter +@SuperBuilder +@NoArgsConstructor +@ToString(callSuper = true) +public class Product extends BaseEntity { + @ManyToOne(fetch = FetchType.LAZY) + private Member author; // 작가 + + @ManyToOne(fetch = FetchType.LAZY) + private PostKeyword postKeyword; // 게시글 키워드 + + private String subject; // (노출용)상품명 + + @Column(columnDefinition = "TEXT") + private String content; // 상품설명 + + private int price; // 판매가 + + @OneToMany(mappedBy = "product", cascade = {CascadeType.ALL}) + private List productHashTags = new ArrayList<>(); // 도서 해시태그 리스트 + + // 실제 판매가 + public int getSalePrice() { + return getPrice(); + } + + // 도매가 + public int getWholesalePrice() { + // 판매자 : 멋북스 = 5 : 5 + return (int) Math.ceil(getPrice() * 0.5); + } + + // 해당 도서의 해시태그들을 한 문장으로 반환 + public String getHashTagString() { + if(productHashTags.isEmpty()) { + return ""; + } + + return "#" + productHashTags + .stream() + .map(hashTag -> hashTag.getProductKeyword().getContent()) + .sorted() + .collect(Collectors.joining(" #")) + .trim(); + } +} \ No newline at end of file diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/product/exception/ProductNotFoundException.java b/mutbooks/src/main/java/com/example/mutbooks/app/product/exception/ProductNotFoundException.java new file mode 100644 index 0000000..2bd5549 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/product/exception/ProductNotFoundException.java @@ -0,0 +1,7 @@ +package com.example.mutbooks.app.product.exception; + +public class ProductNotFoundException extends RuntimeException { + public ProductNotFoundException(String message) { + super(message); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/product/form/ProductForm.java b/mutbooks/src/main/java/com/example/mutbooks/app/product/form/ProductForm.java new file mode 100644 index 0000000..e20c69c --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/product/form/ProductForm.java @@ -0,0 +1,27 @@ +package com.example.mutbooks.app.product.form; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + +@Getter +@Setter +@AllArgsConstructor +public class ProductForm { + @NotEmpty(message = "도서명을 입력해주세요.") + private String subject; + + @NotEmpty(message = "도서 설명을 입력해주세요.") + private String content; + + @NotNull(message = "도서 판매 가격을 입력해주세요.") + private int price; + + @NotNull + private Long postKeywordId; + + private String productKeywords; // 도서(상품) 해시태그 키워드 +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/product/form/ProductModifyForm.java b/mutbooks/src/main/java/com/example/mutbooks/app/product/form/ProductModifyForm.java new file mode 100644 index 0000000..32af602 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/product/form/ProductModifyForm.java @@ -0,0 +1,24 @@ +package com.example.mutbooks.app.product.form; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + +@Getter +@Setter +@AllArgsConstructor +public class ProductModifyForm { + @NotEmpty(message = "도서명을 입력해주세요.") + private String subject; + + @NotEmpty(message = "도서 설명을 입력해주세요.") + private String content; + + @NotNull(message = "도서 판매 가격을 입력해주세요.") + private int price; + + private String productKeywords; // 도서(상품) 해시태그 키워드 +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/product/repository/ProductRepository.java b/mutbooks/src/main/java/com/example/mutbooks/app/product/repository/ProductRepository.java new file mode 100644 index 0000000..b66a31b --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/product/repository/ProductRepository.java @@ -0,0 +1,10 @@ +package com.example.mutbooks.app.product.repository; + +import com.example.mutbooks.app.product.entity.Product; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface ProductRepository extends JpaRepository { + List findALlByOrderByIdDesc(); +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/product/service/ProductService.java b/mutbooks/src/main/java/com/example/mutbooks/app/product/service/ProductService.java new file mode 100644 index 0000000..e695c70 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/product/service/ProductService.java @@ -0,0 +1,86 @@ +package com.example.mutbooks.app.product.service; + +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.postKeyword.entity.PostKeyword; +import com.example.mutbooks.app.postKeyword.service.PostKeywordService; +import com.example.mutbooks.app.product.entity.Product; +import com.example.mutbooks.app.product.exception.ProductNotFoundException; +import com.example.mutbooks.app.product.form.ProductForm; +import com.example.mutbooks.app.product.form.ProductModifyForm; +import com.example.mutbooks.app.product.repository.ProductRepository; +import com.example.mutbooks.app.productHashTag.service.ProductHashTagService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class ProductService { + private final ProductRepository productRepository; + private final PostKeywordService postKeywordService; + private final ProductHashTagService productHashTagService; + + @Transactional + public Product create(Member author, ProductForm productForm) { + PostKeyword postKeyword = postKeywordService.findById(productForm.getPostKeywordId()); + + Product product = Product.builder() + .author(author) + .postKeyword(postKeyword) + .subject(productForm.getSubject()) + .content(productForm.getContent()) + .price(productForm.getPrice()) + .build(); + + productRepository.save(product); + + // 도서 해시태그 적용 + String productKeywords = productForm.getProductKeywords(); + if(productKeywords != null) { + productHashTagService.apply(product, productKeywords); + } + + return product; + } + + public Product findById(long id) { + return productRepository.findById(id).orElseThrow(() -> { + throw new ProductNotFoundException("해당 도서는 존재하지 않습니다."); + }); + } + + public List findAllByOrderByIdDesc() { + return productRepository.findALlByOrderByIdDesc(); + } + + // 도서 이름, 가격, 설명, 해시태그 수정 + @Transactional + public void modify(Product product, ProductModifyForm productModifyForm) { + product.setSubject(productModifyForm.getSubject()); + product.setContent(productModifyForm.getContent()); + product.setPrice(productModifyForm.getPrice()); + // 해시태그 적용 + String productKeywords = productModifyForm.getProductKeywords(); + if(productKeywords != null) { + productHashTagService.apply(product, productKeywords); + } + } + + @Transactional + public void delete(Product product) { + productRepository.delete(product); + } + + // 수정 권한 검사 + public boolean canModify(Member member, Product product) { + return member.getId().equals(product.getAuthor().getId()); + } + + // 삭제 권한 검사 + public boolean canDelete(Member member, Product product) { + return canModify(member, product); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/productHashTag/entity/ProductHashTag.java b/mutbooks/src/main/java/com/example/mutbooks/app/productHashTag/entity/ProductHashTag.java new file mode 100644 index 0000000..f532288 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/productHashTag/entity/ProductHashTag.java @@ -0,0 +1,32 @@ +package com.example.mutbooks.app.productHashTag.entity; + +import com.example.mutbooks.app.base.entity.BaseEntity; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.product.entity.Product; +import com.example.mutbooks.app.productKeyword.entity.ProductKeyword; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.SuperBuilder; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.ManyToOne; + +@Entity +@Getter +@Setter +@SuperBuilder +@NoArgsConstructor +@ToString(callSuper = true) +public class ProductHashTag extends BaseEntity { + @ManyToOne(fetch = FetchType.LAZY) + private Member member; // 회원 + + @ManyToOne(fetch = FetchType.LAZY) + private Product product; // 도서 + + @ManyToOne(fetch = FetchType.LAZY) + private ProductKeyword productKeyword; // 키워드 +} \ No newline at end of file diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/productHashTag/repository/ProductHashTagRepository.java b/mutbooks/src/main/java/com/example/mutbooks/app/productHashTag/repository/ProductHashTagRepository.java new file mode 100644 index 0000000..177afea --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/productHashTag/repository/ProductHashTagRepository.java @@ -0,0 +1,13 @@ +package com.example.mutbooks.app.productHashTag.repository; + +import com.example.mutbooks.app.productHashTag.entity.ProductHashTag; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; +import java.util.Optional; + +public interface ProductHashTagRepository extends JpaRepository { + List findByProductId(Long productId); + + Optional findByProductIdAndProductKeywordId(Long productId, Long productKeywordId); +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/productHashTag/service/ProductHashTagService.java b/mutbooks/src/main/java/com/example/mutbooks/app/productHashTag/service/ProductHashTagService.java new file mode 100644 index 0000000..9c317e2 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/productHashTag/service/ProductHashTagService.java @@ -0,0 +1,84 @@ +package com.example.mutbooks.app.productHashTag.service; + +import com.example.mutbooks.app.product.entity.Product; +import com.example.mutbooks.app.productHashTag.entity.ProductHashTag; +import com.example.mutbooks.app.productHashTag.repository.ProductHashTagRepository; +import com.example.mutbooks.app.productKeyword.entity.ProductKeyword; +import com.example.mutbooks.app.productKeyword.service.ProductKeywordService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class ProductHashTagService { + private final ProductHashTagRepository productHashTagRepository; + private final ProductKeywordService productKeywordService; + + // 도서(상품)에 해시태그 반영 + @Transactional + public void apply(Product product, String productKeywords) { + // 1. 기존 해시태그 가져오기 + List oldHashTags = findByProductId(product.getId()); + + // 2. 새로운 해시태그 키워드 리스트 + List keywordContents = Arrays.stream(productKeywords.split("#")) + .map(String::trim) + .filter(s -> s.length() > 0) + .collect(Collectors.toList()); + + // 3. 삭제할 해시태그 구하기(기존 해시태그 리스트에서 새로운 해시태그 리스트에 없는 것) + List deleteHashTags = new ArrayList<>(); + for(ProductHashTag oldHashTag : oldHashTags) { + // 기존에 등록된 해시태그가 새롭게 등록된 해시태그에 포함되었는지 여부 + boolean contains = keywordContents.stream().anyMatch(s -> s.equals(oldHashTag.getProductKeyword().getContent())); + + if(!contains) { + deleteHashTags.add(oldHashTag); + } + } + + // 4. 3번에서 구한 해시태그 삭제 + deleteHashTags.forEach(hashTag -> { + productHashTagRepository.delete(hashTag); + }); + + // 5. 나머지 해시태그는 저장 + keywordContents.forEach(keywordContent -> { + save(product, keywordContent); + }); + } + + // 도서 해시태그 저장 + public ProductHashTag save(Product product, String keywordContent) { + // 1. keyword 가져오기 + ProductKeyword productKeyword = productKeywordService.save(keywordContent); + + // 2. (productId + keywordId) 가 DB에 있으면 바로 리턴 + ProductHashTag productHashTag = productHashTagRepository.findByProductIdAndProductKeywordId(product.getId(), productKeyword.getId()).orElse(null); + if(productHashTag != null) { + return productHashTag; + } + + // 3. (productId + keywordId) 로 DB에 없으면 productHashTag 저장 + productHashTag = ProductHashTag.builder() + .member(product.getAuthor()) + .product(product) + .productKeyword(productKeyword) + .build(); + + productHashTagRepository.save(productHashTag); + + return productHashTag; + } + + private List findByProductId(Long productId) { + return productHashTagRepository.findByProductId(productId); + } +} \ No newline at end of file diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/productKeyword/entity/ProductKeyword.java b/mutbooks/src/main/java/com/example/mutbooks/app/productKeyword/entity/ProductKeyword.java new file mode 100644 index 0000000..1006eb3 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/productKeyword/entity/ProductKeyword.java @@ -0,0 +1,22 @@ +package com.example.mutbooks.app.productKeyword.entity; + +import com.example.mutbooks.app.base.entity.BaseEntity; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.SuperBuilder; + +import javax.persistence.Column; +import javax.persistence.Entity; + +@Entity +@Getter +@Setter +@SuperBuilder +@NoArgsConstructor +@ToString(callSuper = true) +public class ProductKeyword extends BaseEntity { + @Column(unique = true) + private String content; // 해시태그 +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/productKeyword/repository/ProductKeywordRepository.java b/mutbooks/src/main/java/com/example/mutbooks/app/productKeyword/repository/ProductKeywordRepository.java new file mode 100644 index 0000000..faf58a0 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/productKeyword/repository/ProductKeywordRepository.java @@ -0,0 +1,10 @@ +package com.example.mutbooks.app.productKeyword.repository; + +import com.example.mutbooks.app.productKeyword.entity.ProductKeyword; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface ProductKeywordRepository extends JpaRepository { + Optional findByContent(String content); +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/productKeyword/service/ProductKeywordService.java b/mutbooks/src/main/java/com/example/mutbooks/app/productKeyword/service/ProductKeywordService.java new file mode 100644 index 0000000..1d9b2e9 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/productKeyword/service/ProductKeywordService.java @@ -0,0 +1,36 @@ +package com.example.mutbooks.app.productKeyword.service; + +import com.example.mutbooks.app.productKeyword.entity.ProductKeyword; +import com.example.mutbooks.app.productKeyword.repository.ProductKeywordRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class ProductKeywordService { + private final ProductKeywordRepository productKeywordRepository; + + // 도서 해시태그 키워드 저장 + @Transactional + public ProductKeyword save(String content) { + Optional optionalProductKeyword = productKeywordRepository.findByContent(content); + + // 1. 해당 키워드가(content)가 DB에 있으면 바로 리턴 + if (optionalProductKeyword.isPresent()) { + return optionalProductKeyword.get(); + } + + // 2. 해당 키워드(content)가 DB에 없으면 저장 + ProductKeyword productKeyword = ProductKeyword.builder() + .content(content) + .build(); + + productKeywordRepository.save(productKeyword); + + return productKeyword; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/rebate/controller/AdmRebateController.java b/mutbooks/src/main/java/com/example/mutbooks/app/rebate/controller/AdmRebateController.java new file mode 100644 index 0000000..2d92d39 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/rebate/controller/AdmRebateController.java @@ -0,0 +1,93 @@ +package com.example.mutbooks.app.rebate.controller; + +import com.example.mutbooks.app.rebate.entity.RebateOrderItem; +import com.example.mutbooks.app.rebate.form.RebateDataForm; +import com.example.mutbooks.app.rebate.service.RebateService; +import lombok.RequiredArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.*; + +import java.util.Arrays; +import java.util.List; + +@Controller +@RequiredArgsConstructor +@RequestMapping("/adm/rebate") +public class AdmRebateController { + private final RebateService rebateService; + + // 정산 데이터 생성폼 + @PreAuthorize("isAuthenticated() and hasAuthority('ADMIN')") + @GetMapping("/makeData") + public String showMakeData() { + return "/adm/rebate/makeData"; + } + + // 정산 데이터 생성 + @PreAuthorize("isAuthenticated() and hasAuthority('ADMIN')") + @PostMapping("/makeData") + public String makeData(RebateDataForm rebateDataForm, BindingResult bindingResult) { + if (bindingResult.hasErrors()) { + return "/adm/rebate/makeData"; + } + + int year = rebateDataForm.getYear(); + int month = rebateDataForm.getMonth(); + rebateService.makeData(year, month); + + // 정산 데이터 리스트 조회 페이지로 리다이렉트 + return "redirect:/adm/rebate/rebateOrderItemList?year=%d&month=%d".formatted(year, month); + } + + // 정산 데이터 리스트 조회 + @PreAuthorize("isAuthenticated() and hasAuthority('ADMIN')") + @GetMapping("/rebateOrderItemList") + public String showRebateOrderItemList( + @RequestParam(required = false) Integer year, + @RequestParam(required = false) Integer month, + Model model + ) { + List items = null; + + if(year == null || month == null) { + // 전체 조회 + items = rebateService.findRebateOrderItems(); + } else { + // 월별 조회 + items = rebateService.findRebateOrderItemsByPayDateIn(year, month); + } + model.addAttribute("items", items); + + return "/adm/rebate/rebateOrderItemList"; + } + + // 건별 정산 + @PreAuthorize("isAuthenticated() and hasAuthority('ADMIN')") + @PostMapping("/rebateOne/{rebateOrderItemId}") + public String rebateOne(@PathVariable long rebateOrderItemId) { + rebateService.rebate(rebateOrderItemId); + + // 정산 데이터 리스트 조회 페이지로 리다이렉트 + return "redirect:/adm/rebate/rebateOrderItemList"; + } + + // 선택 정산 + @PreAuthorize("isAuthenticated() and hasAuthority('ADMIN')") + @PostMapping("/rebate") + public String rebateAll(String ids) { + // TODO: 서비스단으로 옮겨야하는지 고민해보기 + // 정산 처리해야하는 rebateOrderItem id 리스트 + String[] idsArr = ids.split(","); + Arrays.stream(idsArr) + .mapToLong(Long::parseLong) + .forEach(id -> { + rebateService.rebate(id); + }); + + // 정산 데이터 리스트 조회 페이지로 리다이렉트 + return "redirect:/adm/rebate/rebateOrderItemList"; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/rebate/entity/RebateOrderItem.java b/mutbooks/src/main/java/com/example/mutbooks/app/rebate/entity/RebateOrderItem.java new file mode 100644 index 0000000..490793e --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/rebate/entity/RebateOrderItem.java @@ -0,0 +1,139 @@ +package com.example.mutbooks.app.rebate.entity; + +import com.example.mutbooks.app.base.entity.BaseEntity; +import com.example.mutbooks.app.cash.entity.CashLog; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.order.entity.Order; +import com.example.mutbooks.app.order.entity.OrderItem; +import com.example.mutbooks.app.product.entity.Product; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.SuperBuilder; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Entity +@Getter +@Setter +@SuperBuilder +@NoArgsConstructor +@ToString(callSuper = true) +public class RebateOrderItem extends BaseEntity { + @OneToOne(fetch = FetchType.LAZY) + @ToString.Exclude + @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private OrderItem orderItem; // 주문품목 번호 + private LocalDateTime orderItemCreateDate; // 주문품목 생성일시 + + /** + * orderItem + */ + @ManyToOne(fetch = FetchType.LAZY) + @ToString.Exclude + @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private Order order; // 주문번호 + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private Product product; // 상품번호 + private String productSubject; // 상품명 + + private LocalDateTime payDate; // 결제 일시 + private LocalDateTime refundDate; // 환불 일시 + + private int price; // 권장 판매가 + private int salePrice; // 실제 판매가 + private int wholesalePrice; // 도매가 + private int pgFee; // 결제대행사 수수료 + private int payPrice; // 결제 금액 + private int refundPrice; // 환불 금액 + + private boolean isPaid; // 결제 여부 + private boolean isRefunded; // 환불 여부 + + /** + * member + */ + // 구매자 회원 + @ManyToOne(fetch = FetchType.LAZY) + @ToString.Exclude + @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private Member buyer; // 구매자 + private String buyerName; // 구매자명 + + // 판매자 회원 + @ManyToOne(fetch = FetchType.LAZY) + @ToString.Exclude + @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private Member seller; // 판매자 + private String sellerName; // 판매자명 + + /** + * CashLog + */ + @ManyToOne(fetch = FetchType.LAZY) + @ToString.Exclude + @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private CashLog rebateCashLog; // 정산금액 지급 내역 + private LocalDateTime rebateDate; // 정산금액 지급 일시 + private boolean isRebated; // 정산 여부 + + public RebateOrderItem(OrderItem orderItem) { + this.orderItem = orderItem; + + order = orderItem.getOrder(); + product = orderItem.getProduct(); + price = orderItem.getPrice(); + salePrice = orderItem.getSalePrice(); + wholesalePrice = orderItem.getWholesalePrice(); + pgFee = orderItem.getPgFee(); + payPrice = orderItem.getPayPrice(); + refundPrice = orderItem.getRefundPrice(); + payDate = orderItem.getPayDate(); + refundDate = orderItem.getRefundDate(); + isPaid = orderItem.isPaid(); + isRefunded = orderItem.isRefunded(); + + // 상품 추가데이터 + productSubject = orderItem.getProduct().getSubject(); + + // 주문품목 추가데이터 + orderItemCreateDate = orderItem.getCreateDate(); + + // 구매자 추가데이터 + buyer = orderItem.getOrder().getBuyer(); + buyerName = orderItem.getOrder().getBuyer().getUsername(); + + // 판매자 추가데이터 + seller = orderItem.getProduct().getAuthor(); + sellerName = orderItem.getProduct().getAuthor().getUsername(); + } + + // 예상 정산 금액 계산 + public int calculateRebatePrice() { + if(isRefunded) { + return 0; + } + // 정산금액 = 도매가 - PG 수수료 + return wholesalePrice - pgFee; + } + + // 정산 가능 여부 + public boolean isRebateAvailable() { + // 전액 환불건 or 정산 완료건은 정산 불가 + if(isRefunded || isRebated) { + return false; + } + return true; + } + + // 정산 완료 처리 + public void setRebateDone(CashLog cashLog) { + rebateDate = LocalDateTime.now(); + rebateCashLog = cashLog; + isRebated = true; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/rebate/exception/RebateOrderItemNotFoundException.java b/mutbooks/src/main/java/com/example/mutbooks/app/rebate/exception/RebateOrderItemNotFoundException.java new file mode 100644 index 0000000..38b72b6 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/rebate/exception/RebateOrderItemNotFoundException.java @@ -0,0 +1,7 @@ +package com.example.mutbooks.app.rebate.exception; + +public class RebateOrderItemNotFoundException extends RuntimeException { + public RebateOrderItemNotFoundException(String message) { + super(message); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/rebate/form/RebateDataForm.java b/mutbooks/src/main/java/com/example/mutbooks/app/rebate/form/RebateDataForm.java new file mode 100644 index 0000000..0c4c51d --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/rebate/form/RebateDataForm.java @@ -0,0 +1,15 @@ +package com.example.mutbooks.app.rebate.form; + +import lombok.Getter; +import lombok.Setter; + +import javax.validation.constraints.NotNull; + +@Getter +@Setter +public class RebateDataForm { + @NotNull(message = "년도를 선택해주세요.") + private int year; + @NotNull(message = "월을 선택해주세요.") + private int month; +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/rebate/repository/RebateOrderItemRepository.java b/mutbooks/src/main/java/com/example/mutbooks/app/rebate/repository/RebateOrderItemRepository.java new file mode 100644 index 0000000..e2b53f3 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/rebate/repository/RebateOrderItemRepository.java @@ -0,0 +1,16 @@ +package com.example.mutbooks.app.rebate.repository; + +import com.example.mutbooks.app.rebate.entity.RebateOrderItem; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +public interface RebateOrderItemRepository extends JpaRepository { + Optional findByOrderItemId(Long orderItemId); + + List findAllByPayDateBetweenOrderByIdAsc(LocalDateTime startOfDay, LocalDateTime endOfDay); + + List findAllByOrderById(); +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/rebate/service/RebateService.java b/mutbooks/src/main/java/com/example/mutbooks/app/rebate/service/RebateService.java new file mode 100644 index 0000000..56752eb --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/rebate/service/RebateService.java @@ -0,0 +1,120 @@ +package com.example.mutbooks.app.rebate.service; + +import com.example.mutbooks.app.cash.entity.CashLog; +import com.example.mutbooks.app.member.service.MemberService; +import com.example.mutbooks.app.order.entity.OrderItem; +import com.example.mutbooks.app.order.service.OrderService; +import com.example.mutbooks.app.rebate.entity.RebateOrderItem; +import com.example.mutbooks.app.rebate.exception.RebateOrderItemNotFoundException; +import com.example.mutbooks.app.rebate.repository.RebateOrderItemRepository; +import com.example.mutbooks.util.Ut; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class RebateService { + private final OrderService orderService; + private final MemberService memberService; + private final RebateOrderItemRepository rebateOrderItemRepository; + + // 정산 데이터 생성 + @Transactional + public void makeData(int year, int month) { + int endDay = Ut.date.getEndDay(year, month); + + // TODO: 테스트를 위해 잠시 주석 처리 + // 해당 달 정산 데이터는 다음 달 15일 새벽 4시 이후에 가능 +// if(!canMakeData(year, month)) { +// +// } + + // 1. 정산 데이터를 생성할 날짜 범위 구하기 + LocalDateTime startOfDay = Ut.date.getStartOfDay(year, month, 1); // 해당일자의 시작일시 + LocalDateTime endOfDay = Ut.date.getEndOfDay(year, month, endDay); // 해당일자의 종료일시 + + // 2. 해당 범위의 모든 주문 품목 조회 + List orderItems = orderService.findAllByPayDateBetweenOrderByIdAsc(startOfDay, endOfDay); + + // 3. 주문 데이터 -> 정산 데이터 변환 + List rebateOrderItems = orderItems.stream() + .map(this::toRebateOrderItem) + .collect(Collectors.toList()); + + // 4. 정산 데이터 생성 + rebateOrderItems.forEach(this::makeRebateOrderItem); + } + + // RebateOrderItem 생성 + private void makeRebateOrderItem(RebateOrderItem rebateOrderItem) { + RebateOrderItem oldRebateOrderItem = rebateOrderItemRepository.findByOrderItemId(rebateOrderItem.getOrderItem().getId()) + .orElse(null); + // TODO: 이미 생성된 정산 데이터가 있으면 삭제하고 다시 만들기 + if(oldRebateOrderItem != null) { + rebateOrderItemRepository.delete(oldRebateOrderItem); + } + rebateOrderItemRepository.save(rebateOrderItem); + } + + // OrderItem -> RebateOrderItem 변환 + private RebateOrderItem toRebateOrderItem(OrderItem orderItem) { + return new RebateOrderItem(orderItem); + } + + // 정산 데이터 생성 가능한지 검증 + public boolean canMakeData(int year, int month) { + LocalDateTime dataCreationDate = LocalDateTime.of(year, month, 15, 4, 0) + .plusMonths(1); // 정산 데이터 예상 생성일시 + // 현재 날짜 기준 해당 월의 정산 데이터를 생성가능한지 검증 + if(LocalDateTime.now().isBefore(dataCreationDate)) { + throw new RuntimeException("%d-%2d 의 정산 데이터 생성은 %s 이후에 가능합니다.".formatted( + year, month, + dataCreationDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")) + )); + } + return true; + } + + // 해당 년월의 정산 데이터 조회 + public List findRebateOrderItemsByPayDateIn(int year, int month) { + int endDay = Ut.date.getEndDay(year, month); + LocalDateTime startOfDay = Ut.date.getStartOfDay(year, month, 1); // 해당일자의 시작일시 + LocalDateTime endOfDay = Ut.date.getEndOfDay(year, month, endDay); // 해당일자의 종료일시 + + return rebateOrderItemRepository.findAllByPayDateBetweenOrderByIdAsc(startOfDay, endOfDay); + } + + public List findRebateOrderItems() { + return rebateOrderItemRepository.findAllByOrderById(); + } + + // 단건 정산 처리 + @Transactional + public void rebate(long rebateOrderItemId) { + RebateOrderItem rebateOrderItem = findById(rebateOrderItemId); + // 1. 정산 가능 상태인지 검증 + if(!rebateOrderItem.isRebateAvailable()) { + throw new RuntimeException("정산 처리가 가능한 상태가 아닙니다."); + } + // 2. 판매자에게 예치금으로 정산금액 지급 + CashLog cashLog = memberService.addCash( + rebateOrderItem.getSeller(), + rebateOrderItem.calculateRebatePrice(), + "정산금액지급__캐시__정산__%d".formatted(rebateOrderItem.getOrderItem().getId())); + // 3. 정산 완료 처리 + rebateOrderItem.setRebateDone(cashLog); + } + + public RebateOrderItem findById(long rebateOrderItemId) { + return rebateOrderItemRepository.findById(rebateOrderItemId).orElseThrow(() -> { + throw new RebateOrderItemNotFoundException("정산 데이터가 존재하지않습니다."); + }); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/security/ApiSecurityConfig.java b/mutbooks/src/main/java/com/example/mutbooks/app/security/ApiSecurityConfig.java new file mode 100644 index 0000000..9c1dc08 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/security/ApiSecurityConfig.java @@ -0,0 +1,70 @@ +package com.example.mutbooks.app.security; + +import com.example.mutbooks.app.security.filter.JwtAuthorizationFilter; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS; + +@EnableWebSecurity +@RequiredArgsConstructor +public class ApiSecurityConfig { + private final JwtAuthorizationFilter jwtAuthorizationFilter; +// private final ApiAuthenticationEntryPoint authenticationEntryPoint; + + @Bean + public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception { + http + .antMatcher("/api/**") +// .exceptionHandling(exceptionHandling -> exceptionHandling +// .authenticationEntryPoint(authenticationEntryPoint) +// ) + // jwt 사용 기본 설정 + .httpBasic().disable() + .formLogin().disable() + .csrf().disable() + .sessionManagement(sessionManagement -> sessionManagement + .sessionCreationPolicy(STATELESS) + ) + // cors 허용 설정 + .cors(cors -> cors + .configurationSource(corsConfigurationSource()) + ) + .authorizeRequests( + authorizeRequests -> authorizeRequests + // 로그인 요청 외 모든 요청은 로그인 필수 + .antMatchers("/api/*/member/login").permitAll() + .anyRequest() + .authenticated() // 최소자격 : 로그인 + ) + // 필터 설정 + .addFilterBefore( + jwtAuthorizationFilter, + UsernamePasswordAuthenticationFilter.class + ) + .logout().disable(); + + return http.build(); + } + + // cors 허용 정책 설정 + @Bean + public CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration corsConfiguration = new CorsConfiguration(); + + corsConfiguration.addAllowedOrigin("*"); // 모든 URL 허용 + corsConfiguration.addAllowedHeader("*"); // 모든 Header 허용 + corsConfiguration.addAllowedMethod("*"); // 모든 HTTP METHOD 허용 + + UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); + urlBasedCorsConfigurationSource.registerCorsConfiguration("/api/**", corsConfiguration); + return urlBasedCorsConfigurationSource; + } +} \ No newline at end of file diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/security/SecurityConfig.java b/mutbooks/src/main/java/com/example/mutbooks/app/security/SecurityConfig.java new file mode 100644 index 0000000..705ede8 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/security/SecurityConfig.java @@ -0,0 +1,46 @@ +package com.example.mutbooks.app.security; + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.web.SecurityFilterChain; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +@RequiredArgsConstructor +public class SecurityConfig { +// private final AuthenticationSuccessHandler authenticationSuccessHandler; +// private final AuthenticationFailureHandler authenticationFailureHandler; + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http + .httpBasic().disable() + .formLogin( + formLogin -> formLogin + .loginPage("/member/login") // GET + .loginProcessingUrl("/member/login") // POST +// .successHandler(authenticationSuccessHandler) +// .failureHandler(authenticationFailureHandler) + ) + .authorizeRequests( + authorizeRequests -> authorizeRequests + // spring doc 관리자 회원만 허용 + .antMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html") + .hasAuthority("ADMIN") + .anyRequest() + .permitAll() + ) + .logout( + logout -> logout.logoutUrl("/member/logout") + // 로그아웃 후 기본 이동경로 = /login?logout + ) + .csrf().disable(); // CSRF 토큰 끄기; + + return http.build(); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/security/dto/MemberContext.java b/mutbooks/src/main/java/com/example/mutbooks/app/security/dto/MemberContext.java new file mode 100644 index 0000000..d59dd36 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/security/dto/MemberContext.java @@ -0,0 +1,80 @@ +package com.example.mutbooks.app.security.dto; + +import com.example.mutbooks.app.member.entity.Member; +import lombok.Getter; +import lombok.Setter; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.User; + +import java.time.LocalDateTime; +import java.util.List; + +@Getter +public class MemberContext extends User { + private final Long id; + private final LocalDateTime createDate; + @Setter + private LocalDateTime updateDate; + private final String username; + @Setter + private String email; + @Setter + private String nickname; + + // 예치금 + @Setter + private int restCash; + + // 임시 추가 필드 +// @Setter +// private String bankName; +// @Setter +// private String bankAccountNo; + + public MemberContext(Member member, List authorities) { + super(member.getUsername(), member.getPassword(), authorities); + this.id = member.getId(); + this.createDate = member.getCreateDate(); + this.updateDate = member.getUpdateDate(); + this.username = member.getUsername(); + this.email = member.getEmail(); + this.nickname = member.getNickname(); + // 예치금 추가 + this.restCash = member.getRestCash(); + // 임시 추가 +// this.bankName = member.getBankName(); +// this.bankAccountNo = member.getBankAccountNo(); + } + + public Member getMember() { + return Member + .builder() + .id(id) + .createDate(createDate) + .updateDate(updateDate) + .username(username) + .email(email) + .nickname(nickname) + // 예치금 추가 + .restCash(restCash) + // 임시 추가 +// .bankName(bankName) +// .bankAccountNo(bankAccountNo) + .build(); + } + + public MemberContext(Member member) { + super(member.getUsername(), "", member.getAuthorities()); + + id = member.getId(); + createDate = member.getCreateDate(); + updateDate = member.getUpdateDate(); + username = member.getUsername(); + email = member.getEmail(); +// authorities = member.getAuthorities().stream().collect(Collectors.toSet()); + } + + public String getName() { + return getUsername(); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java b/mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java new file mode 100644 index 0000000..c6e4a05 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/security/filter/JwtAuthorizationFilter.java @@ -0,0 +1,74 @@ +package com.example.mutbooks.app.security.filter; + +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.member.service.MemberService; +import com.example.mutbooks.app.security.dto.MemberContext; +import com.example.mutbooks.app.security.jwt.JwtProvider; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Map; + +/** + * 매 요청마다 컨트롤러에 요청이 도달하기 전에 필터를 거쳐 인증/인가 수행 + * 1. 요청 헤더의 Access Token 유효성 검증 + * 2. 토큰으로부터 회원 정보(claims)를 이용해 DB에서 Member 객체 조회 + * 3. 해당 회원 강제 로그인 처리(MemberContext 세션 등록) + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class JwtAuthorizationFilter extends OncePerRequestFilter { + private final JwtProvider jwtProvider; + private final MemberService memberService; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + String bearerToken = request.getHeader("Authorization"); + // 1. 1차 체크(정보가 변조되지 않았는지 검증) + if(bearerToken != null) { + // accessToken 에서 회원 정보 가져오려면 Authorization 에서 Bearer 제거 필요 + String token = bearerToken.split(" ")[1]; + // 토큰이 유효하면 회원 정보 얻어서 강제 로그인 처리 + if(jwtProvider.verify(token)) { + Map claims = jwtProvider.getClaims(token); + String username = (String) claims.get("username"); + Member member = memberService.findByUsername(username); + + // 2. 2차 체크(해당 엑세스 토큰이 화이트 리스트에 포함되는지 검증) + if (memberService.verifyWithWhiteList(member, token)) { + // 강제 로그인 처리 + forceAuthentication(member); + } + } + } + filterChain.doFilter(request, response); + } + + // 강제 로그인 처리 + private void forceAuthentication(Member member) { + MemberContext memberContext = new MemberContext(member); + + UsernamePasswordAuthenticationToken authentication = + UsernamePasswordAuthenticationToken.authenticated( + memberContext, + null, + member.getAuthorities() + ); + + // 이후 컨트롤러 단에서 MemberContext 객체 사용O + SecurityContext context = SecurityContextHolder.createEmptyContext(); + context.setAuthentication(authentication); + SecurityContextHolder.setContext(context); + } +} \ No newline at end of file diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtConfig.java b/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtConfig.java new file mode 100644 index 0000000..963942d --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtConfig.java @@ -0,0 +1,26 @@ +package com.example.mutbooks.app.security.jwt; + +import io.jsonwebtoken.security.Keys; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.crypto.SecretKey; +import java.util.Base64; + +/** + * JwtConfig + * - JWT 비밀키 관리 + */ +@Configuration +public class JwtConfig { + @Value("${custom.jwt.secretKey}") + private String secretKeyPlain; // 비밀키 원문 + + // JWT 비밀키 싱글톤 빈 관리 + @Bean + public SecretKey jwtSecretKey() { + String keyBase64Encoded = Base64.getEncoder().encodeToString(secretKeyPlain.getBytes()); + return Keys.hmacShaKeyFor(keyBase64Encoded.getBytes()); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java b/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java new file mode 100644 index 0000000..cc802cf --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/security/jwt/JwtProvider.java @@ -0,0 +1,69 @@ +package com.example.mutbooks.app.security.jwt; + +import com.example.mutbooks.util.Ut; +import io.jsonwebtoken.ExpiredJwtException; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import java.util.Date; +import java.util.Map; + +/** + * JwtProvider + * - JWT 토큰 생성, 검증에 관여 + */ +@Component +@RequiredArgsConstructor +public class JwtProvider { + private final SecretKey jwtSecretKey; // 비밀키 + private long ACCESS_TOKEN_VALIDATION_SECOND = 60 * 60 * 24 * 365 * 100L; // accessToken 유효시간(100년) + + private SecretKey getSecretKey() { + return jwtSecretKey; + } + + // JWT Access Token 발급 + public String generateAccessToken(Map claims) { + long now = new Date().getTime(); + Date accessTokenExpiresIn = new Date(now + 1000L * ACCESS_TOKEN_VALIDATION_SECOND); + + return Jwts.builder() + .claim("body", Ut.json.toStr(claims)) // Claims 정보 설정 + .setExpiration(accessTokenExpiresIn) // accessToken 만료 시간 설정 + .signWith(getSecretKey(), SignatureAlgorithm.HS512) // HS512, 비밀키로 서명 + .compact(); // 토큰 생성 + } + + // JWT Access Token 검증 + public boolean verify(String accessToken) { + try { + Jwts.parserBuilder() + .setSigningKey(getSecretKey()) // 비밀키 + .build() + .parseClaimsJws(accessToken); // 파싱 및 검증(실패시 에러) + } catch (ExpiredJwtException e) { + // 토큰이 만료되었을 경우 + return false; + } + catch (Exception e) { + // 그 외 에러 + return false; + } + return true; + } + + // accessToken 으로부터 Claim 정보 얻기 + public Map getClaims(String accessToken) { + String body = Jwts.parserBuilder() + .setSigningKey(getSecretKey()) + .build() + .parseClaimsJws(accessToken) + .getBody() + .get("body", String.class); + + return Ut.json.toMap(body); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/security/service/CustomUserDetailsService.java b/mutbooks/src/main/java/com/example/mutbooks/app/security/service/CustomUserDetailsService.java new file mode 100644 index 0000000..a212f82 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/security/service/CustomUserDetailsService.java @@ -0,0 +1,28 @@ +package com.example.mutbooks.app.security.service; + +import com.example.mutbooks.app.security.dto.MemberContext; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.member.repository.MemberRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +@RequiredArgsConstructor +public class CustomUserDetailsService implements UserDetailsService { + private final MemberRepository memberRepository; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + Member member = memberRepository.findByUsername(username).get(); + + List authorities = member.getAuthorities(); + + return new MemberContext(member, authorities); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/AdmWithdrawController.java b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/AdmWithdrawController.java new file mode 100644 index 0000000..72e1d98 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/AdmWithdrawController.java @@ -0,0 +1,54 @@ +package com.example.mutbooks.app.withdraw.controller; + +import com.example.mutbooks.app.security.dto.MemberContext; +import com.example.mutbooks.app.withdraw.entity.WithdrawApply; +import com.example.mutbooks.app.withdraw.service.WithdrawService; +import lombok.RequiredArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import java.util.List; + +@Controller +@RequiredArgsConstructor +@RequestMapping("/adm/withdraw") +public class AdmWithdrawController { + private final WithdrawService withdrawService; + + // 출금 신청 내역 조회 + @PreAuthorize("hasAuthority('ADMIN')") + @GetMapping("/applyList") + public String showApplyList(Model model) { + List withdrawApplies = withdrawService.findAll(); + model.addAttribute("withdrawApplies", withdrawApplies); + + return "adm/withdraw/apply_list"; + } + + // 출금 신청 내역 조회 + @PreAuthorize("hasAuthority('ADMIN')") + @PostMapping("/{withdrawApplyId}") + public String withdraw(@PathVariable long withdrawApplyId) { + withdrawService.withdraw(withdrawApplyId); + + return "redirect:/adm/withdraw/applyList"; + } + + // 출금 취소(관리자) + @PreAuthorize("hasAuthority('ADMIN')") + @PostMapping("/cancel/{withdrawApplyId}") + public String cancel( + @PathVariable long withdrawApplyId, + @AuthenticationPrincipal MemberContext memberContext + ) { + withdrawService.cancelByAdmin(memberContext.getUsername(), withdrawApplyId); + // 출금 신청 내역 페이지로 리다이렉트 + return "redirect:/withdraw/applyList"; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/WithdrawController.java b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/WithdrawController.java new file mode 100644 index 0000000..9a2cbee --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/controller/WithdrawController.java @@ -0,0 +1,81 @@ +package com.example.mutbooks.app.withdraw.controller; + +import com.example.mutbooks.app.security.dto.MemberContext; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.member.service.MemberService; +import com.example.mutbooks.app.withdraw.entity.WithdrawApply; +import com.example.mutbooks.app.withdraw.form.WithdrawApplyForm; +import com.example.mutbooks.app.withdraw.service.WithdrawService; +import lombok.RequiredArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import javax.validation.Valid; +import java.util.List; + +@Controller +@RequiredArgsConstructor +@RequestMapping("/withdraw") +public class WithdrawController { + private final MemberService memberService; + private final WithdrawService withdrawService; + + // 출금 신청 폼 + @PreAuthorize("isAuthenticated()") + @GetMapping("/apply") + public String showApply(@AuthenticationPrincipal MemberContext memberContext, WithdrawApplyForm withdrawApplyForm, Model model) { + Member member = memberService.findByUsername(memberContext.getUsername()); + // 출금 계좌 정보가 존재하지 않으면, 출금 계좌 관리 페이지로 리다이렉트 + if(!member.hasBankInfo()) { + return "redirect:/member/manageWithdrawAccount"; + } + model.addAttribute("member", member); + + return "withdraw/apply"; + } + + // 출금 신청 + @PreAuthorize("isAuthenticated()") + @PostMapping("/apply") + public String apply( + @AuthenticationPrincipal MemberContext memberContext, + @Valid WithdrawApplyForm withdrawApplyForm, BindingResult bindingResult + ) { + if(bindingResult.hasErrors()) { + return "withdraw/apply"; + } + + withdrawService.apply(memberContext.getUsername(), withdrawApplyForm); + // 출금 신청 내역 페이지로 리다이렉트 + return "redirect:/withdraw/applyList"; + } + + // 출금 신청 내역 조회 + @PreAuthorize("isAuthenticated()") + @GetMapping("/applyList") + public String showApplyList(@AuthenticationPrincipal MemberContext memberContext, Model model) { + List withdrawApplies = withdrawService.findByApplicantIdOrderByIdDesc(memberContext.getId()); + model.addAttribute("withdrawApplies", withdrawApplies); + + return "withdraw/apply_list"; + } + + // 출금 취소 + @PreAuthorize("isAuthenticated()") + @PostMapping("/cancel/{withdrawApplyId}") + public String cancel( + @PathVariable long withdrawApplyId, + @AuthenticationPrincipal MemberContext memberContext + ) { + withdrawService.cancel(memberContext.getUsername(), withdrawApplyId); + // 출금 신청 내역 페이지로 리다이렉트 + return "redirect:/withdraw/applyList"; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/entity/CancelType.java b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/entity/CancelType.java new file mode 100644 index 0000000..face574 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/entity/CancelType.java @@ -0,0 +1,28 @@ +package com.example.mutbooks.app.withdraw.entity; + +import lombok.Getter; + +import java.util.Arrays; + +@Getter +public enum CancelType { + USER_REQUEST(1, "사용자 요청"), + ADMIN_REQUEST(2, "관리자 요청"); + + private final int code; + private final String value; + + CancelType(int code, String value) { + this.code = code; + this.value = value; + } + + // Enum 에서 code 값으로 해당 Enum 을 찾는 메서드 + public static CancelType ofCode(String value) { + if(value == null) return null; + return Arrays.stream(CancelType.values()) + .filter(v -> v.getValue().equals(value)) + .findFirst() + .orElseThrow(() -> new RuntimeException(String.format("value=[%s]가 존재하지 않습니다.", value))); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/entity/CancelTypeConverter.java b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/entity/CancelTypeConverter.java new file mode 100644 index 0000000..8bf2d18 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/entity/CancelTypeConverter.java @@ -0,0 +1,28 @@ +package com.example.mutbooks.app.withdraw.entity; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; + +/** + * AttributeConverter X, Y + * X : 엔티티의 속성에 대응하는 타입 + * Y : DB 에 대응하는 타입 + */ +@Converter +public class CancelTypeConverter implements AttributeConverter { + + // Enum -> db 데이터(value:String) + @Override + public String convertToDatabaseColumn(CancelType attribute) { + if(attribute == null) + return null; + + return attribute.getValue(); + } + + // db 데이터(value:String) -> Enum + @Override + public CancelType convertToEntityAttribute(String dbData) { + return CancelType.ofCode(dbData); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/entity/WithdrawApply.java b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/entity/WithdrawApply.java new file mode 100644 index 0000000..e4e3629 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/entity/WithdrawApply.java @@ -0,0 +1,77 @@ +package com.example.mutbooks.app.withdraw.entity; + +import com.example.mutbooks.app.base.entity.BaseEntity; +import com.example.mutbooks.app.cash.entity.CashLog; +import com.example.mutbooks.app.member.entity.Member; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.SuperBuilder; + +import javax.persistence.Convert; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.ManyToOne; +import java.time.LocalDateTime; + +@Entity +@Getter +@Setter +@SuperBuilder +@NoArgsConstructor +@ToString(callSuper = true) +public class WithdrawApply extends BaseEntity { + @ManyToOne(fetch = FetchType.LAZY) + private Member applicant; // 신청자 + + @ManyToOne(fetch = FetchType.LAZY) + private CashLog withdrawCashLog; // 출금 관련 캐시 내역 + + private String bankName; // 출금 신청 은행명 + private String bankAccountNo; // 출금 신청 계좌번호 + private int price; // 출금 신청 금액 + private LocalDateTime withdrawDate; // 출금 일시 + private LocalDateTime cancelDate; // 출금 취소 일시 + private boolean isWithdrawn; // 출금 여부 + private boolean isCancelled; // 출금 신청 취소 여부 + @Convert(converter = CancelTypeConverter.class) + private CancelType cancelType; // 취소 사유 + + // 신청 완료 여부 + public boolean isAppliedStatus() { + if(!isWithdrawn && !isCancelled) { + return true; + } + return false; + } + + // 출금 완료 + public boolean isWithdrawnStatus() { + if(isWithdrawn) { + return true; + } + return false; + } + + // 취소 완료 + public boolean isCancelledStatus() { + if(isCancelled) { + return true; + } + return false; + } + + // 출금 완료 처리 + public void setWithdrawDone() { + isWithdrawn = true; + withdrawDate = LocalDateTime.now(); + } + + // 출금 취소 처리 + public void setCancelDone(CancelType cancelType) { + this.cancelType = cancelType; + this.isCancelled = true; + this.cancelDate = LocalDateTime.now(); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/exception/WithdrawApplyNotFoundException.java b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/exception/WithdrawApplyNotFoundException.java new file mode 100644 index 0000000..8983af9 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/exception/WithdrawApplyNotFoundException.java @@ -0,0 +1,7 @@ +package com.example.mutbooks.app.withdraw.exception; + +public class WithdrawApplyNotFoundException extends RuntimeException { + public WithdrawApplyNotFoundException(String message) { + super(message); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/form/WithdrawApplyForm.java b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/form/WithdrawApplyForm.java new file mode 100644 index 0000000..cda8039 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/form/WithdrawApplyForm.java @@ -0,0 +1,16 @@ +package com.example.mutbooks.app.withdraw.form; + +import lombok.Getter; +import lombok.Setter; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; + +@Getter +@Setter +public class WithdrawApplyForm { + // 최소 출금 신청 금액 = 1000원 + @Min(value = 1000, message = "1회 최소 출금 가능한 금액은 1천원입니다.") + @NotNull(message = "출금 금액을 입력해주세요.") + private int price; // 출금 금액 +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/repository/WithdrawApplyRepository.java b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/repository/WithdrawApplyRepository.java new file mode 100644 index 0000000..d0045a4 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/repository/WithdrawApplyRepository.java @@ -0,0 +1,10 @@ +package com.example.mutbooks.app.withdraw.repository; + +import com.example.mutbooks.app.withdraw.entity.WithdrawApply; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface WithdrawApplyRepository extends JpaRepository { + List findByApplicantIdOrderByIdDesc(Long applicantId); +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/service/WithdrawService.java b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/service/WithdrawService.java new file mode 100644 index 0000000..bea9fbc --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/app/withdraw/service/WithdrawService.java @@ -0,0 +1,104 @@ +package com.example.mutbooks.app.withdraw.service; + +import com.example.mutbooks.app.cash.entity.CashLog; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.member.service.MemberService; +import com.example.mutbooks.app.withdraw.entity.CancelType; +import com.example.mutbooks.app.withdraw.entity.WithdrawApply; +import com.example.mutbooks.app.withdraw.exception.WithdrawApplyNotFoundException; +import com.example.mutbooks.app.withdraw.form.WithdrawApplyForm; +import com.example.mutbooks.app.withdraw.repository.WithdrawApplyRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class WithdrawService { + private final MemberService memberService; + private final WithdrawApplyRepository withdrawApplyRepository; + + @Transactional + public void apply(String username, WithdrawApplyForm withdrawApplyForm) { + Member applicant = memberService.findByUsername(username); + int price = withdrawApplyForm.getPrice(); // 출금 신청 금액 + + if(canWithdrawApply(applicant, price)) { + // 캐시 차감 처리 + CashLog withdrawCashLog = memberService.addCash(applicant, -1 * price, "출금"); + + WithdrawApply withdrawApply = WithdrawApply.builder() + .applicant(applicant) + .bankName(applicant.getMemberExtra().getBankName()) + .bankAccountNo(applicant.getMemberExtra().getBankAccountNo()) + .price(price) + .withdrawCashLog(withdrawCashLog) + .build(); + + withdrawApplyRepository.save(withdrawApply); + } + } + + // 출금 신청 가능 여부 검증 + public boolean canWithdrawApply(Member applicant, int price) { + // 보유 금액보다 많은 금액 출금 요청시 + if(applicant.getRestCash() < price) { + throw new RuntimeException("출금 신청 금액이 보유 금액보다 많습니다."); + } + return true; + } + + public List findByApplicantIdOrderByIdDesc(Long applicantId) { + return withdrawApplyRepository.findByApplicantIdOrderByIdDesc(applicantId); + } + + public List findAll() { + return withdrawApplyRepository.findAll(); + } + + public WithdrawApply findById(long id) { + return withdrawApplyRepository.findById(id).orElseThrow(() -> { + throw new WithdrawApplyNotFoundException("출금 신청 내역이 존재하지 않습니다."); + }); + } + + @Transactional + public void withdraw(long id) { + WithdrawApply withdrawApply = findById(id); + // TODO: 해당 계좌로 입금 요청 API 호출 + withdrawApply.setWithdrawDone(); + } + + // 사용자 본인 출금 취소 + @Transactional + public void cancel(String username, long id) { + WithdrawApply withdrawApply = findById(id); + Member member = memberService.findByUsername(username); + + if(canCancel(member, withdrawApply)) { + memberService.addCash(member, withdrawApply.getPrice(), "출금취소__캐시"); + withdrawApply.setCancelDone(CancelType.USER_REQUEST); + } + } + + // 관리자에 의한 출금 취소 + @Transactional + public void cancelByAdmin(String username, long id) { + WithdrawApply withdrawApply = findById(id); + Member member = memberService.findByUsername(username); + + memberService.addCash(member, withdrawApply.getPrice(), "출금취소__캐시"); + withdrawApply.setCancelDone(CancelType.ADMIN_REQUEST); + } + + // 취소 권한 검증 + public boolean canCancel(Member member, WithdrawApply withdrawApply) { + if(!member.getId().equals(withdrawApply.getApplicant().getId())) { + throw new RuntimeException("해당 출금 신청 내역의 취소 권한이 없습니다."); + } + return true; + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/job/makeRebateOrderItem/MakeRebateOrderItemJobConfig.java b/mutbooks/src/main/java/com/example/mutbooks/job/makeRebateOrderItem/MakeRebateOrderItemJobConfig.java new file mode 100644 index 0000000..b415498 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/job/makeRebateOrderItem/MakeRebateOrderItemJobConfig.java @@ -0,0 +1,114 @@ +package com.example.mutbooks.job.makeRebateOrderItem; + +import com.example.mutbooks.app.order.entity.OrderItem; +import com.example.mutbooks.app.order.repository.OrderItemRepository; +import com.example.mutbooks.app.rebate.entity.RebateOrderItem; +import com.example.mutbooks.app.rebate.repository.RebateOrderItemRepository; +import com.example.mutbooks.util.Ut; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.Job; +import org.springframework.batch.core.Step; +import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; +import org.springframework.batch.core.configuration.annotation.JobScope; +import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepScope; +import org.springframework.batch.item.ItemProcessor; +import org.springframework.batch.item.ItemReader; +import org.springframework.batch.item.ItemWriter; +import org.springframework.batch.item.data.RepositoryItemReader; +import org.springframework.batch.item.data.builder.RepositoryItemReaderBuilder; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.CommandLineRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.domain.Sort; + +import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.Collections; + +@Configuration +@RequiredArgsConstructor +@Slf4j +public class MakeRebateOrderItemJobConfig { + private final JobBuilderFactory jobBuilderFactory; + private final StepBuilderFactory stepBuilderFactory; + + private final OrderItemRepository orderItemRepository; // 읽기 대상 + private final RebateOrderItemRepository rebateOrderItemRepository; // 쓰기 대상 + + // 매월 15일 오전 4시 0분 0초에 이전 달(1일~말일) 정산 데이터 생성 + @Bean + public Job makeRebateOrderItemJob(Step makeRebateOrderItemStep1, CommandLineRunner initData) throws Exception { + log.info("makeRebateOrderItemJob 실행"); + initData.run(); + + return jobBuilderFactory.get("makeRebateOrderItemJob") + .start(makeRebateOrderItemStep1) + .build(); + } + + @Bean + @JobScope + public Step makeRebateOrderItemStep1( + ItemReader orderItemReader, + ItemProcessor orderItemToRebateOrderItemProcessor, + ItemWriter RebateOrderItemWriter + ) { + log.info("makeRebateOrderItemStep1 실행"); + return stepBuilderFactory.get("makeRebateOrderItemStep1") + .chunk(2) // 100개씩 처리 + .reader(orderItemReader) + .processor(orderItemToRebateOrderItemProcessor) + .writer(RebateOrderItemWriter) + .build(); + } + + @StepScope + @Bean + public RepositoryItemReader orderItemReader( + @Value("#{jobParameters[year]}") int year, + @Value("#{jobParameters[month]}") int month + ) { + log.info("orderItemReader 실행"); + log.info("%d-%d".formatted(year, month)); + // 1. 정산 데이터를 생성할 날짜 범위 구하기 + int endDay = Ut.date.getEndDay(year, month); + LocalDateTime startOfDay = Ut.date.getStartOfDay(year, month, 1); // 해당일자의 시작일시 + LocalDateTime endOfDay = Ut.date.getEndOfDay(year, month, endDay); // 해당일자의 종료일시 + // 2. 해당 범위의 모든 주문 품목 조회 + return new RepositoryItemReaderBuilder() + .name("orderItemReader") + .repository(orderItemRepository) + .methodName("findAllByPayDateBetween") + .pageSize(2) + .arguments(Arrays.asList(startOfDay, endOfDay)) // 메서드 인자 + .sorts(Collections.singletonMap("id", Sort.Direction.ASC)) + .build(); + } + + @StepScope + @Bean + public ItemProcessor orderItemToRebateOrderItemProcessor() { + log.info("orderItemToRebateOrderItemProcessor 실행"); + // 3. 주문 데이터 -> 정산 데이터 변환 + return orderItem -> new RebateOrderItem(orderItem); + } + + @StepScope + @Bean + public ItemWriter RebateOrderItemWriter() { + log.info("RebateOrderItemWriter 실행"); + // 4. 정산 데이터 생성 + return items -> items.forEach(item -> { + RebateOrderItem oldRebateOrderItem = rebateOrderItemRepository.findByOrderItemId(item.getOrderItem().getId()) + .orElse(null); + // 이미 생성된 정산 데이터가 있으면 삭제하고 다시 만들기 + if(oldRebateOrderItem != null) { + rebateOrderItemRepository.delete(oldRebateOrderItem); + } + rebateOrderItemRepository.save(item); + }); + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/scheduler/JobScheduler.java b/mutbooks/src/main/java/com/example/mutbooks/scheduler/JobScheduler.java new file mode 100644 index 0000000..7cecd7f --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/scheduler/JobScheduler.java @@ -0,0 +1,65 @@ +package com.example.mutbooks.scheduler; + +import com.example.mutbooks.job.makeRebateOrderItem.MakeRebateOrderItemJobConfig; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.Job; +import org.springframework.batch.core.JobParameter; +import org.springframework.batch.core.JobParameters; +import org.springframework.batch.core.JobParametersInvalidException; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException; +import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException; +import org.springframework.batch.core.repository.JobRestartException; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.Map; + +@Component +@RequiredArgsConstructor +@Slf4j +public class JobScheduler { + private final JobLauncher jobLauncher; // Job 실행 객체 + + private final MakeRebateOrderItemJobConfig makeRebateOrderItemJobConfig; + private final Job makeRebateOrderItemJob; // 빈으로 등록한 Job 을 주입받아 사용 + + + // 매달 15일 오전 4시에 Job 실행해야하지만, 오류를 고려하여 매일 오전 4시에 실행 +// @Scheduled(cron = "0 0 4 * * *") // TODO: 운영시 주석 해제 + @Scheduled(cron = "30 * * * * *") // 개발용(매분 30초마다 실행) + public void runJob() { + log.info("scheduler 실행 " + String.valueOf(LocalDateTime.now())); + + // 현재 일시 LocalDateTime -> String 변환한 값을 Job Parameter 에 담기 + Map confMap = new HashMap<>(); + LocalDateTime rebateDate = getMakeRebateDataDateTime(); + confMap.put("year", new JobParameter((long) rebateDate.getYear())); + confMap.put("month", new JobParameter((long) rebateDate.getMonthValue())); + JobParameters jobParameters = new JobParameters(confMap); + + try { + jobLauncher.run(makeRebateOrderItemJob, jobParameters); + } catch (JobExecutionAlreadyRunningException e) { + throw new RuntimeException(e); + } catch (JobRestartException e) { + throw new RuntimeException(e); + } catch (JobInstanceAlreadyCompleteException e) { + throw new RuntimeException(e); + } catch (JobParametersInvalidException e) { + throw new RuntimeException(e); + } + } + + // jobParameter 값 생성 + public LocalDateTime getMakeRebateDataDateTime() { + // 정산 데이터 생성 날짜 범위(15일 이후 = 1달 전, 15일 이전 = 2달 전) + // TODO : 운영시 주석 해제 +// return LocalDateTime.now().getDayOfMonth() >= 15 ? +// LocalDateTime.now().minusMonths(1) : LocalDateTime.now().minusMonths(2); + return LocalDateTime.now(); // 개발용 + } +} diff --git a/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java b/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java new file mode 100644 index 0000000..8fa4b17 --- /dev/null +++ b/mutbooks/src/main/java/com/example/mutbooks/util/Ut.java @@ -0,0 +1,135 @@ +package com.example.mutbooks.util; + +import com.example.mutbooks.app.AppConfig; +import com.example.mutbooks.app.base.dto.RsData; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.Calendar; +import java.util.LinkedHashMap; +import java.util.Map; + +public class Ut { + // jwt 관련 + private static ObjectMapper getObjectMapper() { + return (ObjectMapper) AppConfig.getContext().getBean("objectMapper"); + } + + public static class json { + + // map(json) -> String 변환 + public static Object toStr(Map map) { + try { + return getObjectMapper().writeValueAsString(map); + } catch (JsonProcessingException e) { + return null; + } + } + + // String -> map(json) 변환 + public static Map toMap(String jsonStr) { + try { + return getObjectMapper().readValue(jsonStr, LinkedHashMap.class); + } catch (JsonProcessingException e) { + return null; + } + } + } + // 추가 끝 + + + // 인자 값들을 map 형태로 반환 + public static Map mapOf(Object... args) { + Map map = new LinkedHashMap<>(); + + int size = args.length / 2; + + for (int i = 0; i < size; i++) { + int keyIndex = i * 2; + int valueIndex = keyIndex + 1; + + K key = (K) args[keyIndex]; + V value = (V) args[valueIndex]; + + map.put(key, value); + } + return map; + } + + public static class spring { + public static ResponseEntity responseEntityOf(RsData rsData) { + return responseEntityOf(rsData, null); + } + + public static ResponseEntity responseEntityOf(RsData rsData, HttpHeaders headers) { + HttpStatus httpStatus = rsData.isSuccess() ? HttpStatus.OK : HttpStatus.BAD_REQUEST; + // body, header, httpStatus + return new ResponseEntity<>(rsData, headers, httpStatus); + } + + // 들어온 인자를 (key, value) 형태의 HttpHeaders 로 반환 + public static HttpHeaders httpHeadersOf(String... args) { + HttpHeaders headers = new HttpHeaders(); + + // (key, value) + Map map = Ut.mapOf(args); + + for(String key : map.keySet()) { + String value = map.get(key); + headers.set(key, value); + } + + return headers; + } + } + + public static class date { + + // 해당 년, 월의 마지막 일자 구하기 + public static int getEndDay(int year, int month) { + Calendar cal = Calendar.getInstance(); + cal.set(year, month - 1, 1); + + return cal.getActualMaximum(Calendar.DAY_OF_MONTH); + } + + // 해당 일자의 시작일시 구하기 + public static LocalDateTime getStartOfDay(int year, int month, int day) { + LocalDate date = LocalDate.of(year, month, day); + return date.atStartOfDay(); + } + + // 해당 일자의 종료일시 구하기 + public static LocalDateTime getEndOfDay(int year, int month, int day) { + LocalDate date = LocalDate.of(year, month, day); + return date.atTime(LocalTime.MAX); + } + + // 날짜 문자열 -> 해당 패턴의 LocalDateTime 변환 + public static LocalDateTime parse(String pattern, String dateText) { + return LocalDateTime.parse(dateText, DateTimeFormatter.ofPattern(pattern)); + } + + // 날짜 문자열 -> 디폴트 패턴의 LocalDateTime 변환 + public static LocalDateTime parse(String dateText) { + return parse("yyyy-MM-dd HH:mm:ss.SSSSSS", dateText); + } + + // 해당 패턴의 LocalDateTime -> 날짜 문자열 변환 + public static String format(String pattern, LocalDateTime datetime) { + return datetime.format(DateTimeFormatter.ofPattern(pattern)); + } + + // 디폴트 패턴의 LocalDateTime -> 날짜 문자열 변환 + public static String format(LocalDateTime datetime) { + return format("yyyy-MM-dd HH:mm:ss.SSSSSS", datetime); + } + } +} diff --git a/mutbooks/src/main/resources/application-dev.yml b/mutbooks/src/main/resources/application-dev.yml new file mode 100644 index 0000000..2a8b91d --- /dev/null +++ b/mutbooks/src/main/resources/application-dev.yml @@ -0,0 +1,18 @@ +server: + port: 8010 +spring: + thymeleaf: + cache: false + prefix: file:src/main/resources/templates/ + devtools: + livereload: + enabled: true + restart: + enabled: true + datasource: + url: jdbc:mariadb://127.0.0.1:3306/mut_books__dev?useUnicode=true&characterEncoding=utf8&autoReconnect=true&serverTimezone=Asia/Seoul + username: root + password: '0114' + jpa: + hibernate: + ddl-auto: create \ No newline at end of file diff --git a/mutbooks/src/main/resources/application-test.yml b/mutbooks/src/main/resources/application-test.yml new file mode 100644 index 0000000..1d43bde --- /dev/null +++ b/mutbooks/src/main/resources/application-test.yml @@ -0,0 +1,8 @@ +spring: + datasource: + url: jdbc:mariadb://${testDbIp:127.0.0.1}:3306/mut_books__test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&serverTimezone=Asia/Seoul + username: ${testDbId:root} + password: ${testDbPw:0114} + jpa: + hibernate: + ddl-auto: create \ No newline at end of file diff --git a/mutbooks/src/main/resources/application.yml b/mutbooks/src/main/resources/application.yml new file mode 100644 index 0000000..2a49bc8 --- /dev/null +++ b/mutbooks/src/main/resources/application.yml @@ -0,0 +1,41 @@ +spring: + profiles: + active: dev + include: + - base-addi + batch: + job: + names: ${job.name:NONE} + enabled: false # 자동 Job 실행 막기 + jdbc: + initialize-schema: ALWAYS # batch 테이블 생성 + datasource: + driver-class-name: org.mariadb.jdbc.Driver + jpa: + properties: + hibernate: + show_sql: true + format_sql: true + use_sql_comments: true + mail: + host: smtp.gmail.com + port: 587 + username: + password: + properties: + mail: + smtp: + auth: true + starttls: + enable: true +logging: + level: + root: info + com.ll.exam.app__2022_10_11.app: debug + org.hibernate.type.descriptor.sql: trace +custom: + site: + name: MUTBooks + baseUrl: "http://localhost:8010" + jwt: + secretKey: secretKeysecretKeysecretKeysecretKeysecretKeysecretKeysecretKeysecretKeysecretKeysecretKey \ No newline at end of file diff --git a/mutbooks/src/main/resources/static/resource/common/common.css b/mutbooks/src/main/resources/static/resource/common/common.css new file mode 100644 index 0000000..5458cf3 --- /dev/null +++ b/mutbooks/src/main/resources/static/resource/common/common.css @@ -0,0 +1,55 @@ +/* 지마켓 산스 불러오기 */ +@font-face { + font-family: 'GmarketSansMedium'; + src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_2001@1.1/GmarketSansMedium.woff') format('woff'); + font-weight: normal; + font-style: normal; +} + +html > body { + font-family: "GmarketSansMedium"; + text-underline-position: under; + color: #444; +} + + +/* 지마켓 산스 불러오기 */ +@font-face { + font-family: "GmarketSansMedium"; + src: url("https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_2001@1.1/GmarketSansMedium.woff") + format("woff"); + font-weight: normal; + font-style: normal; +} + +/* 토스트 UI 에디터 관련 스타일 시작 */ +html > body, +html > body .ProseMirror, +html > body .toastui-editor-contents, +html > body code[class*="language-"], +html > body pre[class*="language-"], +html > body code[class*="lang-"], +html > body pre[class*="lang-"] { + font-family: "GmarketSansMedium"; + text-underline-position: under; + letter-spacing: 0; +} + +html > body code[class*="language-"], +html > body pre[class*="language-"], +html > body code[class*="lang-"], +html > body pre[class*="lang-"] { + color: white; + background-color: #444; +} + +html > body .ProseMirror, +html > body .toastui-editor-contents { + font-size: 1.1rem; +} + +.toastui-editor-dark { + background-color: #333; +} +/* 토스트 UI 에디터 관련 스타일 끝 */ + diff --git a/mutbooks/src/main/resources/static/resource/common/common.js b/mutbooks/src/main/resources/static/resource/common/common.js new file mode 100644 index 0000000..433bb25 --- /dev/null +++ b/mutbooks/src/main/resources/static/resource/common/common.js @@ -0,0 +1,368 @@ +toastr.options = { + closeButton: false, + debug: false, + newestOnTop: false, + progressBar: false, + positionClass: "toast-top-right", + preventDuplicates: false, + onclick: null, + showDuration: "300", + hideDuration: "1000", + timeOut: "5000", + extendedTimeOut: "1000", + showEasing: "swing", + hideEasing: "linear", + showMethod: "fadeIn", + hideMethod: "fadeOut" +}; + +function successModal(msg) { + toastr["success"](msg); +} + +function errorModal(msg) { + toastr["error"](msg); +} + +function warningModal(msg) { + toastr["warning"](msg); +} + + +console.clear(); + +// 토스트 에디터 시작 + +// 토스트 에디터 - 라이브러리 - 시작 +function ToastEditor__getUriParams(uri) { + uri = uri.trim(); + uri = uri.replaceAll("&", "&"); + if (uri.indexOf("#") !== -1) { + let pos = uri.indexOf("#"); + uri = uri.substr(0, pos); + } + + let params = {}; + + uri.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (str, key, value) { + params[key] = value; + }); + return params; +} + +function ToastEditor__escape(origin) { + return origin + .replaceAll("' + ); + } + // 유튜브 플러그인 끝 + + return { toHTMLRenderers }; +} + +// katex 플러그인 +function ToastEditor__PluginKatex() { + const toHTMLRenderers = { + katex(node) { + let html = katex.renderToString(node.literal, { + throwOnError: false + }); + + return [ + { type: "openTag", tagName: "div", outerNewLine: true }, + { type: "html", content: html }, + { type: "closeTag", tagName: "div", outerNewLine: true } + ]; + } + }; + + return { toHTMLRenderers }; +} + +function ToastEditor__PluginCodepen() { + const toHTMLRenderers = { + codepen(node) { + const html = renderCodepen(node.literal); + + return [ + { type: "openTag", tagName: "div", outerNewLine: true }, + { type: "html", content: html }, + { type: "closeTag", tagName: "div", outerNewLine: true } + ]; + } + }; + + function renderCodepen(uri) { + let uriParams = ToastEditor__getUriParams(uri); + + let height = 400; + + let preview = ""; + + if (uriParams.height) { + height = uriParams.height; + } + + let width = "100%"; + + if (uriParams.width) { + width = uriParams.width; + } + + if (!isNaN(width)) { + width += "px"; + } + + let iframeUri = uri; + + if (iframeUri.indexOf("#") !== -1) { + let pos = iframeUri.indexOf("#"); + iframeUri = iframeUri.substr(0, pos); + } + + return ( + '' + ); + } + + return { toHTMLRenderers }; +} +// 유튜브 플러그인 끝 + +// repl 플러그인 시작 +function ToastEditor__PluginRepl() { + const toHTMLRenderers = { + repl(node) { + const html = renderRepl(node.literal); + + return [ + { type: "openTag", tagName: "div", outerNewLine: true }, + { type: "html", content: html }, + { type: "closeTag", tagName: "div", outerNewLine: true } + ]; + } + }; + + function renderRepl(uri) { + var uriParams = ToastEditor__getUriParams(uri); + + let uriBits = uri.split("#"); + const hash = uriBits.length == 2 ? uriBits[1] : ""; + uriBits = uriBits[0].split("?"); + + const newUrl = uriBits[0] + "?embed=true#" + hash; + + var height = 400; + + if (uriParams.height) { + height = uriParams.height; + } + + return ( + '' + ); + } + + return { toHTMLRenderers }; +} +// 토스트 에디터 - 플러그인 - 끝 + +// 토스트 에디터 - 에디터 초기화 - 시작 +function ToastEditor__init() { + $(".toast-ui-editor, .toast-ui-viewer").each(function (index, node) { + const $node = $(node); + const isViewer = $node.hasClass("toast-ui-viewer"); + const $initialValueEl = $node.find(" > script"); + const initialValue = + $initialValueEl.length == 0 + ? "" + : ToastEditor__escape($initialValueEl.html().trim()); + + const placeholder = ToastEditor__getAttrValue( + $node, + "toast-ui-editor--placeholder", + "" + ); + const previewStyle = ToastEditor__getAttrValue( + $node, + "toast-ui-editor--previewStyle", + "vertical" + ); + const height = ToastEditor__getAttrValue( + $node, + "toast-ui-editor--height", + "600px" + ); + const theme = ToastEditor__getAttrValue( + $node, + "toast-ui-editor--theme", + "light" + ); + + const editorConfig = { + el: node, + viewer: isViewer, + previewStyle: previewStyle, + initialValue: initialValue, + placeholder: placeholder, + height: height, + theme: theme, + plugins: [ + [toastui.Editor.plugin.chart, ToastEditor__chartOptions], + [toastui.Editor.plugin.codeSyntaxHighlight, { highlighter: Prism }], + toastui.Editor.plugin.tableMergedCell, + toastui.Editor.plugin.colorSyntax, + [ + toastui.Editor.plugin.uml, + { rendererURL: "http://www.plantuml.com/plantuml/svg/" } + ], + ToastEditor__PluginKatex, + ToastEditor__PluginYoutube, + ToastEditor__PluginCodepen, + ToastEditor__PluginRepl + ], + customHTMLSanitizer: (html) => { + return ( + DOMPurify.sanitize(html, { + ADD_TAGS: ["iframe"], + ADD_ATTR: [ + "width", + "height", + "allow", + "allowfullscreen", + "frameborder", + "scrolling", + "style", + "title", + "loading", + "allowtransparency" + ] + }) || "" + ); + } + }; + + const editor = isViewer + ? new toastui.Editor.factory(editorConfig) + : new toastui.Editor(editorConfig); + + $node.data("data-toast-editor", editor); + }); +} +// 토스트 에디터 - 에디터 초기화 - 끝 + +// 토스트 에디터 실행 +ToastEditor__init(); + +// 토스트 에디터 끝 \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/adm/home/main.html b/mutbooks/src/main/resources/templates/adm/home/main.html new file mode 100644 index 0000000..1b2b0fd --- /dev/null +++ b/mutbooks/src/main/resources/templates/adm/home/main.html @@ -0,0 +1,14 @@ + + + + + 관리자 메인 + + +
+
+

관리자 메인페이지

+
+
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/adm/layout/layout.html b/mutbooks/src/main/resources/templates/adm/layout/layout.html new file mode 100644 index 0000000..2ce6898 --- /dev/null +++ b/mutbooks/src/main/resources/templates/adm/layout/layout.html @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+ + + + + + + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/adm/rebate/makeData.html b/mutbooks/src/main/resources/templates/adm/rebate/makeData.html new file mode 100644 index 0000000..e95d90d --- /dev/null +++ b/mutbooks/src/main/resources/templates/adm/rebate/makeData.html @@ -0,0 +1,91 @@ + + + + + 정산데이터 + + + +
+
+
+

정산데이터

+ + + + 생성 + + + 조회 + + + 전체 조회 +
+
+ + + +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/adm/rebate/rebateOrderItemList.html b/mutbooks/src/main/resources/templates/adm/rebate/rebateOrderItemList.html new file mode 100644 index 0000000..7498dbd --- /dev/null +++ b/mutbooks/src/main/resources/templates/adm/rebate/rebateOrderItemList.html @@ -0,0 +1,115 @@ + + + + + 정산데이터 목록 + + +
+
+
+

정산데이터 목록

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + 정산번호주문품목번호상품명결제일시결제금액PG 수수료도매가환불일시환불금액판매자예상정산금액정산내역번호비고
+ + + 건별정산 + +
정산완료
+
환불완료
+
+ + 선택정산 + + + +
+
+
+
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/adm/withdraw/apply_list.html b/mutbooks/src/main/resources/templates/adm/withdraw/apply_list.html new file mode 100644 index 0000000..1eb20b8 --- /dev/null +++ b/mutbooks/src/main/resources/templates/adm/withdraw/apply_list.html @@ -0,0 +1,70 @@ + + + + + 출금신청 내역 + + + +
+
+
+

출금신청 내역

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
번호은행명계좌번호금액신청일시출금일시취소일시처리 상태비고
+
-
+
+
+
-
+
+
신청완료출금완료취소완료 + 출금 처리 + + 취소 + +
+
+
+
+
+ + + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/cart/list.html b/mutbooks/src/main/resources/templates/cart/list.html new file mode 100644 index 0000000..21ea437 --- /dev/null +++ b/mutbooks/src/main/resources/templates/cart/list.html @@ -0,0 +1,149 @@ + + + + + 장바구니 + + + +
+
+ +
+

eBook

+ +
+ + 전체 선택 +
+ +
+
+
장바구니에 담긴 상품이 없습니다.
+
+
+ +
    +
  • +
    +
    +
    +
    + + + +
    +
    +
    + +

    +
    + +
    +
    +
    |
    +
    + +
    + +
    +
    무배송. 결제 후 즉시 다운로드
    +
    + 수량 : 1 +
    +
    + + +
    +
    +
    +
  • +
+ + 선택삭제 + + +
+ 주문하기 + +
+ + + +
+
+ +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/home/main.html b/mutbooks/src/main/resources/templates/home/main.html new file mode 100644 index 0000000..1700c29 --- /dev/null +++ b/mutbooks/src/main/resources/templates/home/main.html @@ -0,0 +1,14 @@ + + + + + 메인 + + +
+
+

메인페이지(최신글 100개)

+
+
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/layout/layout.html b/mutbooks/src/main/resources/templates/layout/layout.html new file mode 100644 index 0000000..50d4e8c --- /dev/null +++ b/mutbooks/src/main/resources/templates/layout/layout.html @@ -0,0 +1,212 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/member/confirm_password.html b/mutbooks/src/main/resources/templates/member/confirm_password.html new file mode 100644 index 0000000..9f41100 --- /dev/null +++ b/mutbooks/src/main/resources/templates/member/confirm_password.html @@ -0,0 +1,43 @@ + + + + + 임시 비밀번호 발급 + + + +
+
+ +
+

임시 비밀번호 발급

+ +
+
+ + +
+
+ +
+ 로그인 +
+ + +
+ + +
+ +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/member/confirm_username.html b/mutbooks/src/main/resources/templates/member/confirm_username.html new file mode 100644 index 0000000..72e4eaa --- /dev/null +++ b/mutbooks/src/main/resources/templates/member/confirm_username.html @@ -0,0 +1,43 @@ + + + + + 아이디 확인 + + + +
+
+ +
+

아이디 확인

+ +
+
+ + +
+
+ +
+ 로그인 +
+ + +
+ + +
+ +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/member/find_password.html b/mutbooks/src/main/resources/templates/member/find_password.html new file mode 100644 index 0000000..3dbfa4f --- /dev/null +++ b/mutbooks/src/main/resources/templates/member/find_password.html @@ -0,0 +1,73 @@ + + + + + 비밀번호 찾기 + + + +
+ + +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/member/find_username.html b/mutbooks/src/main/resources/templates/member/find_username.html new file mode 100644 index 0000000..aa11318 --- /dev/null +++ b/mutbooks/src/main/resources/templates/member/find_username.html @@ -0,0 +1,57 @@ + + + + + 아이디 찾기 + + + +
+ + +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/member/join.html b/mutbooks/src/main/resources/templates/member/join.html new file mode 100644 index 0000000..6d15b8d --- /dev/null +++ b/mutbooks/src/main/resources/templates/member/join.html @@ -0,0 +1,114 @@ + + + + + 회원가입 + + + +
+
+ +
+

회원가입

+ + + +
+
+ + +
+
+ * + +
+ +
+ + +
+ +
+ + +
+
+ * + +
+ + +
+ + + *작가 회원으로 가입을 원하는 경우, 작가명을 입력해주세요. +
+
+ * + +
+ +
+ +
+
+
+ + +
+ +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/member/login.html b/mutbooks/src/main/resources/templates/member/login.html new file mode 100644 index 0000000..b085f8d --- /dev/null +++ b/mutbooks/src/main/resources/templates/member/login.html @@ -0,0 +1,86 @@ + + + + + 로그인 + + + +
+ + +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/member/manage_withdraw_account.html b/mutbooks/src/main/resources/templates/member/manage_withdraw_account.html new file mode 100644 index 0000000..4f9a316 --- /dev/null +++ b/mutbooks/src/main/resources/templates/member/manage_withdraw_account.html @@ -0,0 +1,49 @@ + + + + + 출금계좌 관리 + + + +
+
+ +
+

출금계좌 관리

+ +
+ +
+ + +
+ +
+ + +
+ +
+ +
출금 계좌 정보가 존재하지 않습니다.
아래 버튼을 클릭해 출금 계좌 정보를 등록해주세요.
+ +
+
+
+ + +
+ +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/member/modify.html b/mutbooks/src/main/resources/templates/member/modify.html new file mode 100644 index 0000000..5942138 --- /dev/null +++ b/mutbooks/src/main/resources/templates/member/modify.html @@ -0,0 +1,70 @@ + + + + + 회원정보 수정 + + + +
+
+ +
+

회원정보 수정

+ + + + +
+ +
+ + +
+ + +
+ + + *작가명을 입력하지 않으면 일반 회원으로 전환됩니다. +
+ +
+ +
+
+
+ + +
+ +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/member/modify_password.html b/mutbooks/src/main/resources/templates/member/modify_password.html new file mode 100644 index 0000000..76f14a9 --- /dev/null +++ b/mutbooks/src/main/resources/templates/member/modify_password.html @@ -0,0 +1,93 @@ + + + + + 비밀번호 수정 + + + +
+
+ +
+

비밀번호 변경

+
•이전에 사용한적 없는 비밀번호를 입력해주세요.
+ + + + +
+ +
+ +
+ +
+ +
+ +
+ * + +
+ +
+ +
+ +
+ * + +
+ +
+ +
+
+
+ + +
+ +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/member/profile.html b/mutbooks/src/main/resources/templates/member/profile.html new file mode 100644 index 0000000..5fa0203 --- /dev/null +++ b/mutbooks/src/main/resources/templates/member/profile.html @@ -0,0 +1,65 @@ + + + + + 내 프로필 + + + +
+
+ +
+

내 프로필

+
작가 회원
+
관리자 회원
+ +
+
+ + +
+ +
+ + +
+ + +
+ + +
+ +
+ + +
+ + + + +
+
+ + +
+ +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/member/register_withdraw_account.html b/mutbooks/src/main/resources/templates/member/register_withdraw_account.html new file mode 100644 index 0000000..60a2d73 --- /dev/null +++ b/mutbooks/src/main/resources/templates/member/register_withdraw_account.html @@ -0,0 +1,87 @@ + + + + + 출금계좌 등록 + + + +
+
+ +
+

출금계좌 등록

+ + + +
+
+ + +
+
+ * + +
+ +
+ + +
+
+ * + +
+ +
+ +
+
+
+ + +
+ +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/order/detail.html b/mutbooks/src/main/resources/templates/order/detail.html new file mode 100644 index 0000000..897756f --- /dev/null +++ b/mutbooks/src/main/resources/templates/order/detail.html @@ -0,0 +1,265 @@ + + + + + 주문 상세 + + + +
+ + + + + + + +
+ +
+

주문 상세

+
+
주문 상품 :
+
총 
+
+
 개
+
+
주문 완료
+
결제 완료
+
취소 완료
+
환불 완료
+
+
+ +
+
+
+
+
+ + + +
+
+
+

+
+ +
+
+ 수량 : 1 +
+
무배송. 결제 후 즉시 다운로드
+
+
+
+
+
+ +
+
주문 정보 +
+
+
+ 주문고객 [[${order.buyer.username}]] 님 +
+
+ 총 상품수 [[${order.orderItems.size()}]] 개 +
+
+ 총 상품금액 [[${order.calcPayPrice}]] 원 +
+
+
+ + +
+
결제 정보 +
+
+
+ 총 상품금액 [[${order.calcPayPrice}]] 원 +
+
+ 캐시 사용금액 [[${order.cashPayPrice}]] 원 +
+
+ 최종 결제금액 [[${order.pgPayPrice}]] 원 +
+
+
+ + +
+
캐시
+
+ MUT 캐시 + [[${restCash}]] 원 +
+ + + +
+ + +
+
+
결제정보
+
+ 최종 결제금액 + + +
+
+
+ + + + + + + + + + +
+
+ + + + + + +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/order/fail.html b/mutbooks/src/main/resources/templates/order/fail.html new file mode 100644 index 0000000..246c5d3 --- /dev/null +++ b/mutbooks/src/main/resources/templates/order/fail.html @@ -0,0 +1,24 @@ + + + + + 주문 결제실패 + + + +
+
+
+ 주문 결제실패 +
+ +
+ 주문번호 : [[${orderId}]] +
+ +
[[${message}]]
+
[[${code}]]
+
+
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/order/list.html b/mutbooks/src/main/resources/templates/order/list.html new file mode 100644 index 0000000..bbe9128 --- /dev/null +++ b/mutbooks/src/main/resources/templates/order/list.html @@ -0,0 +1,53 @@ + + + + + 주문 내역 + + + +
+
+
+

주문 내역

+
+
+
+
+
주문 완료
+
결제 완료
+
취소 완료
+
환불 완료
+
+
+ + 상세보기 + + +
+ +
+
+
+
+
+
+ +
+
+

+
수량 : 1
+
+
+
+
+
+
+
+
+
+
+
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/order/success.html b/mutbooks/src/main/resources/templates/order/success.html new file mode 100644 index 0000000..0e32ec9 --- /dev/null +++ b/mutbooks/src/main/resources/templates/order/success.html @@ -0,0 +1,21 @@ + + + + + 주문 결제성공 + + + +
+
+
+ 주문 결제성공 +
+ +
+ 주문번호 : [[${orderId}]] +
+
+
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/post/detail.html b/mutbooks/src/main/resources/templates/post/detail.html new file mode 100644 index 0000000..fd55c17 --- /dev/null +++ b/mutbooks/src/main/resources/templates/post/detail.html @@ -0,0 +1,65 @@ + + + + + 글 상세(임시) + + + +
+
+ +
+
+
+

+
+ +
+
+
+ +
+
+ # + +
+ +
+ + +
+
+ + + +
+
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/post/list.html b/mutbooks/src/main/resources/templates/post/list.html new file mode 100644 index 0000000..c3705b8 --- /dev/null +++ b/mutbooks/src/main/resources/templates/post/list.html @@ -0,0 +1,56 @@ + + + + + 글 리스트 + + + +
+
+ +
+

글 리스트

+ +
+ + + + + + + + + + + + + + + + + + + + + + +
번호제목작성자작성날짜수정날짜
+ +
+ +
+
+
+ +
+
+ +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/post/modify.html b/mutbooks/src/main/resources/templates/post/modify.html new file mode 100644 index 0000000..eea95ac --- /dev/null +++ b/mutbooks/src/main/resources/templates/post/modify.html @@ -0,0 +1,92 @@ + + + + + 글 수정 + + + +
+
+ +
+

글 수정

+ + + + +
+ + +
+ + +
+ +
+ +
+
+ +
+ + +
+ +
+ + +
+
+
+ + +
+ +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/post/write.html b/mutbooks/src/main/resources/templates/post/write.html new file mode 100644 index 0000000..5663d04 --- /dev/null +++ b/mutbooks/src/main/resources/templates/post/write.html @@ -0,0 +1,92 @@ + + + + + 글 작성 + + + +
+
+ +
+

글 작성

+ + + + +
+ + +
+ + +
+ +
+ +
+
+ +
+ + +
+ +
+ + +
+
+
+ + +
+ +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/product/create.html b/mutbooks/src/main/resources/templates/product/create.html new file mode 100644 index 0000000..30c59cd --- /dev/null +++ b/mutbooks/src/main/resources/templates/product/create.html @@ -0,0 +1,122 @@ + + + + + 도서 등록 + + + +
+
+ +
+

+ + 도서 정보 수정 +

+ + + + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ +
+ +
+ + +
+
+
+ +
+ +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/product/detail.html b/mutbooks/src/main/resources/templates/product/detail.html new file mode 100644 index 0000000..029a621 --- /dev/null +++ b/mutbooks/src/main/resources/templates/product/detail.html @@ -0,0 +1,83 @@ + + + + + 도서 정보 + + + +
+
+ +
+
+
+ +
+ +
+

+
+ +
+
+
|
+
+ +
+ +
+
+
+ +
+

소개

+
+
+ + + + + + + + + + + + + + + + + + + + + +
+
+ # + +
+
+ + +
+
+
+
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/product/list.html b/mutbooks/src/main/resources/templates/product/list.html new file mode 100644 index 0000000..ddf0b9a --- /dev/null +++ b/mutbooks/src/main/resources/templates/product/list.html @@ -0,0 +1,60 @@ + + + + + 도서 목록 + + + +
+
+ +
+ + +
+
+
+
+ +
+
+ +

+
+ +
+
+
|
+
+ +
+ +
+ +
+
+ # + +
+
+
+ + +
+
+
+
+ +
+
+ +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/product/modify.html b/mutbooks/src/main/resources/templates/product/modify.html new file mode 100644 index 0000000..fe487c3 --- /dev/null +++ b/mutbooks/src/main/resources/templates/product/modify.html @@ -0,0 +1,117 @@ + + + + + 도서 정보 수정 + + + +
+
+ +
+

+ + 도서 등록 +

+ + + + +
+ +
+ +
+
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ +
+ +
+ + +
+
+
+ +
+ +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/withdraw/apply.html b/mutbooks/src/main/resources/templates/withdraw/apply.html new file mode 100644 index 0000000..920335b --- /dev/null +++ b/mutbooks/src/main/resources/templates/withdraw/apply.html @@ -0,0 +1,157 @@ + + + + + 출금신청 + + + +
+
+ +
+

출금신청

+ + + +
+
출금 계좌 정보
+
+ + 은행 : + +
+ +
+ 계좌번호 : + +
+
+ +
+ + + + + + + + + + + + + +
+
+
+ MUT 캐시 잔액 + [[${member.restCash}]] 원 +
+ +
+ 출금 금액 +
+ + +
+ +
+ +
+
+
+ + +
+ + + + +
+ + \ No newline at end of file diff --git a/mutbooks/src/main/resources/templates/withdraw/apply_list.html b/mutbooks/src/main/resources/templates/withdraw/apply_list.html new file mode 100644 index 0000000..17e158d --- /dev/null +++ b/mutbooks/src/main/resources/templates/withdraw/apply_list.html @@ -0,0 +1,67 @@ + + + + + 출금신청 내역 + + + +
+
+
+

출금신청 내역

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
번호은행명계좌번호금액신청일시출금일시취소일시처리 상태비고
+
-
+
+
+
-
+
+
신청완료출금완료취소완료 + 취소 + +
+
+
+
+
+ + + \ No newline at end of file diff --git a/mutbooks/src/test/java/com/example/mutbooks/MutbooksApplicationTests.java b/mutbooks/src/test/java/com/example/mutbooks/MutbooksApplicationTests.java new file mode 100644 index 0000000..d30a182 --- /dev/null +++ b/mutbooks/src/test/java/com/example/mutbooks/MutbooksApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.mutbooks; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class MutbooksApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java b/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java new file mode 100644 index 0000000..a22ee8d --- /dev/null +++ b/mutbooks/src/test/java/com/example/mutbooks/app/api/controller/MemberApiControllerTest.java @@ -0,0 +1,163 @@ +package com.example.mutbooks.app.api.controller; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.transaction.annotation.Transactional; + +import java.nio.charset.StandardCharsets; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +@Transactional +@ActiveProfiles("test") +class MemberApiControllerTest { + + @Autowired + private MockMvc mvc; + + @Test + @DisplayName("POST /api/v1/member/login 은 로그인 처리 URL 이다.") + void t1() throws Exception { + // When + ResultActions resultActions = mvc + .perform( + post("/api/v1/member/login") + .content(""" + { + "username": "user1", + "password": "1234" + } + """.stripIndent()) + .contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8)) + ) + .andDo(print()); + + // Then + resultActions + .andExpect(status().is2xxSuccessful()); + } + + @Test + @DisplayName("POST /api/v1/member/login 으로 올바른 username과 password 데이터를 넘기면 JWT키를 발급해 응답 헤더에 담아준다.") + void t2() throws Exception { + // When + ResultActions resultActions = mvc + .perform( + post("/api/v1/member/login") + .content(""" + { + "username": "user1", + "password": "1234" + } + """.stripIndent()) + .contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8)) + ) + .andDo(print()); + + // Then + resultActions + .andExpect(status().is2xxSuccessful()); + + // 응답 결과 + MvcResult mvcResult = resultActions.andReturn(); + + MockHttpServletResponse response = mvcResult.getResponse(); + // 응답 헤더 Authentication(key) : JWT 키(value) + String authentication = response.getHeader("Authentication"); + + assertThat(authentication).isNotEmpty(); + } + + @Test + @DisplayName("POST /api/v1/member/login 호출할 때 username 이나 password 를 누락하면 400") + void t3() throws Exception { + // When + ResultActions resultActions = mvc + .perform( + post("/api/v1/member/login") + .content(""" + { + "username": "", + "password": "1234" + } + """.stripIndent()) + .contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8)) + ) + .andDo(print()); + + // Then + resultActions + .andExpect(status().is4xxClientError()); + + resultActions = mvc + .perform( + post("/api/v1/member/login") + .content(""" + { + "username": "user1", + "password": " " + } + """.stripIndent()) + .contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8)) + ) + .andDo(print()); + + // Then + resultActions + .andExpect(status().is4xxClientError()); + } + + @Test + @DisplayName("POST /api/v1/member/login 호출할 때 올바르지 않는 username 이나 password 를 입력하면 400") + void t4() throws Exception { + // When(존재하지 않는 아이디) + ResultActions resultActions = mvc + .perform( + post("/api/v1/member/login") + .content(""" + { + "username": "user4", + "password": "1234" + } + """.stripIndent()) + .contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8)) + ) + .andDo(print()); + + // Then + resultActions + .andExpect(status().is4xxClientError()); + + // when(비밀번호 틀림) + resultActions = mvc + .perform( + post("/api/v1/member/login") + .content(""" + { + "username": "user1", + "password": "12345" + } + """.stripIndent()) + .contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8)) + ) + .andDo(print()); + + // Then + resultActions + .andExpect(status().is4xxClientError()); + } +} \ No newline at end of file diff --git a/mutbooks/src/test/java/com/example/mutbooks/app/post/service/PostServiceTest.java b/mutbooks/src/test/java/com/example/mutbooks/app/post/service/PostServiceTest.java new file mode 100644 index 0000000..29868bb --- /dev/null +++ b/mutbooks/src/test/java/com/example/mutbooks/app/post/service/PostServiceTest.java @@ -0,0 +1,88 @@ +package com.example.mutbooks.app.post.service; + +import com.example.mutbooks.app.postHashTag.entity.PostHashTag; +import com.example.mutbooks.app.postHashTag.service.PostHashTagService; +import com.example.mutbooks.app.member.entity.Member; +import com.example.mutbooks.app.member.repository.MemberRepository; +import com.example.mutbooks.app.post.entity.Post; +import com.example.mutbooks.app.post.form.WriteForm; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@Transactional +@ActiveProfiles("test") +class PostServiceTest { + @Autowired + private PostService postService; + + @Autowired + private MemberRepository memberRepository; + + @Autowired + private PostHashTagService postHashTagService; + + @Test + @DisplayName("글 작성") + void t1() { + // given + Member author = memberRepository.findByUsername("user2").orElse(null); + String keywords = "#로맨스 #판타지 #판타지"; + // when + Post post = postService.write(author, new WriteForm("제목", "안녕하세요1", "
  • 안녕하세요1

", keywords)); + // then + assertThat(post).isNotNull(); + assertThat(post.getAuthor().getUsername()).isEqualTo("user2"); + assertThat(post.getSubject()).isEqualTo("제목"); + assertThat(post.getContent()).isEqualTo("안녕하세요1"); + assertThat(post.getContentHtml()).isEqualTo("
  • 안녕하세요1

"); + // 해시태그 + List hashTags = postHashTagService.findByPostId(3); + assertThat(hashTags.size()).isEqualTo(2); + assertThat(hashTags.get(0).getPostKeyword().getContent()).isEqualTo("로맨스"); + assertThat(hashTags.get(1).getPostKeyword().getContent()).isEqualTo("판타지"); + } + + @Test + @DisplayName("글 수정") + void t2() { + // given + Post post = postService.findById(1); + String keywords = "#로맨스 #판타지 #소설"; + // when + postService.modify(post, new WriteForm("new 제목", "new 안녕하세요", "
  • new 안녕하세요

", keywords)); + // then + assertThat(post).isNotNull(); + assertThat(post.getSubject()).isEqualTo("new 제목"); + assertThat(post.getContent()).isEqualTo("new 안녕하세요"); + assertThat(post.getContentHtml()).isEqualTo("
  • new 안녕하세요

"); + // 해시태그 + List hashTags = postHashTagService.findByPostId(1); + assertThat(hashTags.size()).isEqualTo(3); + assertThat(hashTags.get(0).getPostKeyword().getContent()).isEqualTo("판타지"); + assertThat(hashTags.get(1).getPostKeyword().getContent()).isEqualTo("소설"); + assertThat(hashTags.get(2).getPostKeyword().getContent()).isEqualTo("로맨스"); + } + + @Test + @DisplayName("글 삭제") + void t3() { + // given + Post post = postService.findById(1); + // when + postService.delete(post); + // then + Assertions.assertThrows(RuntimeException.class, () -> { + postService.findById(1); + }); + } +} \ No newline at end of file diff --git a/mutbooks/src/test/java/com/example/mutbooks/app/postHashTag/service/PostHashTagServiceTest.java b/mutbooks/src/test/java/com/example/mutbooks/app/postHashTag/service/PostHashTagServiceTest.java new file mode 100644 index 0000000..d09cfc1 --- /dev/null +++ b/mutbooks/src/test/java/com/example/mutbooks/app/postHashTag/service/PostHashTagServiceTest.java @@ -0,0 +1,65 @@ +package com.example.mutbooks.app.postHashTag.service; + +import com.example.mutbooks.app.postHashTag.entity.PostHashTag; +import com.example.mutbooks.app.postKeyword.service.PostKeywordService; +import com.example.mutbooks.app.post.entity.Post; +import com.example.mutbooks.app.post.service.PostService; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@Transactional +@ActiveProfiles("test") +class PostHashTagServiceTest { + @Autowired + private PostService postService; + @Autowired + private PostHashTagService postHashTagService; + @Autowired + private PostKeywordService postKeywordService; + + @Test + @DisplayName("2번 게시글에 해시태그 키워드 2개 등록하기") + void t1() { + // given + Post post = postService.findById(2); + String keywordContent1 = "판타지"; + String keywordContent2 = "판타지"; + String keywordContent3 = "소설"; + // when + postHashTagService.save(post, keywordContent1); + postHashTagService.save(post, keywordContent2); + postHashTagService.save(post, keywordContent3); + // then + List hashTags = postHashTagService.findByPostId(2); + + assertThat(hashTags.size()).isEqualTo(2); + assertThat(hashTags.get(0).getPostKeyword().getContent()).isEqualTo("판타지"); + assertThat(hashTags.get(1).getPostKeyword().getContent()).isEqualTo("소설"); + } + + @Test + @DisplayName("입력된 문자열에서 해시태그 추출해서 1번 게시글에 등록하기") + void t2() { + // given + Post post = postService.findById(1); + String keywords = "#판타지 #소설 # SF # 소설"; + // when + postHashTagService.apply(post, keywords); + // then + List hashTags = postHashTagService.findByPostId(1); + + assertThat(hashTags.size()).isEqualTo(3); + assertThat(hashTags.get(0).getPostKeyword().getContent()).isEqualTo("판타지"); + assertThat(hashTags.get(1).getPostKeyword().getContent()).isEqualTo("소설"); + assertThat(hashTags.get(2).getPostKeyword().getContent()).isEqualTo("SF"); + } +} \ No newline at end of file diff --git a/mutbooks/src/test/java/com/example/mutbooks/util/UtTest.java b/mutbooks/src/test/java/com/example/mutbooks/util/UtTest.java new file mode 100644 index 0000000..f35223f --- /dev/null +++ b/mutbooks/src/test/java/com/example/mutbooks/util/UtTest.java @@ -0,0 +1,21 @@ +package com.example.mutbooks.util; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +class UtTest { + @Test + @DisplayName("Ut.mapOf() 인자값을 map 으로 변환") + void t1() { + Map ages = Ut.mapOf("영수", 22, "철수", 33, "영희", 44, "민수", 55); + + assertThat(ages.get("영수")).isEqualTo(22); + assertThat(ages.get("철수")).isEqualTo(33); + assertThat(ages.get("영희")).isEqualTo(44); + assertThat(ages.get("민수")).isEqualTo(55); + } +} \ No newline at end of file