Skip to content

Commit

Permalink
feat: create kakao signin api
Browse files Browse the repository at this point in the history
  • Loading branch information
Kang1221 committed Aug 10, 2024
1 parent 6118d6f commit be97e8e
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 28 deletions.
11 changes: 7 additions & 4 deletions src/main/java/co/orange/ddanzi/controller/AuthController.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package co.orange.ddanzi.controller;

import co.orange.ddanzi.dto.auth.LoginDto;
import co.orange.ddanzi.domain.user.enums.LoginType;
import co.orange.ddanzi.dto.auth.SigninRequestDto;
import co.orange.ddanzi.global.common.response.ApiResponse;
import co.orange.ddanzi.service.AuthService;
import com.fasterxml.jackson.core.JsonProcessingException;
Expand All @@ -17,12 +18,14 @@ public class AuthController {
private final AuthService authService;

@PostMapping("/signin/test")
ApiResponse<?> test(@RequestBody LoginDto requestDto){
ApiResponse<?> test(@RequestBody SigninRequestDto requestDto){
return authService.testSignin(requestDto.getToken());
}

@PostMapping("/signin")
ApiResponse<?> signin(@RequestBody LoginDto requestDto) {
return authService.testSignin(requestDto.getToken());
ApiResponse<?> signin(@RequestBody SigninRequestDto requestDto) throws JsonProcessingException {
if(requestDto.getType().equals(LoginType.KAKAO))
return authService.kakaoSignIn(requestDto.getToken());
return authService.kakaoSignIn(requestDto.getToken());
}
}
83 changes: 59 additions & 24 deletions src/main/java/co/orange/ddanzi/service/AuthService.java
Original file line number Diff line number Diff line change
@@ -1,28 +1,35 @@
package co.orange.ddanzi.service;

import co.orange.ddanzi.domain.user.User;
import co.orange.ddanzi.domain.user.enums.LoginType;
import co.orange.ddanzi.domain.user.enums.UserStatus;
import co.orange.ddanzi.dto.auth.AuthResponseDto;
import co.orange.ddanzi.dto.auth.LoginResponseDto;
import co.orange.ddanzi.dto.auth.SigninResponseDto;
import co.orange.ddanzi.global.common.error.Error;
import co.orange.ddanzi.global.common.response.ApiResponse;
import co.orange.ddanzi.global.common.response.Success;
import co.orange.ddanzi.global.config.jwt.JwtUtils;
import co.orange.ddanzi.repository.UserRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Optional;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
Expand All @@ -35,61 +42,69 @@ public class AuthService {
@Transactional
public ApiResponse<?> testSignin(String idToken){

Optional<User> optionalUser = userRepository.findByLoginId(idToken);
Optional<User> optionalUser = userRepository.findByEmail(idToken);
if(optionalUser.isEmpty()){
return ApiResponse.onFailure(Error.ERROR, null);
}
User user = optionalUser.get();

AuthResponseDto responseDto = AuthResponseDto.builder()
.accesstoken(jwtUtils.createAccessToken(user.getLoginId()))
.accesstoken(jwtUtils.createAccessToken(user.getEmail()))
.nickname(user.getNickname())
.build();
return ApiResponse.onSuccess(Success.SUCCESS, responseDto);
}

@Transactional
public ApiResponse<?> signinKakao(String token) throws JsonProcessingException {
public ApiResponse<?> kakaoSignIn(String token) throws JsonProcessingException {
log.info("카카오 로그인 진입");
String email = getKakaoEmail(token);
log.info("카카오 이메일 조회 성공 email: {}", email);
Optional<User> user = userRepository.findByEmail(email);

User user = checkKakaoUserExist(email);
if (user.isEmpty()){
log.info("카카오 회원 가입 시작");
kakaoSignUp(email);
user = userRepository.findByEmail(email);
}

LoginResponseDto responseDto = LoginResponseDto.builder()
SigninResponseDto responseDto = SigninResponseDto.builder()
.accesstoken(jwtUtils.createAccessToken(email))
.refreshtoken(jwtUtils.createRefreshToken(email))
.nickname("예시닉네임")
.nickname(user.get().getNickname())
.build();
return ApiResponse.onSuccess(Success.SIGNIN_KAKAO_SUCCESS, responseDto);
}


public User checkKakaoUserExist (String email) {
// DB에 중복되는 email이 있는지 확인
Optional<User> user = userRepository.findByLoginId(email);

// 회원가입
if (user.isEmpty()) {
}

return user.get();
public void kakaoSignUp(String email) {
User user = User.builder()
.email(email)
.type(LoginType.KAKAO)
.status(UserStatus.UNAUTHENTICATED)
.nickname(generateNickname())
.build();
userRepository.save(user);
}

public String getKakaoEmail(String accessToken) throws JsonProcessingException {
// HTTP Header 생성
log.info("HTTP 해더 생성");
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + accessToken);
headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8");

// HTTP 요청 보내기
HttpEntity<MultiValueMap<String, String>> kakaoUserInfoRequest = new HttpEntity<>(headers);
log.info("HTTP 요청 보내기");
HttpEntity<String> kakaoUserInfoRequest = new HttpEntity<>(headers);
RestTemplate rt = new RestTemplate();

ResponseEntity<String> response = rt.exchange(
"https://kapi.kakao.com/v2/user/me",
HttpMethod.POST,
HttpMethod.GET,
kakaoUserInfoRequest,
String.class
);

// responseBody에 있는 정보 꺼내기
log.info("응답 수신 성공");
String responseBody = response.getBody();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(responseBody);
Expand All @@ -98,6 +113,26 @@ public String getKakaoEmail(String accessToken) throws JsonProcessingException {

return email;
}

private List<String> loadWordsFromFile(String classpath) throws IOException {
ClassPathResource resource = new ClassPathResource(classpath);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
return reader.lines().collect(Collectors.toList());
}
}
private String generateNickname() {
try {
List<String> adjectives = loadWordsFromFile("nickname/adjectives.txt");
List<String> animals = loadWordsFromFile("nickname/animals.txt");
String selectedAdjectives = adjectives.get(new Random().nextInt(adjectives.size()));
String selectedAnimals = animals.get(new Random().nextInt(animals.size()));
int randomSuffix = (int) (Math.random() * 100);
return selectedAdjectives + selectedAnimals + randomSuffix;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}


0 comments on commit be97e8e

Please sign in to comment.