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

구글 로그인 추가 #60

Merged
merged 2 commits into from
Jan 21, 2025
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package com.wafflestudio.toyproject.memoWithTags.user

import com.wafflestudio.toyproject.memoWithTags.exception.OAuthRequestException
import com.wafflestudio.toyproject.memoWithTags.user.dto.GoogleOAuthToken
import com.wafflestudio.toyproject.memoWithTags.user.dto.GoogleProfile
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.MediaType
import org.springframework.stereotype.Component
import org.springframework.util.MultiValueMap
import org.springframework.web.client.RestTemplate

@Component
class GoogleUtil(
@Value("\${google.auth.client-id}")
private val googleClientId: String,
@Value("\${google.auth.client-secret}")
private val googleClientSecret: String,
@Value("\${google.auth.redirect}")
private val googleRedirectUri: String
) {
private val logger = LoggerFactory.getLogger(GoogleUtil::class.java)

fun requestToken(accessCode: String): GoogleOAuthToken {
val restTemplate = RestTemplate()
val headers = HttpHeaders()
headers.contentType = MediaType.APPLICATION_JSON

val params = mapOf(
"grant_type" to "authorization_code",
"client_id" to googleClientId,
"client_secret" to googleClientSecret,
"redirect_uri" to googleRedirectUri,
"code" to accessCode
)

val googleTokenRequest = HttpEntity(params, headers)
logger.info("Token Request: $googleTokenRequest")

val response = restTemplate.exchange(
"https://oauth2.googleapis.com/token",
HttpMethod.POST,
googleTokenRequest,
GoogleOAuthToken::class.java
)
logger.info("Token Response: $response")

return try {
val oAuthToken = response.body!!
logger.info("oAuthToken: ${oAuthToken.access_token}")
oAuthToken
} catch (e: NullPointerException) {
logger.info("Token processing error: ${e.message}")
throw OAuthRequestException()
}
}

fun requestProfile(oAuthToken: GoogleOAuthToken): GoogleProfile {
val restTemplate = RestTemplate()
val headers = HttpHeaders()
headers.setBearerAuth(oAuthToken.access_token)
headers.contentType = MediaType.APPLICATION_JSON

val kakaoProfileRequest: HttpEntity<MultiValueMap<String, String>> = HttpEntity(headers)
logger.info("Profile Request: $kakaoProfileRequest")

val response = restTemplate.exchange(
"https://www.googleapis.com/userinfo/v2/me",
HttpMethod.GET,
kakaoProfileRequest,
GoogleProfile::class.java
)
logger.info("Profile Response: $response")

return try {
val googleProfile = response.body!!
logger.info("google email: ${googleProfile.email}")
googleProfile
} catch (e: NullPointerException) {
logger.info("Profile processing error: ${e.message}")
throw OAuthRequestException()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ class SocialLoginController(
}

@GetMapping("/oauth/google")
fun googleCallback() {
fun googleCallback(
@RequestParam("code") code: String
): ResponseEntity<LoginResponse> {
val (_, accessToken, refreshToken) = socialLoginService.googleCallback(code)
return ResponseEntity.ok(LoginResponse(accessToken, refreshToken))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.wafflestudio.toyproject.memoWithTags.user.dto

data class GoogleOAuthToken(
val access_token: String,
val expires_in: Int,
val scope: String,
val token_type: String,
val id_token: String
)

data class GoogleProfile(
val id: String,
val email: String,
val verified_email: Boolean,
val name: String,
val given_name: String,
val family_name: String,
val picture: String?,
val locale: String?
)
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package com.wafflestudio.toyproject.memoWithTags.user.service

import com.wafflestudio.toyproject.memoWithTags.user.GoogleUtil
import com.wafflestudio.toyproject.memoWithTags.user.JwtUtil
import com.wafflestudio.toyproject.memoWithTags.user.KakaoUtil
import com.wafflestudio.toyproject.memoWithTags.user.NaverUtil
import com.wafflestudio.toyproject.memoWithTags.user.SocialType
import com.wafflestudio.toyproject.memoWithTags.user.controller.User
import com.wafflestudio.toyproject.memoWithTags.user.dto.GoogleOAuthToken
import com.wafflestudio.toyproject.memoWithTags.user.dto.GoogleProfile
import com.wafflestudio.toyproject.memoWithTags.user.dto.KakaoOAuthToken
import com.wafflestudio.toyproject.memoWithTags.user.dto.KakaoProfile
import com.wafflestudio.toyproject.memoWithTags.user.dto.NaverOAuthToken
Expand All @@ -19,7 +22,8 @@ import java.time.Instant
class SocialLoginService(
private val userRepository: UserRepository,
private val kakaoUtil: KakaoUtil,
private val naverUtil: NaverUtil
private val naverUtil: NaverUtil,
private val googleUtil: GoogleUtil
) {
private val logger = LoggerFactory.getLogger(javaClass)

Expand Down Expand Up @@ -102,4 +106,44 @@ class SocialLoginService(

return User.fromEntity(userEntity)
}

fun googleCallback(accessCode: String): Triple<User, String, String> {
val oAuthToken: GoogleOAuthToken = googleUtil.requestToken(accessCode)
val googleProfile: GoogleProfile = googleUtil.requestProfile(oAuthToken)

val googleEmail = googleProfile.email
val userEntity = userRepository.findByEmail(googleEmail)
val user: User = if (userEntity != null && userEntity.socialType == SocialType.GOOGLE) {
logger.info("google user already exists: ${userEntity.id}, ${userEntity.email}")
User.fromEntity(userEntity)
} else {
logger.info("creating google user $googleEmail")
createGoogleUser(googleProfile)
}

return Triple(
user,
JwtUtil.generateAccessToken(googleEmail),
JwtUtil.generateRefreshToken(googleEmail)
)
}

fun createGoogleUser(profile: GoogleProfile): User {
val googleEmail = profile.email
val googleNickname = profile.name
val encryptedPassword = "google_registered_user"

val userEntity = userRepository.save(
UserEntity(
email = googleEmail,
nickname = googleNickname,
hashedPassword = encryptedPassword,
verified = true,
socialType = SocialType.GOOGLE,
createdAt = Instant.now()
)
)

return User.fromEntity(userEntity)
}
}
6 changes: 6 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ naver:
client-id: ${NAVER_CLIENT_ID}
client-secret: ${NAVER_CLIENT_SECRET}

google:
auth:
client-id: ${GOOGLE_CLIENT_ID}
client-secret: ${GOOGLE_CLIENT_SECRET}
redirect: ${GOOGLE_REDIRECT_URI}

springdoc:
override-with-generic-response: false
# 이후 jwt도 yml에 넣어서 관리 예정
Loading