Skip to content

Commit

Permalink
[fix] 구글 로그인 api 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
hysong4u committed Apr 16, 2024
1 parent d314524 commit 90dc85f
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ public class OauthController {
@GetMapping("/code/{registrationId}")
ResponseEntity<SuccessResponse<?>> googleLogin(@RequestParam (name = "code") String code, @PathVariable (name = "registrationId") String registrationId) {

Long userId = oauthService.socialLogin(code, registrationId);
Long userId = oauthService.socialLogin(code, registrationId);
String accessToken = userService.issueNewAccessToken(userId);
String randomNickname = userService.generateNickname();

LoginResponseDto response = new LoginResponseDto(accessToken, randomNickname);

return SuccessResponse.ok(response);
}


}
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
package com.example.comma.domain.user.service;

import com.example.comma.domain.user.dto.response.UserInfoResponseDto;
import com.example.comma.domain.user.dto.response.UserTokenResponseDto;
import com.example.comma.domain.user.entity.User;
import com.example.comma.domain.user.repository.UserRepository;
import com.example.comma.global.config.auth.jwt.JwtProvider;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.env.Environment;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;

import java.util.Map;

@Service
@Transactional
Expand All @@ -26,9 +26,6 @@ public class OauthService {

private final Environment env;
private final UserRepository userRepository;
private final JwtProvider jwtProvider;

private final RestTemplate restTemplate = new RestTemplate();

@Value("${spring.security.oauth2.client.registration.google.client-id}")
private String clientId;
Expand All @@ -39,47 +36,73 @@ public class OauthService {
@Value("${spring.security.oauth2.client.registration.google.redirect-uri}")
private String redirectUri;

private final RestTemplate restTemplate = new RestTemplate();

public Long socialLogin(String code, String registrationId) {
String accessToken = getOauthToken(code, registrationId);
JsonNode userResourceNode = getUserResource(accessToken, registrationId);
String accessToken = getOauthToken(code);
JsonNode userResourceNode = getUserResource(accessToken);
String socialId = userResourceNode.get("id").asText();
String email = userResourceNode.get("email").asText();
String nickname = userResourceNode.get("name").asText();
String profileImage = userResourceNode.get("picture").asText();
System.out.println("Social ID: " + socialId);
System.out.println("Email: " + email);
System.out.println("Nickname: " + nickname);
System.out.println("Profile Image: " + profileImage);

UserInfoResponseDto user = saveMember(socialId, nickname, email, profileImage);
Long userId = user.id();
return userId;

}

public String getOauthToken(String authorizationCode, String registrationId) {
String tokenUri = env.getProperty("oauth2." + registrationId + ".token-uri");

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("code", authorizationCode);
params.add("client_id", clientId);
params.add("client_secret", clientSecret);
params.add("redirect_uri", redirectUri);
params.add("grant_type", "authorization_code");
public String getOauthToken(String code) {
String tokenUri = "https://oauth2.googleapis.com/token";

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

HttpEntity entity = new HttpEntity(params, headers);

ResponseEntity<JsonNode> responseNode = restTemplate.exchange(tokenUri, HttpMethod.POST, entity, JsonNode.class);
JsonNode accessTokenNode = responseNode.getBody();
String accessToken = accessTokenNode.get("access_token").asText();
return accessToken;
MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
requestBody.add("code", code);
requestBody.add("client_id", clientId);
requestBody.add("client_secret", clientSecret);
requestBody.add("redirect_uri", redirectUri);
requestBody.add("grant_type", "authorization_code");

HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);

ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(tokenUri, HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Map<String, Object>>() {
});
Map<String, Object> responseBody = responseEntity.getBody();
if (responseBody != null && responseBody.containsKey("access_token")) {
return (String) responseBody.get("access_token");
} else {
throw new IllegalStateException("Access token not found in response");
}
}

private JsonNode getUserResource(String accessToken, String registrationId) {
String resourceUri = env.getProperty("oauth2."+registrationId+".resource-uri");
public JsonNode getUserResource(String accessToken) {
String apiUrl = "https://www.googleapis.com/oauth2/v2/userinfo";

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + accessToken);
HttpEntity entity = new HttpEntity(headers);
return restTemplate.exchange(resourceUri, HttpMethod.GET, entity, JsonNode.class).getBody();
HttpEntity<String> entity = new HttpEntity<>(headers);

ResponseEntity<String> responseEntity = restTemplate.exchange(apiUrl, HttpMethod.GET, entity, String.class);
if (responseEntity.getStatusCode() != HttpStatus.OK) {
throw new RuntimeException("Failed to retrieve user resource: " + responseEntity.getStatusCode());
}

ObjectMapper objectMapper = new ObjectMapper();
JsonNode userResourceNode;
try {
userResourceNode = objectMapper.readTree(responseEntity.getBody());
} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to parse user resource response", e);
}

return userResourceNode;
}

public UserInfoResponseDto saveMember(String socialId, String name, String email, String profileImage) {
Expand All @@ -99,6 +122,4 @@ public UserInfoResponseDto saveMember(String socialId, String name, String email

return new UserInfoResponseDto(existMember.getId(), existMember.getSocialId(), existMember.getName(), existMember.getEmail(), existMember.getProfileImage());
}


}
}

0 comments on commit 90dc85f

Please sign in to comment.