Skip to content

Commit

Permalink
Modify kakao login logic (#87)
Browse files Browse the repository at this point in the history
  • Loading branch information
jinlee1703 authored Sep 23, 2023
2 parents 50a9fb0 + f5ca6e7 commit 92a455b
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 113 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -161,23 +161,16 @@ public ResponseEntity<Message> naverCallback(@RequestParam String code, @Request
);
}

@GetMapping("/sign-in/kakao")
@Operation(summary = "카카오 로그인 메서드", description = "카카오 로그인을 하기 위한 메서드입니다.")
public void kakaoLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.sendRedirect(kakaoService.getAuthorizationUrl());
}

@GetMapping("/sign-in/kakao/callback")
@PostMapping("/sign-in/kakao")
@Operation(summary = "카카오 로그인 콜백 메서드", description = "카카오 로그인 콜백을 하기 위한 메서드입니다.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "카카오 로그인 성공"),
@ApiResponse(responseCode = "400(400-1)", description = "잘못된 프로토콜 요청"),
@ApiResponse(responseCode = "400(400-2)", description = "잘못된 URL 요쳥"),
@ApiResponse(responseCode = "400(500)", description = "HTTP 연결 수행 실패"),
})
public ResponseEntity<Message> kakaoCallback(@RequestParam String code) throws IOException {
TokenDto kakaoTokenDto = kakaoService.getToken(code);
KakaoDto kakaoDto = kakaoService.getUserInfo(kakaoTokenDto);
public ResponseEntity<Message> kakaoCallback(@RequestBody TokenDto dto) throws IOException {
KakaoDto kakaoDto = kakaoService.getUserInfo(dto);
TokenDto tokenDto = kakaoService.signIn(kakaoDto);
Member member = memberService.read(kakaoDto.getUsername());
oAuthService.save(member, OAuthPlatform.KAKAO, kakaoDto.getId());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package org.swmaestro.repl.gifthub.auth.dto;

import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
Expand All @@ -9,8 +12,8 @@
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class TokenDto {
private String accessToken;
private String refreshToken;

}
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package org.swmaestro.repl.gifthub.auth.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
Expand All @@ -13,7 +11,6 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;
import org.swmaestro.repl.gifthub.auth.dto.KakaoDto;
import org.swmaestro.repl.gifthub.auth.dto.TokenDto;
import org.swmaestro.repl.gifthub.auth.entity.Member;
Expand All @@ -25,97 +22,18 @@
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import lombok.RequiredArgsConstructor;

@Service
@PropertySource("classpath:application.yml")
@RequiredArgsConstructor
public class KakaoService {
private final MemberService memberService;
private final MemberRepository memberRepository;
private final RefreshTokenService refreshTokenService;
private final String clientId;
private final String redirectUri;
private final JwtProvider jwtProvider;
private final String authorizationUri;
private final String tokenUri;
private final String userInfoUri;

public KakaoService(MemberService memberService, MemberRepository memberRepository, RefreshTokenService refreshTokenService,
JwtProvider jwtProvider, @Value("${kakao.client_id}") String clientId, @Value("${kakao.redirect_uri}") String redirectUri,
@Value("${kakao.authorization_uri}") String authorizationUri, @Value("${kakao.user_info_uri}") String userInfoUri,
@Value("${kakao.token_uri}") String tokenUri) {
this.memberService = memberService;
this.memberRepository = memberRepository;
this.refreshTokenService = refreshTokenService;
this.jwtProvider = jwtProvider;
this.clientId = clientId;
this.redirectUri = redirectUri;
this.authorizationUri = authorizationUri;
this.userInfoUri = userInfoUri;
this.tokenUri = tokenUri;
}

public String getAuthorizationUrl() {
return UriComponentsBuilder
.fromUriString(authorizationUri)
.queryParam("client_id", clientId)
.queryParam("redirect_uri", redirectUri)
.queryParam("response_type", "code")
.build()
.toString();
}

public TokenDto getToken(String code) throws MalformedURLException {

TokenDto tokenDto = null;
try {
URL url = new URL(tokenUri);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();

conn.setRequestMethod("POST");
conn.setDoOutput(true);

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
StringBuilder sb = new StringBuilder();

sb.append("grant_type=authorization_code");
sb.append("&client_id=" + clientId);
sb.append("&redirect_uri=" + redirectUri);
sb.append("&code=" + code);
bw.write(sb.toString());
bw.flush();

int responseCode = conn.getResponseCode();

BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
String result = "";

while ((line = br.readLine()) != null) {
result += line;
}

JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result);

String accessToken = element.getAsJsonObject().get("access_token").getAsString();
String refreshToken = element.getAsJsonObject().get("refresh_token").getAsString();

br.close();
bw.close();

tokenDto = TokenDto.builder()
.accessToken(accessToken)
.refreshToken(refreshToken)
.build();
} catch (ProtocolException e) {
throw new BusinessException("잘못된 프로토콜을 사용하였습니다.", StatusEnum.BAD_REQUEST);
} catch (MalformedURLException e) {
throw new BusinessException("잘못된 URL 형식을 사용하였습니다.", StatusEnum.BAD_REQUEST);
} catch (IOException e) {
throw new BusinessException("HTTP 연결을 수행하는 동안 입출력 관련 오류가 발생하였습니다.", StatusEnum.INTERNAL_SERVER_ERROR);
}

return tokenDto;
}
@Value("${kakao.user_info_uri}")
private String userInfoUri;

public KakaoDto getUserInfo(TokenDto tokenDto) {

Expand Down Expand Up @@ -146,10 +64,13 @@ public KakaoDto getUserInfo(TokenDto tokenDto) {

String id = Integer.toString(element.getAsJsonObject().get("id").getAsInt());
String nickname = element.getAsJsonObject().get("kakao_account").getAsJsonObject().get("profile").getAsJsonObject().get("nickname").getAsString();
boolean hasEmail = element.getAsJsonObject().get("kakao_account").getAsJsonObject().get("has_email").getAsBoolean();
String email = null;
if (hasEmail) {
email = element.getAsJsonObject().get("kakao_account").getAsJsonObject().get("email").getAsString();

JsonElement emailJsonElement = element.getAsJsonObject().get("kakao_account").getAsJsonObject().get("email");
String email = "";
if (emailJsonElement == null) {
email = "";
} else {
email = emailJsonElement.getAsString();
}
br.close();
kakaoDto = KakaoDto.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,11 +137,7 @@ public void reissueAccessTokenTest() throws Exception {
}

@Test
public void kakaoSignInCallbackTest() throws Exception {
String accesstoken = "myawesome_accesstoken";
String code = "myawesome_code";
String state = "myawesome_state";

public void kakaoSignInTest() throws Exception {
TokenDto kakaoTokenDto = TokenDto.builder()
.accessToken("myawesomeKakaojwt")
.refreshToken("myawesomeKakaojwt")
Expand All @@ -162,16 +158,13 @@ public void kakaoSignInCallbackTest() throws Exception {
.nickname(kakaoDto.getNickname())
.build();

when(kakaoService.getToken(code)).thenReturn(kakaoTokenDto);
when(kakaoService.getUserInfo(kakaoTokenDto)).thenReturn(kakaoDto);
when(memberService.read(kakaoDto.getUsername())).thenReturn(member);

when(kakaoService.signIn(kakaoDto)).thenReturn(tokenDto);

mockMvc.perform(get("/auth/sign-in/kakao/callback")
.queryParam("code", code)
.queryParam("state", state)
.header("Authorization", "Bearer " + accesstoken))
mockMvc.perform(post("/auth/sign-in/kakao")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(kakaoTokenDto)))
.andExpect(status().isOk());
}

Expand Down

0 comments on commit 92a455b

Please sign in to comment.