Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

전남대 BE_안재영 5주차 과제 (3단계) #432

Open
wants to merge 38 commits into
base: ajy9851
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
b50f9c2
0단계 코드 준비
ajy9851 Jul 22, 2024
ac300a3
설정 파일 ignore추가
ajy9851 Jul 24, 2024
b38fe3d
feat(KakaoAuthController): 카카오 인증 컨트롤러 추가
ajy9851 Jul 24, 2024
8efdb3a
feat(KakaoTokenResponseDTO): 응답 dto 추가
ajy9851 Jul 24, 2024
6546960
gitignore 다시 적용
ajy9851 Jul 24, 2024
7af895c
gitignore 다시 적용
ajy9851 Jul 24, 2024
79691d4
feat(RestTemplateConfig): 1단계 피드백 반영(Bean으로 만들고 타임아웃 설정)
ajy9851 Jul 25, 2024
783c6d6
feat(KakaoAuthService): 1단계 피드백 반영(컨트롤러의 로직을 서비스에 할당)
ajy9851 Jul 25, 2024
14f3d0a
feat(KakaoAuthController): 1단계 피드백 반영(컨트롤러의 로직을 서비스에 할당하고 컨트롤러에 해당 로직…
ajy9851 Jul 25, 2024
59cd0f7
feat
ajy9851 Jul 25, 2024
6b83dbd
fix(Kakao): 로그인 후 바로 토큰을 받아올 수 있도록 변경
ajy9851 Jul 25, 2024
606423e
feat(KakaoUserDTO): 카카오 유저 정보 DTO 추가
ajy9851 Jul 26, 2024
c576234
feat(KakaoAuthService): 카카오 사용자 정보 조회 및 사용자 등록 로직 추가
ajy9851 Jul 26, 2024
5f5dcb3
fix(KakaoAuthController): 토큰 발급 후 카카오 사용자 조회하여 새로운 사용자 등록하거나 기존 사용자를 …
ajy9851 Jul 26, 2024
c1403b1
fix(KakaoAuthController): 코드 오류 수정
ajy9851 Jul 26, 2024
2753ce7
feat(Order): 주문 엔티티 추가
ajy9851 Jul 26, 2024
df691ca
feat(OrderRepository): 주문 레포지토리 추가
ajy9851 Jul 26, 2024
74ca3cf
feat(OptionService): OrderService에서 사용할 findOptionById 추가
ajy9851 Jul 26, 2024
cc4d7f6
feat(OrderRequestDTO): 주문 요청 DTO 추가
ajy9851 Jul 26, 2024
72e004f
feat(OrderService): 주문 서비스 추가
ajy9851 Jul 26, 2024
c48ab7a
fix(KakaoAuthService): 카카오 로그인 시 임의로 비밀번호 등록하도록 수정
ajy9851 Jul 26, 2024
d8ce11f
feat(OrderController): 주문 컨트롤러 추가
ajy9851 Jul 26, 2024
d51f4b8
feat(KakaoMessageService): 카카오 메세지 전송을 위한 서비스 추가
ajy9851 Jul 28, 2024
e9dc20b
feat(Member): 멤버에 토큰 필드 추가
ajy9851 Jul 28, 2024
f9d8e4f
feat(Member): 멤버에 setToken추가
ajy9851 Jul 28, 2024
ff5008f
feat(KakaoAuthService): 사용자 등록시 토큰 추가
ajy9851 Jul 28, 2024
d6c4894
feat(KakaoAuthController): registerOrGetMember메서드 파라미터에 토큰 추가
ajy9851 Jul 28, 2024
7301a78
feat(Order): getter 생성
ajy9851 Jul 28, 2024
69a66d6
feat(OrderService): 카카오 메세지 전송 메서드 사용
ajy9851 Jul 28, 2024
8b200f1
feat(OrderResponseDTO): 주문 응답 dto 추가
ajy9851 Jul 28, 2024
c4db444
feat(DatabaseInitializer): 어플리케이션 실행 시 데이터베이스 초기화 및 더미 데이터 삽입
ajy9851 Jul 28, 2024
6a6fe19
feat(OrderRequestDTO): 기본 생성자 추가
ajy9851 Jul 28, 2024
b1e97e2
fix(Order): @Table 어노테이션으로 테이블 이름 수정
ajy9851 Jul 28, 2024
e405100
fix(KakaoMessageService): template_object 파라미터 오류로 인한 수정
ajy9851 Jul 28, 2024
faac9b6
feat(KakaoAuthService): getEmailFromAccessToken 메서드 추가
ajy9851 Jul 28, 2024
f0673e4
fix(Order): OrderResponseDTO 사용
ajy9851 Jul 28, 2024
c7d85d5
chore(build.gradle): swagger 의존성 추가하여 api 문서 자동으로 확인 가능하도록 수정
ajy9851 Jul 30, 2024
dd8b1c7
Merge branch 'ajy9851' into ajy9851-step3
ajy9851 Jul 30, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ dependencies {
implementation 'io.jsonwebtoken:jjwt-api:0.11.2'
implementation 'io.jsonwebtoken:jjwt-impl:0.11.2'
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.2'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'
runtimeOnly 'com.h2database:h2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
Expand Down
39 changes: 39 additions & 0 deletions src/main/java/gift/config/DatabaseInitializer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package gift.config;

import gift.model.Category;
import gift.model.Option;
import gift.model.Product;
import gift.repository.CategoryRepository;
import gift.repository.OptionRepository;
import gift.repository.ProductRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DatabaseInitializer {

@Bean
public CommandLineRunner initDatabase(CategoryRepository categoryRepository, ProductRepository productRepository, OptionRepository optionRepository) {
return args -> {
Category category = new Category("Electronics");
categoryRepository.save(category);

Product product1 = new Product("Smartphone", 500, "image_url_1", category);
Product product2 = new Product("Laptop", 1000, "image_url_2", category);

productRepository.save(product1);
productRepository.save(product2);

Option option1 = new Option("64GB", 100, product1);
Option option2 = new Option("128GB", 200, product1);
Option option3 = new Option("256GB", 150, product2);
Option option4 = new Option("512GB", 250, product2);

optionRepository.save(option1);
optionRepository.save(option2);
optionRepository.save(option3);
optionRepository.save(option4);
};
}
}
23 changes: 23 additions & 0 deletions src/main/java/gift/config/RestTemplateConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package gift.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;

@Configuration
public class RestTemplateConfig {

@Bean
public RestTemplate restTemplate() {
return new RestTemplate(clientHttpRequestFactory());
}

private ClientHttpRequestFactory clientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(5000); // 연결 타임아웃 5초
factory.setReadTimeout(5000); // 읽기 타임아웃 5초
return factory;
}
}
57 changes: 31 additions & 26 deletions src/main/java/gift/controller/KakaoAuthController.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
package gift.controller;

import gift.dto.KakaoTokenResponseDTO;
import gift.dto.KakaoUserDTO;
import gift.model.Member;
import gift.service.KakaoAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class KakaoAuthController {
Expand All @@ -19,28 +22,30 @@ public class KakaoAuthController {
@Value("${kakao.redirect-uri}")
private String redirectUri;

private final RestTemplate restTemplate = new RestTemplate();

@GetMapping("/oauth/kakao/callback")
public ResponseEntity<String> kakaoCallback(@RequestParam String code) {
String tokenUrl = "https://kauth.kakao.com/oauth/token";

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
@Autowired
private KakaoAuthService kakaoAuthService;

MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("grant_type", "authorization_code");
body.add("client_id", clientId);
body.add("redirect_uri", redirectUri);
body.add("code", code);
public KakaoAuthController(KakaoAuthService kakaoAuthService) {
this.kakaoAuthService = kakaoAuthService;
}

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(body, headers);
ResponseEntity<KakaoTokenResponseDTO> response = restTemplate.exchange(tokenUrl, HttpMethod.POST, request, KakaoTokenResponseDTO.class);
@GetMapping("/login/kakao")
public void redirectKakaoLogin(HttpServletResponse response) throws IOException {
String url = kakaoAuthService.getKakaoLoginUrl();
response.sendRedirect(url);
}

if (response.getStatusCode() == HttpStatus.OK) {
return ResponseEntity.ok(response.getBody().toString());
} else {
return ResponseEntity.status(response.getStatusCode()).body("카카오 로그인 실패");
@GetMapping("/oauth/kakao/callback")
public ResponseEntity<String> kakaoCallback(@RequestParam(name = "code") String code) throws IOException {
try {
KakaoTokenResponseDTO tokenResponse = kakaoAuthService.getKakaoToken(code);
KakaoUserDTO kakaoUserDTO = kakaoAuthService.getKakaoUser(
tokenResponse.getAccessToken());
Member member = kakaoAuthService.registerOrGetMember(kakaoUserDTO, tokenResponse.getAccessToken());
return ResponseEntity.ok(tokenResponse.getAccessToken());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("카카오 로그인 실패: " + e.getMessage());
}
}
}
35 changes: 35 additions & 0 deletions src/main/java/gift/controller/OrderController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package gift.controller;

import gift.dto.OrderRequestDTO;
import gift.dto.OrderResponseDTO;
import gift.model.Order;
import gift.service.KakaoAuthService;
import gift.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

@Autowired
private OrderService orderService;

@Autowired
private KakaoAuthService kakaoAuthService;

@PostMapping
public ResponseEntity<OrderResponseDTO> placeOrder(@RequestHeader("Authorization") String token, @RequestBody OrderRequestDTO orderRequestDTO) {
try {
String accessToken = token.substring(7); // "Bearer " 제거
String email = kakaoAuthService.getEmailFromAccessToken(accessToken);
Order order = orderService.placeOrder(email, orderRequestDTO, accessToken);
OrderResponseDTO orderResponseDTO = new OrderResponseDTO(order.getId(), order.getOption().getId(), order.getQuantity(), order.getOrderDateTime(), order.getMessage());
return new ResponseEntity<>(orderResponseDTO, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
4 changes: 4 additions & 0 deletions src/main/java/gift/dto/KakaoTokenResponseDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ public class KakaoTokenResponseDTO {
@JsonProperty("scope")
private String scope;

public String getAccessToken() {
return accessToken;
}

@Override
public String toString() {
return "KakaoTokenResponseDTO{" +
Expand Down
25 changes: 25 additions & 0 deletions src/main/java/gift/dto/KakaoUserDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package gift.dto;

import com.fasterxml.jackson.annotation.JsonProperty;

public class KakaoUserDTO {
@JsonProperty("id")
private Long id;

@JsonProperty("kakao_account")
private KakaoAccount kakaoAccount;

public Long getId() {
return id;
}

public String getEmail() {
return kakaoAccount.email;
}

public static class KakaoAccount {
@JsonProperty("email")
private String email;

}
}
27 changes: 27 additions & 0 deletions src/main/java/gift/dto/OrderRequestDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package gift.dto;

public class OrderRequestDTO {
private Long optionId;
private int quantity;
private String message;

public OrderRequestDTO() {}

public OrderRequestDTO(Long optionId, int quantity, String message) {
this.optionId = optionId;
this.quantity = quantity;
this.message = message;
}

public Long getOptionId() {
return optionId;
}

public int getQuantity() {
return quantity;
}

public String getMessage() {
return message;
}
}
39 changes: 39 additions & 0 deletions src/main/java/gift/dto/OrderResponseDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package gift.dto;

import java.time.LocalDateTime;

public class OrderResponseDTO {
private Long id;
private Long optionId;
private int quantity;
private LocalDateTime orderDateTime;
private String message;

public OrderResponseDTO(Long id, Long optionId, int quantity, LocalDateTime orderDateTime, String message) {
this.id = id;
this.optionId = optionId;
this.quantity = quantity;
this.orderDateTime = orderDateTime;
this.message = message;
}

public Long getId() {
return id;
}

public Long getOptionId() {
return optionId;
}

public int getQuantity() {
return quantity;
}

public LocalDateTime getOrderDateTime() {
return orderDateTime;
}

public String getMessage() {
return message;
}
}
12 changes: 12 additions & 0 deletions src/main/java/gift/model/Member.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ public class Member {
@NotBlank(message = "비밀번호는 공백이 될 수 없습니다.")
private String password;

private String token;

public String getToken() {
return token;
}

@OneToMany(mappedBy = "member", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<WishList> wishLists = new HashSet<>();

Expand All @@ -38,6 +44,12 @@ public Member(String email, String password) {
public Long getId() {
return id;
}

public void setToken(String token) {
this.token = token;
}


public String getEmail() {
return email;
}
Expand Down
62 changes: 62 additions & 0 deletions src/main/java/gift/model/Order.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package gift.model;

import jakarta.persistence.*;
import java.time.LocalDateTime;

@Entity
@Table(name = "`order`")
public class Order {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id")
private Member member;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "option_id")
private Option option;

private int quantity;

private LocalDateTime orderDateTime;

private String message;

public Order() {
}

public Order(Member member, Option option, int quantity, String message) {
this.member = member;
this.option = option;
this.quantity = quantity;
this.orderDateTime = LocalDateTime.now();
this.message = message;
}

public Long getId() {
return id;
}

public Member getMember() {
return member;
}

public Option getOption() {
return option;
}

public int getQuantity() {
return quantity;
}

public LocalDateTime getOrderDateTime() {
return orderDateTime;
}

public String getMessage() {
return message;
}
}
7 changes: 7 additions & 0 deletions src/main/java/gift/repository/OrderRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package gift.repository;

import gift.model.Order;
import org.springframework.data.jpa.repository.JpaRepository;

public interface OrderRepository extends JpaRepository<Order, Long> {
}
Loading