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

Fix: 구글 로그인 로직 복원 #183

Merged
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 @@ -9,8 +9,7 @@ public enum UserExceptionStatus implements BaseExceptionStatus {
GOOGLE_TOKEN_INVALID("유효하지 않은 구글 토큰입니다.", 400, "14000"),
REFRESH_TOKEN_INVALID("유효하지 않은 토큰입니다.", 400, "14001"),
REFRESH_TOKEN_EXPIRED("유효기간이 만료된 토큰입니다.", 400, "14002"),
GOOGLE_CODE_MISSING("구글 코드를 입력하지 않았습니다.", 400, "14003"),
GOOGLE_CODE_INVALID("유효하지 않은 구글 코드입니다.", 400, "14004"),
GOOGLE_TOKEN_MISSING("구글 토큰를 입력하지 않았습니다.", 400, "14003"),
USER_NOT_FOUND("회원이 존재하지 않습니다", 404, "14040"),
GOOGLE_API_CONNECTION_ERROR("구글 API 연동 중 문제가 발생했습니다", 500, "15000");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,25 +68,24 @@ public String redirectGoogleLogin(
if (error.isPresent()) {
return error.get();
}
return code;
// MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
// parameters.add("grant_type", "authorization_code");
// parameters.add("client_id", clientId);
// parameters.add("redirect_uri", redirectUri);
// parameters.add("code", code);
// parameters.add("client_secret", clientSecret);
//
// try {
// HttpHeaders headers = new HttpHeaders();
// headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// HttpEntity<?> httpRequestEntity = new HttpEntity<>(parameters, headers);
// ResponseEntity<String> response = restTemplate.postForEntity(tokenUri, httpRequestEntity, String.class);
// GoogleTokenResponseDto responseDto = om.readValue(response.getBody(), GoogleTokenResponseDto.class);
// return responseDto.accessToken();
// } catch (Exception e) {
// System.out.println(e.getMessage());
// }
// return "failed";
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("grant_type", "authorization_code");
parameters.add("client_id", clientId);
parameters.add("redirect_uri", redirectUri);
parameters.add("code", code);
parameters.add("client_secret", clientSecret);

try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<?> httpRequestEntity = new HttpEntity<>(parameters, headers);
ResponseEntity<String> response = restTemplate.postForEntity(tokenUri, httpRequestEntity, String.class);
GoogleTokenResponseDto responseDto = om.readValue(response.getBody(), GoogleTokenResponseDto.class);
return responseDto.accessToken();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return "failed";
}

private record GoogleTokenResponseDto(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,9 @@ public class GoogleLoginController {

@PostMapping("/login")
public ResponseEntity<?> loginGoogle(HttpServletRequest request) {
String code = Optional.ofNullable(request.getHeader("Google")).orElseThrow(
() -> new Exception400(UserExceptionStatus.GOOGLE_CODE_MISSING));
String accessToken = Optional.ofNullable(request.getHeader("Google")).orElseThrow(
() -> new Exception400(UserExceptionStatus.GOOGLE_TOKEN_MISSING));

String accessToken = googleService.getGoogleAccessToken(code);
GoogleUserInfo userInfo = googleService.getGoogleUserInfo(accessToken);
LoginResponseDto resultDto = userService.socialLogin(userInfo);
return ResponseEntity.ok(ApiUtils.success(resultDto));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,10 @@
@Slf4j
public class GoogleService {

@Value("${oauth2.google.redirect_uri}")
private String redirectUri;
@Value("${oauth2.google.client_secret}")
private String clientSecret;
@Value("${oauth2.google.client_id}")
private String clientId;
private static final String tokenUri = "https://oauth2.googleapis.com/token";
private static final String GOOGLE_INFO_URI = "https://www.googleapis.com/oauth2/v2/userinfo";

private final RestTemplate restTemplate;

private final ObjectMapper om;

public GoogleUserInfo getGoogleUserInfo(String token) {
HttpHeaders httpHeaders = new HttpHeaders();
Expand All @@ -58,36 +50,4 @@ public GoogleUserInfo getGoogleUserInfo(String token) {
throw new Exception500(UserExceptionStatus.GOOGLE_API_CONNECTION_ERROR);
}
}

public String getGoogleAccessToken(String code) {
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("grant_type", "authorization_code");
parameters.add("client_id", clientId);
parameters.add("redirect_uri", redirectUri);
parameters.add("code", code);
parameters.add("client_secret", clientSecret);

try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<?> httpRequestEntity = new HttpEntity<>(parameters, headers);
ResponseEntity<GoogleTokenResponseDto> response = restTemplate.exchange(
tokenUri,
HttpMethod.POST,
httpRequestEntity,
GoogleTokenResponseDto.class
);

return response.getBody().accessToken();
}catch (HttpClientErrorException e) {
if (e.getStatusCode().value() == 400) {
throw new Exception400(UserExceptionStatus.GOOGLE_CODE_INVALID);
}
log.error(e.getMessage());
throw new Exception500(UserExceptionStatus.GOOGLE_API_CONNECTION_ERROR);
} catch (Exception e) {
log.error(e.getMessage());
throw new Exception500(UserExceptionStatus.GOOGLE_API_CONNECTION_ERROR);
}
}
}
8 changes: 0 additions & 8 deletions linknamu/src/main/resources/application-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,6 @@ security:
# 기본 보안 설정을 비활성화합니다. => 즉 2단계 처럼 사용자정의보안코드를 작성하라는 말이겠죠?
enabled: false

oauth2:
google:
client_id : test_client_id
auth_uri : test_auth_uri
token_uri : test_token_uri
client_secret : test_client_secret
redirect_uri : test_redirect_uri

##access랑 refresh token은 이경님이 맘대로 설정해주세요...ㅎ
access-jwt-secret-key: KakaoTechCampusLinkNamu
refresh-jwt-secret-key: KakaoTechCampusLinkNamu1234
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,21 +49,13 @@ void successNoUserInDB() throws Exception {
GoogleUserInfo googleUserInfo = new GoogleUserInfo("123", "[email protected]",
true, null);
String googleToken = "googleAccessToken";
GoogleTokenResponseDto googleTokenResponseDto = new GoogleTokenResponseDto(
googleToken,
123,
"token",
"scope",
"refreshToken");


// mock
given(
restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), eq(GoogleUserInfo.class)))
.willReturn(ResponseEntity.ok((googleUserInfo)));
given(
restTemplate.exchange(anyString(), eq(HttpMethod.POST), any(HttpEntity.class), eq(GoogleTokenResponseDto.class)))
.willReturn(ResponseEntity.ok((googleTokenResponseDto)));


// when
ResultActions resultActions = mvc.perform(
Expand Down Expand Up @@ -94,21 +86,13 @@ void successUserInDB() throws Exception {
GoogleUserInfo googleUserInfo = new GoogleUserInfo("123", "[email protected]",
true, null);
String googleToken = "googleAccessToken";
GoogleTokenResponseDto googleTokenResponseDto = new GoogleTokenResponseDto(
googleToken,
123,
"token",
"scope",
"refreshToken");


// mock
given(
restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), eq(GoogleUserInfo.class)))
.willReturn(ResponseEntity.ok((googleUserInfo)));
given(
restTemplate.exchange(anyString(), eq(HttpMethod.POST), any(HttpEntity.class), eq(GoogleTokenResponseDto.class)))
.willReturn(ResponseEntity.ok((googleTokenResponseDto)));


// when
ResultActions resultActions = mvc.perform(
Expand Down