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(OAuth): fix google login #43

Merged
merged 4 commits into from
Jul 24, 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
2 changes: 1 addition & 1 deletion src/main/java/com/mapu/domain/user/domain/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class User extends BaseEntity {

@Email(message = "์ด๋ฉ”์ผ ํ˜•์‹์ด ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์Šต๋‹ˆ๋‹ค.")
@NotNull(message = "์ด๋ฉ”์ผ์€ ํ•„์ˆ˜์ž…๋‹ˆ๋‹ค.")
@Column(nullable = false, unique = true, length = 20)
@Column(nullable = false, unique = true, length = 50)
private String email;

@NotNull(message = "์—ญํ• ์€ ํ•„์ˆ˜์ž…๋‹ˆ๋‹ค.")
Expand Down
75 changes: 32 additions & 43 deletions src/main/java/com/mapu/infra/oauth/application/OAuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,31 +79,18 @@ private OAuthUserInfo getUserInfoFromOAuth(String socialLoginType, String code)

switch (socialLoginType) {
case "GOOGLE": {
try {
userInfo = getGoogleUserInfo(code);
//TODO: null์ผ ๋•Œ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ
} catch (Exception e) {
throw new OAuthException(OAuthExceptionErrorCode.GOOGLE_LOGIN_FAIL);
}finally {
break;
}
userInfo = getGoogleUserInfo(code);
log.info("google user info: {}", userInfo.getEmail());
break;
}
case "KAKAO": {
try {
userInfo = getKakaoUserInfo(code);
//TODO: null์ผ ๋•Œ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ
} catch (Exception e) {
throw new OAuthException(OAuthExceptionErrorCode.KAKAO_LOGIN_FAIL);
} finally {
break;
}
userInfo = getKakaoUserInfo(code);
break;
}
default: {
// ๊ธฐ๋ณธ ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ
throw new OAuthException(OAuthExceptionErrorCode.INVALID_SOCIAL_LOGIN_TYPE);
}
}

return userInfo;
}

Expand All @@ -114,33 +101,35 @@ private void saveUserInfoToSession(HttpSession session, OAuthUserInfo oAuthUserI
log.info("New user info saved in session: {}", session.getAttribute("email"));
}

