11package wonjun .stiky .auth .config ;
22
3+ import java .util .UUID ;
34import lombok .RequiredArgsConstructor ;
45import org .springframework .security .oauth2 .client .userinfo .DefaultOAuth2UserService ;
56import org .springframework .security .oauth2 .client .userinfo .OAuth2UserRequest ;
67import org .springframework .security .oauth2 .core .OAuth2AuthenticationException ;
78import org .springframework .security .oauth2 .core .user .OAuth2User ;
89import org .springframework .stereotype .Service ;
9- import wonjun . stiky . global . exception . CustomException ;
10+ import org . springframework . transaction . annotation . Transactional ;
1011import wonjun .stiky .member .domain .Member ;
1112import wonjun .stiky .member .service .MemberQueryService ;
1213
@@ -16,6 +17,7 @@ public class CustomOAuth2UserService extends DefaultOAuth2UserService {
1617
1718 private final MemberQueryService memberQueryService ;
1819
20+ @ Transactional
1921 @ Override
2022 public OAuth2User loadUser (OAuth2UserRequest userRequest ) throws OAuth2AuthenticationException {
2123 OAuth2User oAuth2User = super .loadUser (userRequest );
@@ -25,25 +27,33 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic
2527 OAuthAttributes attributes = OAuthAttributes .of (registrationId , userNameAttributeName ,
2628 oAuth2User .getAttributes ());
2729
28- update (attributes );
30+ process (attributes );
2931 return oAuth2User ;
3032 }
3133
32- private void update (OAuthAttributes attributes ) {
33- try {
34- Member foundMember = memberQueryService .fetchByEmail (attributes .getEmail ());
35- foundMember .updateSocialInfo (attributes .getProvider (), attributes .getNameAttributeKey ());
36- memberQueryService .save (foundMember );
37- } catch (CustomException e ) {
38- Member member = Member .builder ()
39- .email (attributes .getEmail ())
40- .nickname (attributes .getName ()) // TODO: 사용자가 온보딩 때 바꿀 수 있도록
41- .role ("ROLE_USER" )
42- .provider (attributes .getProvider ())
43- .providerId (attributes .getNameAttributeKey ())
44- .build ();
45- memberQueryService .save (member );
46- }
34+ private void process (OAuthAttributes attributes ) {
35+ memberQueryService .fetchByEmailOpt (attributes .getEmail ())
36+ .ifPresentOrElse (
37+ member -> {
38+ member .updateSocialInfo (attributes .getProvider (), attributes .getNameAttributeKey ());
39+ memberQueryService .save (member );
40+ },
41+ () -> {
42+ Member member = makeMember (attributes );
43+ memberQueryService .save (member );
44+ }
45+ );
46+ }
47+
48+ private Member makeMember (OAuthAttributes attributes ) {
49+ return Member .builder ()
50+ .email (attributes .getEmail ())
51+ .nickname (attributes .getName ())
52+ .password (UUID .randomUUID ().toString ()) // 더미 패스워드
53+ .role ("ROLE_USER" )
54+ .provider (attributes .getProvider ())
55+ .providerId (attributes .getNameAttributeKey ())
56+ .build ();
4757 }
4858
4959}
0 commit comments