Skip to content

Commit

Permalink
fix : 소셜로그인시 유저정보 못가져오는 현상 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
wooni89 committed Oct 25, 2023
1 parent 6ab2896 commit 150943f
Show file tree
Hide file tree
Showing 20 changed files with 122 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public static AccountSearchResponse of(User user ){
return AccountSearchResponse.builder()
.id(user.getId())
.email(user.getEmail())
.thumbnail(user.getThumbnail())
.thumbnail(user.getThumbNail())
.nickName(user.getNickName())
.role(user.getRole())
.status(user.getStatus())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public boolean logout() {

@GetMapping("/oauth/kakao")
public OAuthResponse registerUserForKakao(@RequestParam String code) {
log.info("code >>> {}", code);
return authService.registerUserKakaoCode(code);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ public class AuthResponse {
private final String token;
private final String nickName;
private final String role;
private final String thumbnail;
private final String thumbNail;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package HookKiller.server.auth.dto.response;

import HookKiller.server.user.entity.OauthInfo;
import HookKiller.server.user.entity.OauthProvider;
import HookKiller.server.user.entity.Profile;
import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class KakaoUserInfoDto {

private final String oauthId;

private final String email;
private final String profileImage;
private final String userName;
// oauth 제공자
private final OauthProvider oauthProvider;

public Profile toProfile() {
return Profile.builder()
.thumbNail(this.profileImage)
.nickName(userName)
.email(email)
.build();
}

public OauthInfo toOauthInfo() {
return OauthInfo.builder().oid(oauthId).provider(oauthProvider).build();
}
}
20 changes: 16 additions & 4 deletions src/main/java/HookKiller/server/auth/helper/OauthHelper.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package HookKiller.server.auth.helper;

import HookKiller.server.auth.dto.OIDCUserInfo;
import HookKiller.server.auth.dto.response.KakaoUserInfoDto;
import HookKiller.server.common.dto.OIDCDto;
import HookKiller.server.outer.api.oauth.client.GoogleOauthClient;
import HookKiller.server.outer.api.oauth.client.KakaoInfoClient;
import HookKiller.server.outer.api.oauth.client.KakaoOauthClient;
import HookKiller.server.outer.api.oauth.dto.response.GoogleInfoResponse;
import HookKiller.server.outer.api.oauth.dto.response.GoogleTokenResponse;
import HookKiller.server.outer.api.oauth.dto.response.KakaoTokenResponse;
import HookKiller.server.outer.api.oauth.dto.response.OIDCResponse;
import HookKiller.server.outer.api.oauth.dto.response.*;
import HookKiller.server.properties.GoogleOauthProperties;
import HookKiller.server.properties.KakaoOauthProperties;
import HookKiller.server.user.entity.OauthInfo;
Expand All @@ -23,6 +22,7 @@ public class OauthHelper {

private final KakaoOauthProperties kakaoOauthProperties;
private final KakaoOauthClient kakaoOauthClient;
private final KakaoInfoClient kakaoInfoClient;

private final GoogleOauthProperties googleOauthProperties;
private final GoogleOauthClient googleOauthClient;
Expand Down Expand Up @@ -68,6 +68,18 @@ public OIDCUserInfo getKakaoInfoByIdToken(String idToken) {
.build();
}

public KakaoUserInfoDto getKakaoUserInfo(String oauthAccessToken) {
KakaoInfoResponse response = kakaoInfoClient.kakaoUserInfo("Bearer " + oauthAccessToken);

return KakaoUserInfoDto.builder()
.oauthProvider(OauthProvider.KAKAO)
.userName(response.getNickName())
.profileImage(response.getProfileUrl())
.email(response.getEmail())
.oauthId(response.getId())
.build();
}

public OIDCUserInfo getGoogleInfoById(GoogleInfoResponse googleInfoResponse) {
OauthInfo oauthInfo = OauthInfo.builder()
.provider(OauthProvider.GOOGLE)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public OAuthResponse execute(User user) {
.email(user.getEmail())
.role(user.getRole().getValue())
.nickName(user.getNickName())
.thumbnail(user.getThumbnail())
.thumbnail(user.getThumbNail())
.build();
}
}
16 changes: 9 additions & 7 deletions src/main/java/HookKiller/server/auth/service/AuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import HookKiller.server.auth.dto.OIDCUserInfo;
import HookKiller.server.auth.dto.request.AuthRequest;
import HookKiller.server.auth.dto.response.AuthResponse;
import HookKiller.server.auth.dto.response.KakaoUserInfoDto;
import HookKiller.server.auth.dto.response.OAuthResponse;
import HookKiller.server.auth.exception.PasswordIncorrectException;
import HookKiller.server.auth.exception.StatusNotVerificationException;
Expand Down Expand Up @@ -55,15 +56,16 @@ public ResponseEntity<AuthResponse> loginExecute(AuthRequest request) {
.token(jwtTokenProvider.generateAccessToken(user.getId(), user.getRole().getValue()))
.role(user.getRole().getValue())
.nickName(user.getNickName())
.thumbnail(user.getThumbnail())
.thumbNail(user.getThumbNail())
.build();

return ResponseEntity.ok(res);
}

public OAuthResponse registerUserKakaoCode(String code) {
String idToken = oauthHelper.getOauthTokenKakao(code).getIdToken();
OIDCUserInfo userInfo = oauthHelper.getKakaoInfoByIdToken(idToken);
String accessToken = oauthHelper.getOauthTokenKakao(code).getAccessToken();
log.info("AceessToken >>> {}", accessToken);
KakaoUserInfoDto userInfo = oauthHelper.getKakaoUserInfo(accessToken);

User user =
userRepository.findByEmail(userInfo.getEmail())
Expand All @@ -72,12 +74,12 @@ public OAuthResponse registerUserKakaoCode(String code) {
.orElse(userRepository.save(User.builder()
.email(userInfo.getEmail())
.password(UUID.randomUUID().toString())
.nickName(userInfo.getNickName())
.thumbnail(userInfo.getThumbnailImg())
.nickName(userInfo.getUserName())
.thumbNail(userInfo.getProfileImage())
.loginType(LoginType.KAKAO)
.role(UserRole.USER)
.status(Status.ACTIVE)
.oauthInfo(userInfo.getOauthInfo())
.oauthInfo(userInfo.toOauthInfo())
.build())));


Expand All @@ -96,7 +98,7 @@ public OAuthResponse registerGoogleUser(String code) {
.email(userInfo.getEmail())
.password(UUID.randomUUID().toString())
.nickName(userInfo.getName())
.thumbnail(userInfo.getPicture())
.thumbNail(userInfo.getPicture())
.loginType(LoginType.GOOGLE)
.role(UserRole.USER)
.status(Status.ACTIVE)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public Collection<? extends GrantedAuthority> getAuthorities() {

@Override
public String getPassword() {
return this.userId;
return null;
}

@Override
Expand Down
3 changes: 0 additions & 3 deletions src/main/java/HookKiller/server/common/dto/OIDCDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,4 @@ public class OIDCDto {

private String thumbnailImg;

private String name;

private String picture;
}
1 change: 1 addition & 0 deletions src/main/java/HookKiller/server/common/util/UserUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public class UserUtils {

public static Long getCurrentUserId() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
log.error("들어와요? >>> {}",authentication);
if (authentication == null) {
throw SecurityContextNotFoundException.EXCEPTION;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,14 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
throws ServletException, IOException {
// 토근을 가져옴
String header = request.getHeader(HEADER_STRING);
log.info("header >>> {}", header);
String authToken = null;

// Bearer token인 경우 JWT 토큰 유효성 검사 진행
// AuthenticationManager 역할을 함. -> 토큰이 인증되어있으면 필터로 보내서 context에 저장. 토큰이 인증되어있지 않다면 AuthenticationProvider로 보내어 인증하도록 함.
// token 검증이 되고 인증 정보가 존재하지 않는 경우 spring security 인증 정보 저장
if (header != null && header.startsWith(TOKEN_PREFIX) && !header.equalsIgnoreCase(TOKEN_PREFIX)) {
authToken = header.replace(TOKEN_PREFIX,"");
log.info("AuthToken : {}", authToken);
authToken = header.replace(TOKEN_PREFIX, "");
try {
AccessTokenDetail accessTokenDetail = jwtTokenProvider.parseAccessToken(authToken);

Expand Down
4 changes: 1 addition & 3 deletions src/main/java/HookKiller/server/jwt/JwtOIDCProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,7 @@ public OIDCDto getOIDCTokenBody(String token, String modulus, String exponent) {
body.getSubject(),
body.get("email", String.class),
body.get("nickname", String.class),
body.get("picture", String.class),
body.get("name", String.class),
body.get("thumbnailImg", String.class));
body.get("picture", String.class));
return dto;
}

Expand Down
1 change: 1 addition & 0 deletions src/main/java/HookKiller/server/jwt/JwtTokenProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ public boolean isRefreshToken(String token) {
public AccessTokenDetail parseAccessToken(String token) {
if (isAccessToken(token)) {
Claims claims = getJws(token).getBody();
log.error("claims?>>> {}", claims);
return AccessTokenDetail.builder()
.userId(Long.parseLong(claims.getSubject()))
.role((String) claims.get(TOKEN_ROLE.getValue()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
@RequiredArgsConstructor
public enum StaticVal {

/*
에러코드 관련 변수
*/
BAD_REQUEST(400),
UNAUTHORIZED(401),
FORBIDDEN(403),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ public static class Profile {
private String profileImageUrl;
private boolean isDefaultImage;
}

public String getProfileImageUrl() {
return profile.getProfileImageUrl();
}
}

public String getId() {
Expand All @@ -58,5 +62,9 @@ public String getEmail() {
public String getNickName() {
return kakaoAccount.getProfile().getNickname();
}

public String getProfileUrl() {
return kakaoAccount.getProfileImageUrl();
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public static MyPageUserResponse from(User user) {
return MyPageUserResponse.builder()
.userId(user.getId())
.email(user.getEmail())
.thumbnail(user.getThumbnail())
.thumbnail(user.getThumbNail())
.nickName(user.getNickName())
.createAt(formatTimestamp(user.getCreateAt()))
.build();
Expand Down
27 changes: 27 additions & 0 deletions src/main/java/HookKiller/server/user/entity/Profile.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package HookKiller.server.user.entity;

import jakarta.persistence.Embeddable;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Embeddable
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Profile {

private String nickName;

private String email;

private String thumbNail;

@Builder
public Profile(String nickName, String thumbNail, String email) {
this.email = email;
this.thumbNail = thumbNail;
this.nickName = nickName;
}

}
6 changes: 3 additions & 3 deletions src/main/java/HookKiller/server/user/entity/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public class User extends AbstractTimeStamp {

private String nickName;

private String thumbnail;
private String thumbNail;

@Enumerated(EnumType.STRING)
private UserRole role;
Expand All @@ -57,7 +57,7 @@ public User(
String email,
String password,
String nickName,
String thumbnail,
String thumbNail,
UserRole role,
OauthInfo oauthInfo,
LoginType loginType,
Expand All @@ -66,7 +66,7 @@ public User(
this.email = email;
this.password = SecurityUtils.passwordEncoder.encode(password);
this.nickName = nickName;
this.thumbnail = thumbnail;
this.thumbNail = thumbNail;
this.role = role;
this.status = status;
this.oauthInfo = oauthInfo;
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/HookKiller/server/user/service/MyPageService.java
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,23 @@ public void updateUserInfo(MyPageUserUpdateRequest request) {
@Transactional(propagation = Propagation.REQUIRED)
public CommonBooleanResultResponse updateUserThumbnailPath(MyPageUserUpdateRequest request) {
User user = userUtils.getUser();
<<<<<<< Updated upstream
log.error("request Thumnail >>> {} , userThumnail >>> {}", request.getThumbnail(), user.getThumbnail());
if (request.getThumbnail() == null)
=======
log.error("request Thumnail >>> {} , userThumnail >>> {}", request.getThumbnail(), user.getThumbNail());
if(request.getThumbnail() == null)
>>>>>>> Stashed changes
return CommonBooleanResultResponse.builder().result(false).message("요청 Path가 없습니다.").build();
if (request.getThumbnail().trim().equals(""))
return CommonBooleanResultResponse.builder().result(false).message("요청 Path가 없습니다.").build();
<<<<<<< Updated upstream
if (user.getThumbnail() == null || !request.getThumbnail().equalsIgnoreCase(user.getThumbnail())) {
user.setThumbnail(request.getThumbnail());
=======
if(user.getThumbNail() == null || !request.getThumbnail().equalsIgnoreCase(user.getThumbNail())) {
user.setThumbNail(request.getThumbnail());
>>>>>>> Stashed changes
return CommonBooleanResultResponse.builder().result(true).message("수정이 완료되었습니다.").build();
}
return CommonBooleanResultResponse.builder().result(false).message("동일한 Path라 수정이 불가능합니다.").build();
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/HookKiller/server/user/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public ResponseEntity<User> registerUser(@RequestBody SingUpRequest request) {
if (userRepository.existsByEmail(request.getEmail())) {
throw AlreadyExistUserException.EXCEPTION;
}
User user =User.builder()
User user = User.builder()
.email(request.getEmail())
.password(request.getPassword())
.nickName(request.getNickName())
Expand All @@ -65,8 +65,8 @@ public OAuthResponse registerUserByOIDCToken(String idToken) {
.email(oidcUserInfo.getEmail())
.password(UUID.randomUUID().toString())
.nickName(oidcUserInfo.getNickName())
.thumbnail(oidcUserInfo.getThumbnailImg())
.loginType(LoginType.DEFAULT)
.thumbNail(oidcUserInfo.getThumbnailImg())
.loginType(LoginType.KAKAO)
.role(UserRole.valueOf("USER"))
.oauthInfo(oidcUserInfo.getOauthInfo())
.build()));
Expand Down

0 comments on commit 150943f

Please sign in to comment.