private OAuthUserInfo getGoogleUserInfo(String code) throws JsonProcessingException {
GoogleToken oAuthToken = googleUserService.getAccessToken(code);
GoogleUserInfo googleUserInfo = googleUserService.requestGoogleUserInfo(oAuthToken);
log.info("googleUser: " + googleUserInfo.email);

OAuthUserInfo oAuthUserInfo = OAuthUserInfo.builder()
.socialId(googleUserInfo.getId())
.socialProvider("google")
.email(googleUserInfo.email)
.build();

return oAuthUserInfo;
private OAuthUserInfo getGoogleUserInfo(String code){
GoogleToken googleToken = googleUserService.getAccessToken(code);
try {
GoogleUserInfo googleUserInfo = googleUserService.requestGoogleUserInfo(googleToken);
log.info("googleUser: " + googleUserInfo.email);
OAuthUserInfo oAuthUserInfo = OAuthUserInfo.builder()
.socialId(googleUserInfo.getId())
.socialProvider("google")
.email(googleUserInfo.email)
.build();
return oAuthUserInfo;
}catch (Exception e){
throw new OAuthException(OAuthExceptionErrorCode.GOOGLE_LOGIN_FAIL);
}
}

private OAuthUserInfo getKakaoUserInfo(String code) {
KakaoToken oAuthToken = kakaoUserService.getAccessToken(code);

KakaoUserInfo kakaoUserInfo = kakaoUserService.requestKakaoUserInfo(oAuthToken.getAccess_token());
//KakaoUserInfo kakaoUserInfo = kakaoUserService.requestKakaoUserInfo(code); // postman test ๋ถ€๋ถ„
log.info("kakaoUser: " + kakaoUserInfo.getKakao_account().getEmail());

OAuthUserInfo oAuthUserInfo = OAuthUserInfo.builder()
.socialId(kakaoUserInfo.getId())
.socialProvider("kakao")
.email(kakaoUserInfo.getKakao_account().email)
.build();

return oAuthUserInfo;
KakaoToken kakaoToken = kakaoUserService.getAccessToken(code);
try {
KakaoUserInfo kakaoUserInfo = kakaoUserService.requestKakaoUserInfo(kakaoToken);
log.info("kakaoUser: " + kakaoUserInfo.getKakao_account().getEmail());
OAuthUserInfo oAuthUserInfo = OAuthUserInfo.builder()
.socialId(kakaoUserInfo.getId())
.socialProvider("kakao")
.email(kakaoUserInfo.getKakao_account().email)
.build();
return oAuthUserInfo;
}catch (Exception e){
throw new OAuthException(OAuthExceptionErrorCode.KAKAO_LOGIN_FAIL);
}
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/mapu/infra/oauth/domain/OAuth.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class OAuth extends BaseEntity {
private String platformName;

@NotNull
@Column(nullable = false, length = 20)
@Column(nullable = false, length = 50)
private String platformId;

@OneToOne(fetch = FetchType.LAZY)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ public enum OAuthExceptionErrorCode implements ResponseStatus {
NEED_TO_SIGNUP(5000, HttpStatus.OK.value(), "ํšŒ์›๊ฐ€์ž…์ด ํ•„์š”ํ•œ ์œ ์ €์ž…๋‹ˆ๋‹ค."),
GOOGLE_LOGIN_FAIL(5001,HttpStatus.BAD_REQUEST.value(),"GOOGLE ์†Œ์…œ ๋กœ๊ทธ์ธ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค."),
KAKAO_LOGIN_FAIL(5002,HttpStatus.BAD_REQUEST.value(),"KAKAO ์†Œ์…œ ๋กœ๊ทธ์ธ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค."),
INVALID_SOCIAL_LOGIN_TYPE(5003, HttpStatus.BAD_REQUEST.value(),"์œ ํšจํ•˜์ง€ ์•Š์€ ์†Œ์…œ๋กœ๊ทธ์ธ ์œ ํ˜•์ž…๋‹ˆ๋‹ค.");
INVALID_SOCIAL_LOGIN_TYPE(5003, HttpStatus.BAD_REQUEST.value(),"์œ ํšจํ•˜์ง€ ์•Š์€ ์†Œ์…œ๋กœ๊ทธ์ธ ์œ ํ˜•์ž…๋‹ˆ๋‹ค."),
GET_TOKEN_FAIL(5004, HttpStatus.BAD_REQUEST.value(), "SOCIAL TOKEN์ด ์ œ๋Œ€๋กœ ์ƒ์„ฑ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค");

private final int code;
private final int status;
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/com/mapu/infra/oauth/google/GoogleUserInfo.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
package com.mapu.infra.oauth.google;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
public class GoogleUserInfo {
public String id;
public String email;

@JsonProperty("verified_email")
public Boolean verifiedEmail;

public String name;

@JsonProperty("given_name")
public String givenName;

@JsonProperty("family_name")
public String familyName;

public String picture;
public String locale;
}

50 changes: 41 additions & 9 deletions src/main/java/com/mapu/infra/oauth/google/GoogleUserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,64 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mapu.infra.oauth.config.OAuthClientConfig;
import com.mapu.infra.oauth.exception.OAuthException;
import com.mapu.infra.oauth.exception.errorcode.OAuthExceptionErrorCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class GoogleUserService {

private final OAuthClientConfig oAuthClientConfig;
private final ObjectMapper objectMapper;

private final String accessTokenUri = "https://oauth2.googleapis.com/token";
private final String UserInfoUri = "https://www.googleapis.com/oauth2/v1/userinfo";


public GoogleToken getAccessToken(String code) throws JsonProcessingException {
GoogleToken googleToken = objectMapper.readValue(code, GoogleToken.class);
public GoogleToken getAccessToken(String code) {
//์š”์ฒญ param (body)
MultiValueMap<String , String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "authorization_code");
params.add("client_id", oAuthClientConfig.getGoogleClientId());
params.add("redirect_uri", oAuthClientConfig.getGoogleRedirectUri());
params.add("code", code);
params.add("client_secret", oAuthClientConfig.getGoogleClientSecret());


//request
WebClient wc = WebClient.create(accessTokenUri);
String response = wc.post()
.uri(accessTokenUri)
.body(BodyInserters.fromFormData(params))
.header("Content-type","application/x-www-form-urlencoded;charset=utf-8" ) //์š”์ฒญ ํ—ค๋”
.retrieve()
.bodyToMono(String.class)
.block();
//jsonํ˜•ํƒœ๋กœ ๋ณ€ํ™˜
ObjectMapper objectMapper = new ObjectMapper();
GoogleToken googleToken =null;

try {
googleToken = objectMapper.readValue(response, GoogleToken.class);
} catch (JsonProcessingException e) {
throw new OAuthException(OAuthExceptionErrorCode.GET_TOKEN_FAIL);
}
log.info("Google Token: {}", googleToken.getAccess_token());
return googleToken;
}

public GoogleUserInfo requestGoogleUserInfo(GoogleToken googleToken) {
public GoogleUserInfo requestGoogleUserInfo(GoogleToken googleToken) throws JsonProcessingException {
//Http ์š”์ฒญ
log.info("requestGoogleUserInfo");
WebClient wc = WebClient.create(UserInfoUri);
String response = wc.get()
.uri(UserInfoUri)
Expand All @@ -39,11 +74,8 @@ public GoogleUserInfo requestGoogleUserInfo(GoogleToken googleToken) {
ObjectMapper objectMapper = new ObjectMapper();
GoogleUserInfo googleUserInfo = null;

try {
googleUserInfo = objectMapper.readValue(response, GoogleUserInfo.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
log.info("response: {}", response);
googleUserInfo = objectMapper.readValue(response, GoogleUserInfo.class);
return googleUserInfo;
}
}
41 changes: 6 additions & 35 deletions src/main/java/com/mapu/infra/oauth/kakao/KakaoUserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mapu.infra.oauth.config.OAuthClientConfig;
import com.mapu.infra.oauth.exception.OAuthException;
import com.mapu.infra.oauth.exception.errorcode.OAuthExceptionErrorCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -49,19 +51,18 @@ public KakaoToken getAccessToken(String code) {
try {
kakaoToken = objectMapper.readValue(response, KakaoToken.class);
} catch (JsonProcessingException e) {
log.error("json processing error", e);
e.printStackTrace();
throw new OAuthException(OAuthExceptionErrorCode.GET_TOKEN_FAIL);
}

return kakaoToken;
}
public KakaoUserInfo requestKakaoUserInfo(String token) {
public KakaoUserInfo requestKakaoUserInfo(KakaoToken kakaoToken) throws JsonProcessingException {

//Http ์š”์ฒญ
WebClient wc = WebClient.create(UserInfoUri);
String response = wc.post()
.uri(UserInfoUri)
.header("Authorization", "Bearer " + token)
.header("Authorization", "Bearer " + kakaoToken.getAccess_token())
.header("Content-type", "application/x-www-form-urlencoded;charset=utf-8")
.retrieve()
.bodyToMono(String.class)
Expand All @@ -70,37 +71,7 @@ public KakaoUserInfo requestKakaoUserInfo(String token) {
ObjectMapper objectMapper = new ObjectMapper();
KakaoUserInfo kakaoUserInfo = null;

try {
kakaoUserInfo = objectMapper.readValue(response, KakaoUserInfo.class);
} catch (JsonProcessingException e) {
log.error("json processing error", e);
e.printStackTrace();
}
kakaoUserInfo = objectMapper.readValue(response, KakaoUserInfo.class);
return kakaoUserInfo;
}

// ์†Œ์€์ด๊ฐ€ ํ•˜๋Š” ๋ถ€๋ถ„
// @Transactional
// public User saveUser(String access_token) {
// KakaoUserInfo kakaoUserInfo = findKakaoUser(access_token); //์‚ฌ์šฉ์ž ์ •๋ณด ๋ฐ›์•„์˜ค๊ธฐ
// User user = userRepository.findByUserid(kakaoUserInfo.getId());
//
// //์ฒ˜์Œ์ด์šฉ์ž ๊ฐ•์ œ ํšŒ์›๊ฐ€์ž…
// if(user ==null) {
// user = User.builder()
// .userid(kakaoUserInfo.getId())
// .password(null) //ํ•„์š”์—†์œผ๋‹ˆ ์ผ๋‹จ ์•„๋ฌด๊ฑฐ๋„ ์•ˆ๋„ฃ์Œ. ์›ํ•˜๋Š”๋ฐ๋กœ ๋„ฃ์œผ๋ฉด ๋Œ
// .nickname(kakaoUserInfo.getKakao_account().getProfile().getNickname())
// .profileImg(kakaoUserInfo.getKakao_account().getProfile().getProfile_image_url())
// .email(kakaoUserInfo.getKakao_account().getEmail())
// .roles("USER")
// .createTime(LocalDateTime.now())
// .provider("Kakao")
// .build();
//
// userRepository.save(user);
// }
//
// return user;
// }
}
4 changes: 2 additions & 2 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ spring:
jwt:
secret: ${JWT_SECRET}
token:
access-expiration-time: 600 #10min
access-expiration-time: 3600 #1hour
refresh-expiration-time: 86400 #24hour

---
Expand All @@ -21,7 +21,7 @@ spring:
client-id: ${GOOGLE_CLIENT_ID}
client-secret: ${GOOGLE_CLIENT_SECRET}
scope: email
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
redirect-uri: "http://localhost:3000/google/callback"
authorization-grant-type: authorization_code
client-name: Google
kakao:
Expand Down
Loading