Skip to content

Commit 46d131a

Browse files
authored
Merge pull request #105 from wafflestudio/feat/socialLogin
소셜로그인 재수정
2 parents ef760b0 + bce0e49 commit 46d131a

6 files changed

Lines changed: 76 additions & 64 deletions

File tree

.idea/hangsha-server.iml

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/modules.xml

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

hangsha/src/main/kotlin/com/team1/hangsha/config/SecurityConfig.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,12 @@ class SecurityConfig(
7373
.anyRequest().authenticated()
7474
}
7575
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter::class.java)
76-
/*
76+
7777
.oauth2Login { oauth2 ->
7878
oauth2.userInfoEndpoint { it.userService(customOAuth2UserService) } // 유저 정보 처리 로직
7979
oauth2.successHandler(oAuth2SuccessHandler)
8080
}
81-
*/
81+
8282
return http.build()
8383
}
8484
}

hangsha/src/main/kotlin/com/team1/hangsha/user/handler/OAuth2SuccessHandler.kt

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ class OAuth2SuccessHandler(
2525
private val tokenHasher: TokenHasher,
2626
private val cookieSupport: AuthCookieSupport,
2727
@Value("\${jwt.refresh-expiration-ms}") private val refreshExpirationMs: Long,
28+
@Value("\${app.oauth2.front-redirect-uri}") private val frontRedirectUri: String,
2829
) : SimpleUrlAuthenticationSuccessHandler() {
2930

3031
override fun onAuthenticationSuccess(
@@ -33,8 +34,8 @@ class OAuth2SuccessHandler(
3334
authentication: Authentication
3435
) {
3536
val oAuth2User = authentication.principal as OAuth2User
36-
val email = oAuth2User.attributes["email"] as String
37-
37+
val email = oAuth2User.name
38+
val isNewUser = oAuth2User.attributes["isNewUser"] as? Boolean ?: false
3839
val user = userRepository.findByEmail(email)
3940
?: throw RuntimeException("User not found after OAuth2 login")
4041

@@ -48,10 +49,9 @@ class OAuth2SuccessHandler(
4849
)
4950
response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString())
5051

51-
// 프론트엔드 주소로 변경(http://localhost:3000/oauth/callback)
52-
val targetUrl = UriComponentsBuilder.fromUriString("http://localhost:8080/")
52+
val targetUrl = UriComponentsBuilder.fromUriString(frontRedirectUri)
5353
.queryParam("accessToken", accessToken)
54-
// .queryParam("refreshToken", refreshToken) // 필요시 주석 해제
54+
.queryParam("isNewUser", isNewUser)
5555
.build().toUriString()
5656

5757
redirectStrategy.sendRedirect(request, response, targetUrl)

hangsha/src/main/kotlin/com/team1/hangsha/user/service/CustomOAuth2UserService.kt

Lines changed: 42 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest
1010
import org.springframework.security.oauth2.core.user.OAuth2User
1111
import org.springframework.stereotype.Service
1212
import org.springframework.transaction.annotation.Transactional
13+
import org.springframework.security.oauth2.core.user.DefaultOAuth2User
1314

1415
@Service
1516
class CustomOAuth2UserService(
@@ -33,48 +34,54 @@ class CustomOAuth2UserService(
3334

3435
val authProvider = AuthProvider.valueOf(registrationId.uppercase())
3536

36-
// --- (이하 저장 로직은 기존과 동일) ---
37-
38-
// 3. 이미 연동된 계정인지 확인
37+
var isNewUser = false
3938
val existingIdentity = userIdentityRepository.findByProviderAndProviderUserId(authProvider, providerId)
40-
if (existingIdentity != null) {
41-
return oAuth2User
42-
}
43-
44-
// 4. 이메일로 기존 유저 확인 (계정 연동)
45-
val existingUser = userRepository.findByEmail(email)
39+
if (existingIdentity == null) {
40+
val existingUser = userRepository.findByEmail(email)
41+
42+
if (existingUser != null) {
43+
userIdentityRepository.save(
44+
UserIdentity(
45+
userId = existingUser.id!!,
46+
provider = authProvider,
47+
providerUserId = providerId,
48+
email = email
49+
)
50+
)
51+
} else {
52+
isNewUser = true
53+
val savedUser = userRepository.save(
54+
User(
55+
email = email,
56+
username = name,
57+
profileImageUrl = picture
58+
)
59+
)
4660

47-
if (existingUser != null) {
48-
userIdentityRepository.save(
49-
UserIdentity(
50-
userId = existingUser.id!!,
51-
provider = authProvider,
52-
providerUserId = providerId,
53-
email = email
61+
userIdentityRepository.save(
62+
UserIdentity(
63+
userId = savedUser.id!!,
64+
provider = authProvider,
65+
providerUserId = providerId,
66+
email = email
67+
)
5468
)
55-
)
56-
} else {
57-
val savedUser = userRepository.save(
58-
User(
59-
email = email,
60-
username = name,
61-
profileImageUrl = picture
62-
)
63-
)
69+
}
70+
}
6471

65-
userIdentityRepository.save(
66-
UserIdentity(
67-
userId = savedUser.id!!,
68-
provider = authProvider,
69-
providerUserId = providerId,
70-
email = email
71-
)
72+
// 3. attributes에 "email"과 "isNewUser" 정보 추가
73+
val customAttributes = oAuth2User.attributes.toMutableMap()
74+
customAttributes["email"] = email
75+
customAttributes["isNewUser"] = isNewUser
76+
77+
// 4. 무조건 여기서 묶어서 반환 (조기 반환 버그 해결!)
78+
return DefaultOAuth2User(
79+
oAuth2User.authorities,
80+
customAttributes,
81+
"email" // 식별자 키
7282
)
7383
}
7484

75-
return oAuth2User
76-
}
77-
7885
// 소셜별로 데이터를 꺼내는 도우미 함수
7986
private fun extractAttributes(registrationId: String, attributes: Map<String, Any>): OAuthAttributes {
8087
return when (registrationId) {

hangsha/src/main/resources/application.yml

Lines changed: 10 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -102,13 +102,10 @@ spring:
102102
config:
103103
activate:
104104
on-profile: local
105-
oauth2:
106-
google: # TODO: 로컬 개발 환경에서 클라이언트 쪽으로의 리다이렉션. 우선 임의로 설정. 확인 필요
107-
redirect-uri: "http://localhost:3000/login/callback/google"
108-
naver:
109-
redirect-uri: "http://localhost:3000/login/callback/naver"
110-
kakao:
111-
redirect-uri: "http://localhost:3000/login/callback/kakao"
105+
app:
106+
oauth2:
107+
front-redirect-uri: "http://localhost:3000/auth/callback"
108+
112109

113110
---
114111
# ==========================================
@@ -118,14 +115,9 @@ spring:
118115
config:
119116
activate:
120117
on-profile: dev
121-
oauth2:
122-
google: # TODO : 추후 확인 필요. 정말로 이 리다이렉트 URI가 맞는가?
123-
redirect-uri: "https://hangsha-dev.wafflestudio.com/login/callback/google"
124-
naver:
125-
redirect-uri: "https://hangsha-dev.wafflestudio.com/login/callback/naver"
126-
kakao:
127-
redirect-uri: "https://hangsha-dev.wafflestudio.com/login/callback/kakao"
128-
118+
app:
119+
oauth2:
120+
front-redirect-uri: "https://hangsha-dev.wafflestudio.com/auth/callback"
129121
---
130122
# ==========================================
131123
# prod
@@ -134,10 +126,6 @@ spring:
134126
config:
135127
activate:
136128
on-profile: prod
137-
oauth2:
138-
google:
139-
redirect-uri: "https://hangsha.wafflestudio.com/login/callback/google"
140-
naver:
141-
redirect-uri: "https://hangsha.wafflestudio.com/login/callback/naver"
142-
kakao:
143-
redirect-uri: "https://hangsha.wafflestudio.com/login/callback/kakao"
129+
app:
130+
oauth2:
131+
front-redirect-uri: "https://hangsha.wafflestudio.com/auth/callback"

0 commit comments

Comments
 (0)