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

[FEAT] 이메일 중복 체크 API 구현 #126

Merged
merged 4 commits into from
Aug 30, 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
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fav.daengnyang.domain.member.service.MemberService;
import com.fav.daengnyang.domain.member.service.dto.request.CheckRequest;
import com.fav.daengnyang.domain.member.service.dto.request.CreatedRequest;
import com.fav.daengnyang.domain.member.service.dto.request.LoginRequest;
import com.fav.daengnyang.domain.member.service.dto.response.LoginResponse;
import com.fav.daengnyang.domain.member.service.dto.response.MemberInfoResponse;
import com.fav.daengnyang.domain.pet.service.dto.response.CheckResponse;
import com.fav.daengnyang.global.auth.AuthService;
import com.fav.daengnyang.global.auth.dto.MemberPrincipal;
import com.fav.daengnyang.global.auth.utils.JWTProvider;
Expand All @@ -16,6 +18,8 @@
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@RequestMapping("/members")
@Slf4j
Expand Down Expand Up @@ -46,5 +50,13 @@ public SuccessResponse<MemberInfoResponse> getMemberInfo(@AuthenticationPrincipa
MemberInfoResponse memberInfoResponse = memberService.getMemberInfo(memberPrincipal.getMemberId());
return SuccessResponse.ok(memberInfoResponse);
}

// 이메일 중복 체크
@PostMapping("/check")
public SuccessResponse<?> checkDuplicateEmail(@RequestBody CheckRequest checkRequest) throws JsonProcessingException {

CheckResponse response = memberService.checkDuplicateEmail(checkRequest.getEmail());
return SuccessResponse.ok(response);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import com.fav.daengnyang.domain.member.service.dto.response.LoginResponse;
import com.fav.daengnyang.domain.member.service.dto.response.MemberBankResponse;
import com.fav.daengnyang.domain.member.service.dto.response.MemberInfoResponse;
import com.fav.daengnyang.domain.pet.service.dto.response.CheckResponse;
import com.fav.daengnyang.domain.target.repository.TargetRepository;
import com.fav.daengnyang.global.auth.dto.MemberPrincipal;
import com.fav.daengnyang.global.auth.utils.JWTProvider;
Expand All @@ -27,6 +28,7 @@
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;

Expand Down Expand Up @@ -55,6 +57,7 @@ public class MemberService implements UserDetailsService {
public LoginResponse createMember(CreatedRequest createdRequest) throws JsonProcessingException {
// 1. 금융 API 회원가입
MemberBankResponse memberBankResponse = createMemberBank(createdRequest);
System.out.println("memberBankResponse: " + memberBankResponse);
// 2. 예금 계좌 개설
String depositAccount = createMemberAccount(memberBankResponse);
// 3. 비밀번호 인코딩
Expand All @@ -81,6 +84,11 @@ public Member findByMemberId(Long id) {
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));
}

// 이메일 중복 체크
public CheckResponse checkDuplicateEmail(String email) throws JsonProcessingException {
return checkMemberBank(email);
}

@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

Expand Down Expand Up @@ -120,7 +128,6 @@ private MemberBankResponse createMemberBank(CreatedRequest createdRequest) throw

log.info("회원 가입 API 결과: " + response.getBody());
return objectMapper.readValue(response.getBody(), MemberBankResponse.class);

}

// 계좌 생성 API
Expand Down Expand Up @@ -195,4 +202,35 @@ public MemberInfoResponse getMemberInfo(Long memberId) {
.memberTarget(totalTargets)
.build();
}

private CheckResponse checkMemberBank(String email) throws JsonProcessingException {
// 1. body 객체 생성
HashMap<String, String> body = new HashMap<>();
body.put("apiKey", apiKey);
body.put("userId", email);

// 2. HttpHeaders 설정
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

// 3. HttpEntity 객체 생성
HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(body, headers);

// 4. 외부 API 호출
String url = "/member/search";
try{
ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
log.info("아이디 중복체크" + response.getBody());

return CheckResponse.createCheckResponse("이미 존재하는 이메일입니다.");

} catch (HttpClientErrorException e) {
log.info("아이디 중복체크" + e.getResponseBodyAsString());
CheckResponse checkResponse = objectMapper.readValue(e.getResponseBodyAsString(), CheckResponse.class);
if(checkResponse.getResponseCode().equals("E4003")){
checkResponse.updateCheckResponse("사용가능한 이메일입니다.");
}
return checkResponse;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.fav.daengnyang.domain.member.service.dto.request;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.apache.logging.log4j.core.config.plugins.validation.constraints.NotBlank;

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
public class CheckRequest {
@NotBlank
String email;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.fav.daengnyang.domain.pet.service.dto.response;

import lombok.*;
import org.hibernate.annotations.Check;

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@ToString
public class CheckResponse {

private String responseCode;
private String responseMessage;

@Builder
private CheckResponse(String responseCode, String responseMessage) {
this.responseCode = responseCode;
this.responseMessage = responseMessage;
}

public static CheckResponse createCheckResponse(String responseMessage) {
return CheckResponse.builder()
.responseMessage(responseMessage)
.build();
}

public void updateCheckResponse(String responseMessage){
this.responseMessage = responseMessage;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo
// 로그인, 회원가입은 필터를 적용하지 않음
String requestURI = request.getRequestURI();
logger.info("requestURI : " + requestURI);
if (requestURI.equals("/api/v1/members") || requestURI.equals("/api/v1/members/login")) {
if (requestURI.equals("/api/v1/members") || requestURI.equals("/api/v1/members/login") || requestURI.equals("/api/v1/members/check")) {
filterChain.doFilter(request, servletResponse);
return;
}
Expand All @@ -48,12 +48,11 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo
if (StringUtils.hasText(jwt) && jwtProvider.validateToken(jwt)) {
Long memberId = jwtProvider.getMemberId(jwt);
String userKey = jwtProvider.getUserKey(jwt);
log.info("0");

Member member = memberService.findByMemberId(memberId);

log.info("1");
UserDetails userDetails = MemberPrincipal.createMemberAuthority(member, userKey);
log.info("3");

UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http, MemberService
return http.cors(Customizer.withDefaults())
.csrf((csrf) -> csrf.disable())
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/members", "/members/login").permitAll()
.requestMatchers("/members", "/members/login", "/members/check").permitAll()
.anyRequest().authenticated())
.sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.disable()) // 로그인 폼 미사용
Expand Down
Loading