Skip to content

Commit

Permalink
optimize: 유저레벨 커버링 인덱스 구현 (id, email, role) (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
in-seo authored Jan 2, 2024
2 parents ea739fd + a71e1bd commit 2f36eb1
Show file tree
Hide file tree
Showing 7 changed files with 29 additions and 59 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic
// OAuth2UserService
OAuthAttributes attributes = OAuthAttributes.of(registrationId, userNameAttributeName, oAuth2User.getAttributes());
User user = saveOrUpdate(attributes);
httpSession.setAttribute("user", new SessionUser(user)); // SessionUser (직렬화된 dto 클래스 사용)
httpSession.setAttribute("user", new SessionUser(user)); // SessionUser (직렬화된 dto 클래스 사용하되, 커버링 인덱스를 사용하기 위해 id, email만 이용한다.)

return new DefaultOAuth2User(Collections.singleton(new SimpleGrantedAuthority(user.getRoleKey())),
attributes.getAttributes(),
Expand All @@ -44,10 +44,7 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic

// 유저 생성 및 수정 서비스 로직
private User saveOrUpdate(OAuthAttributes attributes){
// User user = userRepository.findByEmail(attributes.getEmail())
// .map(entity -> entity.update(attributes.getName(), attributes.getPicture()))
// .orElse(attributes.toEntity());
Optional<User> optionalUser = userRepository.findByEmail(attributes.getEmail());
Optional<User> optionalUser = userRepository.findByEmailWithIndex(attributes.getEmail()); // id, email, role만 가져오는 커버링 인덱스!
if(optionalUser.isPresent())
return optionalUser.get();
return userRepository.save(optionalUser.map(entity -> entity.update(attributes.getName(), attributes.getPicture())).orElse(attributes.toEntity()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,30 +26,18 @@ public OAuthAttributes(Map<String, Object> attributes, String nameAttributeKey,
this.nameAttributeKey = nameAttributeKey;
this.name = name;
this.email = email;
if(origin.equals("Facebook"))
this.picture = "https://graph.facebook.com/"+picture+"/picture?type=large&width=720&height=720";
else
this.picture = picture;
this.picture = picture;
this.origin = origin;
}

public static OAuthAttributes of(String registrationId, String userNameAttributeName, Map<String, Object> attributes){
// 여기서 네이버와 카카오 등 구분 (ofNaver, ofKakao)
if("naver".equals(registrationId)) return ofNaver("id",attributes);
else if("kakao".equals(registrationId)) return ofKakao("id", attributes);
else if("facebook".equals(registrationId)) return ofFaceBook(userNameAttributeName,attributes);
// else if("facebook".equals(registrationId)) return ofFaceBook(userNameAttributeName,attributes);
return ofGoogle(userNameAttributeName, attributes);
}
private static OAuthAttributes ofFaceBook(String userNameAttributeName, Map<String, Object> attributes){
return OAuthAttributes.builder()
.name((String) attributes.get("name"))
.email((String) attributes.get("email"))
.picture((String) attributes.get("id"))
.origin("Facebook")
.attributes(attributes)
.nameAttributeKey(userNameAttributeName)
.build();
}

private static OAuthAttributes ofKakao(String userNameAttributeName, Map<String, Object> attributes){
Map<String, Object> kakao_account = (Map<String, Object>) attributes.get("kakao_account");
Map<String, Object> profile = (Map<String, Object>) kakao_account.get("profile");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package Matching.SouP.config.auth.dto;

import Matching.SouP.common.error.UserNotFoundException;
import Matching.SouP.domain.user.User;
import Matching.SouP.repository.UserRepository;
import lombok.RequiredArgsConstructor;
Expand All @@ -12,26 +13,25 @@
@Service //Bean 등록
@RequiredArgsConstructor
@Transactional
public class PrincipalDetailService implements UserDetailsService {
public class PrincipalDetailService implements UserDetailsService {

private final UserRepository userRepository;
private final UserRepository userRepository;

/**스프링이 로그인 요청을 가로챌 때, username, passwrod 변수 2개를 가로채는데
password 부분처리는 알아서 함.
username (email) 이 DB 에 있는지만 확인해주면 됨. return
/**
* 스프링이 로그인 요청을 가로챌 때, username, passwrod 변수 2개를 가로채는데
* password 부분처리는 알아서 함.
* username (email) 이 DB 에 있는지만 확인해주면 됨. return
*/
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User principal = userRepository.findByEmailWithIndex(email)
.orElseThrow(UserNotFoundException::new);

User principal=userRepository.findByEmail(email).get();
if(principal==null){
throw new UsernameNotFoundException(email);
}
UserDetails result= org.springframework.security.core.userdetails.User.builder()
.username(principal.getEmail())
.password(principal.getPicture())
.roles(principal.getRole().toString())
.build();
UserDetails result = org.springframework.security.core.userdetails.User.builder()
.username(principal.getEmail())
.password(String.valueOf(principal.getId()))
.roles(principal.getRoleKey())
.build();

return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@

@Getter
public class SessionUser implements Serializable {
private String name;
private Long id;
private String email;
private String picture;
private String role;

public SessionUser(User user){
this.name = user.getName();
this.id = user.getId();
this.email = user.getEmail();
this.picture = user.getPicture();
this.role = user.getRoleKey();
}
}
11 changes: 0 additions & 11 deletions SouP/src/main/java/Matching/SouP/domain/user/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,4 @@ public void changeName(String name) {
this.nickName = name;
}

// public User updateProfile(UserForm userForm){
// if(!userForm.getEmail().isEmpty())
// this.role=Role.USER; //정식 승인
// this.email = userForm.getEmail();
// this.nickName = userForm.getNickName();
// this.stack = userForm.getStack();
// this.favor = userForm.getFavor();
// this.portfolio=userForm.getPortfolio();
// return this;
// }

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@
import java.util.Optional;

public interface UserRepository extends JpaRepository<User,Long> {

Optional<User> findByEmail(@Param("email")String email);

@Query("select u.id, u.email, u.role from User u where u.email = :email")
Optional<User> findByEmailWithIndex(@Param("email")String email);

@Query("select u from User u left join fetch u.postList where u.email = :email")
Optional<User> findByEmailFetchPL(@Param("email")String email);

Expand Down
12 changes: 2 additions & 10 deletions SouP/src/main/java/Matching/SouP/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,27 +47,19 @@ public User getUserWithLoungeFav(String email) {
.orElseThrow(UserNotFoundException::new);
}


@Transactional(readOnly = true)
public JSONObject makeUserDto(String email) {
Optional<User> optionalUser = getOptionalUser(email);
if (optionalUser.isPresent())
return addDetails(optionalUser.get());

return SoupResponse.fail();
User user = getUser(email);
return addDetails(user);
}


public JSONObject changeNickName(String email, String nickName) {
User user = userRepository.findByEmail(email)
.orElseThrow(UserNotFoundException::new);
user.changeName(nickName);
return SoupResponse.success();
}

private Optional<User> getOptionalUser(String email) {
return userRepository.findByEmail(email);
}

public User getUser(String email) {
return userRepository.findByEmail(email).orElseThrow(UserNotFoundException::new);
Expand Down

0 comments on commit 2f36eb1

Please sign in to comment.