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

14조 코드리뷰 5회차 #69

Merged
merged 1 commit into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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 @@ -42,6 +42,7 @@ dependencies {
implementation "io.jsonwebtoken:jjwt-api:${jjwt_version}"
implementation "org.springdoc:springdoc-openapi-starter-webmvc-ui:${swagger_version}"
implementation 'org.mapstruct:mapstruct:1.6.2'
implementation 'ch.hsr:geohash:1.4.0'

annotationProcessor 'org.mapstruct:mapstruct-processor:1.6.2'

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class JwtUtil {
private final SecretKey key;
private final int expireTime;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,56 +1,29 @@
package com.ordertogether.team14_be.auth.application.service;

import com.ordertogether.team14_be.auth.JwtUtil;
import com.ordertogether.team14_be.auth.application.dto.KakaoUserInfo;
import com.ordertogether.team14_be.auth.presentation.KakaoClient;
import com.ordertogether.team14_be.common.web.response.ApiResponse;
import com.ordertogether.team14_be.member.application.service.MemberService;
import com.ordertogether.team14_be.member.persistence.entity.Member;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

@RequiredArgsConstructor
@Service
public class AuthService {

private final KakaoClient kakaoClient;
private final MemberService memberService;
private final JwtUtil jwtUtil;

@Value(("${FRONT_PAGE_SIGNUP}"))
String redirectPage;

public ResponseEntity<ApiResponse<String>> kakaoLogin(String authorizationCode) {
String kakaoToken = kakaoClient.getAccessToken(authorizationCode); // 인가코드로부터 카카오토큰 발급
KakaoUserInfo kakaoUserInfo = kakaoClient.getUserInfo((kakaoToken));
String userKakaoEmail = kakaoUserInfo.kakaoAccount().email(); // 와 사용자 카카오 이메일이야

Optional<Member> existMember = memberService.findMemberByEmail(userKakaoEmail);
if (existMember.isPresent()) {
String serviceToken =
jwtUtil.generateToken(memberService.getMemberId(userKakaoEmail)); // 서비스 토큰 줘야징
return ResponseEntity.ok((ApiResponse.with(HttpStatus.OK, "로그인 성공", serviceToken)));
} else {
return ResponseEntity.status(HttpStatus.FOUND)
.location(
URI.create(redirectPage + URLEncoder.encode(userKakaoEmail, StandardCharsets.UTF_8)))
.build();
}
public AuthService(MemberService memberService, JwtUtil jwtUtil) {
this.memberService = memberService;
this.jwtUtil = jwtUtil;
}

public ResponseEntity<ApiResponse<String>> register(
String email, String deliveryName, String phoneNumber) {
public String register(String email, String deliveryName, String phoneNumber) {
Member member = new Member(email, deliveryName, phoneNumber);
memberService.registerMember(member);
Long memberId = memberService.getMemberId(email);
String serviceToken = jwtUtil.generateToken(memberId);
return ResponseEntity.ok((ApiResponse.with(HttpStatus.OK, "회원가입 및 로그인 성공", serviceToken)));
return serviceToken;
}

public String getServiceToken(String email) {
return jwtUtil.generateToken(memberService.getMemberId(email));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.ordertogether.team14_be.auth.application.service;

import com.ordertogether.team14_be.auth.application.dto.KakaoUserInfo;
import com.ordertogether.team14_be.auth.presentation.KakaoClient;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@RequiredArgsConstructor
@Service
public class KakaoAuthService {
private final KakaoClient kakaoClient;

public String getKakaoUserEmail(String authorizationCode) {
String kakaoToken = kakaoClient.getAccessToken(authorizationCode);
KakaoUserInfo kakaoUserInfo = kakaoClient.getUserInfo((kakaoToken));
String userKakaoEmail = kakaoUserInfo.kakaoAccount().email();
return userKakaoEmail;
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
package com.ordertogether.team14_be.auth.presentation;

import com.ordertogether.team14_be.auth.application.service.AuthService;
import com.ordertogether.team14_be.auth.application.service.KakaoAuthService;
import com.ordertogether.team14_be.common.web.response.ApiResponse;
import com.ordertogether.team14_be.member.application.dto.MemberInfoRequest;
import lombok.RequiredArgsConstructor;
import com.ordertogether.team14_be.member.application.service.MemberService;
import com.ordertogether.team14_be.member.persistence.entity.Member;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
Expand All @@ -13,16 +21,49 @@
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/auth")
public class AuthController {

private final AuthService authService;
private final KakaoAuthService kakaoAuthService;
private final String redirectPage;
private final MemberService memberService;

public AuthController(
AuthService authService,
KakaoAuthService kakaoAuthService,
MemberService memberService,
@Value("${FRONT_PAGE_SIGNUP}") String redirectPage) {
this.authService = authService;
this.kakaoAuthService = kakaoAuthService;
this.memberService = memberService;
this.redirectPage = redirectPage;
}

@GetMapping("/login")
public ResponseEntity<ApiResponse<String>> getToken(@RequestHeader String authorizationCode) {
return authService.kakaoLogin(authorizationCode);
String userKakaoEmail = kakaoAuthService.getKakaoUserEmail(authorizationCode);
Optional<Member> existMember = memberService.findMemberByEmail(userKakaoEmail);
if (existMember.isPresent()) {
return ResponseEntity.ok(
ApiResponse.with(HttpStatus.OK, "로그인 성공", authService.getServiceToken(userKakaoEmail)));

} else {
return ResponseEntity.status(HttpStatus.FOUND)
.location(
URI.create(redirectPage + URLEncoder.encode(userKakaoEmail, StandardCharsets.UTF_8)))
.build();
}
}

@PostMapping("/signup")
public ResponseEntity<ApiResponse<String>> signUpMember(
@RequestParam String email, @RequestBody MemberInfoRequest memberInfoRequest) {
String serviceToken =
authService.register(
email, memberInfoRequest.deliveryName(), memberInfoRequest.phoneNumber());
return ResponseEntity.ok(ApiResponse.with(HttpStatus.OK, "로그인 성공", serviceToken));
}

@PostMapping("/signup")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class ApiResponse<T> {

private Integer status;
private String message;
private T data;
private final Integer status;
private final String message;
private final T data;

public static <T> ApiResponse<T> with(HttpStatus httpStatus, String message, @Nullable T data) {
return new ApiResponse<>(httpStatus.value(), message, data);
}

public static <T> ApiResponse<T> with(HttpStatus httpStatus, String message) {
return new ApiResponse<>(httpStatus.value(), message, null);
}
}
19 changes: 19 additions & 0 deletions src/main/java/com/ordertogether/team14_be/config/CorsConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.ordertogether.team14_be.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Frontend와 Backend서버간 Origin이 서로 달라서 CORS 설정을 해주신것 같아요.
서로 같은 Origin이 되도록 웹 서버 (NGINX) 를 하나 두고, 이를 통해 FE의 파일들과, BE의 API를 제공하면 CORS 헤더 없이도 문제를 해결할 수 있을까요?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오호.. nginx를 활용해서 해결할 수도 있는거였군요,, 좋은 방법 알려주셔서 감사합니다! nginx통해서 https 통신을 해보려고 했는데 이 과정 중에서 적용해보겠습니다..!

@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("Authorization", "Content-Type")
.exposedHeaders("Custom-Header")
.maxAge(3600);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,12 @@ public AuditorAware<Long> auditorProvider() {

@Bean
public PaymentEventRepository paymentEventRepository(
SimpleJpaPaymentEventRepository simpleJpaPaymentEventRepository) {
return new JpaPaymentEventRepository(simpleJpaPaymentEventRepository);
SimpleJpaPaymentEventRepository simpleJpaPaymentEventRepository,
SimpleJpaPaymentOrderRepository simpleJpaPaymentOrderRepository,
SimpleJpaProductRepository simpleJpaProductRepository) {
return new JpaPaymentEventRepository(
simpleJpaPaymentEventRepository,
paymentOrderRepository(simpleJpaPaymentOrderRepository, simpleJpaProductRepository));
}

@Bean
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.ordertogether.team14_be.member.application.service;

import com.ordertogether.team14_be.auth.JwtUtil;
import com.ordertogether.team14_be.member.application.dto.MemberInfoResponse;
import com.ordertogether.team14_be.member.application.exception.NotFoundMember;
import com.ordertogether.team14_be.member.persistence.MemberRepository;
Expand Down Expand Up @@ -37,6 +36,25 @@ public MemberInfoResponse findMemberInfo(Long memberId) {
.build();
}

@Transactional(readOnly = true)
public Long getMemberId(String email) {
return memberRepository
.findByEmail(email)
.map(Member::getId)
.orElseThrow(() -> new NoSuchElementException("Member with email " + email + " not found"));
}

@Transactional(readOnly = true)
public MemberInfoResponse findMemberInfo(Long memberId) {
Member member = findMember(memberId);

return MemberInfoResponse.builder()
.deliveryName(member.getDeliveryName())
.phoneNumber(member.getPhoneNumber())
.point(member.getPoint())
.build();
}

@Transactional
public MemberInfoResponse modifyMember(Long memberId, String deliveryName, String phoneNumber) {
Member member = findMember(memberId);
Expand Down Expand Up @@ -65,12 +83,8 @@ public Optional<Member> findMemberByEmail(String email) {
return memberRepository.findByEmail(email);
}

@Transactional
public void registerMember(Member member) {
memberRepository.saveAndFlush(member);
}

public Long getMemberId(String email) {
Member member = memberRepository.findByEmail(email).get();
return member.getId();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@ public class Member {

protected Member() {}

public Member(
Long id, String email, int point, String phoneNumber, String deliveryName, String platform) {
this.id = id;
this.email = email;
this.point = point;
this.phoneNumber = phoneNumber;
this.deliveryName = deliveryName;
this.platform = platform;
}

public Member(String email, int point, String phoneNumber, String deliveryName, String platform) {
this.email = email;
this.point = point;
Expand Down Expand Up @@ -73,18 +83,8 @@ public void modifyMemberInfo(String deliveryName, String phoneNumber) {
this.phoneNumber = phoneNumber;
}

public void modifyMemberInfo(String deliveryName, String phoneNumber) {
this.deliveryName = deliveryName;
this.phoneNumber = phoneNumber;
}

public void modifyMemberInfo(String deliveryName, String phoneNumber) {
this.deliveryName = deliveryName;
this.phoneNumber = phoneNumber;
}

public void modifyMemberInfo(String deliveryName, String phoneNumber) {
this.deliveryName = deliveryName;
this.phoneNumber = phoneNumber;
public Integer increasePoint(int point) {
this.point += point;
return this.point;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.ordertogether.team14_be.memebr.application.service;

import com.ordertogether.team14_be.memebr.persistence.MemberRepository;
import com.ordertogether.team14_be.memebr.persistence.entity.Member;
import org.springframework.stereotype.Service;

@Service
public class MemberService {

private final MemberRepository memberRepository;

public MemberService(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}

public void findOrCreateMember(String email) {
Member member =
memberRepository
.findByEmail(email)
.orElseGet(
() -> {
Member newMember = Member.createMember(email);
return memberRepository.saveAndFlush(newMember);
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.ordertogether.team14_be.memebr.persistence;

import com.ordertogether.team14_be.memebr.persistence.entity.Member;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface MemberRepository extends JpaRepository<Member, Long> {

Optional<Member> findByEmail(String email);
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,12 @@ public enum PaymentStatus {
FAIL("결제 실패");

private final String description;

public boolean isSuccess() {
return this == SUCCESS;
}

public boolean isFail() {
return this == FAIL;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ public class PaymentEventEntity extends BaseTimeEntity {
@Column(nullable = false)
private String orderName;

@Column(nullable = false)
private String paymentKey; // PSP 결제 식별자

@Builder.Default
Expand Down
Loading