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

[Feat] 카카오 소셜로그인 기능추가 #12

Merged
merged 3 commits into from
Oct 21, 2023
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
3 changes: 3 additions & 0 deletions app/.idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions app/.idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions app/.idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions app/.idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ android {
buildConfigField("String", "BASE_URL", getBaseUrl("BASE_URL"))
buildConfigField("String", "NAVER_CLIENT_ID", getBaseUrl("NAVER_CLIENT_ID"))
buildConfigField("String", "NAVER_CLIENT_SECRET", getBaseUrl("NAVER_CLIENT_SECRET"))
buildConfigField("String", "KAKAO_NATIVE_APP_KEY", "\"${getBaseUrl("KAKAO_NATIVE_APP_KEY")}\"")
manifestPlaceholders["kakaoKey"] = "kakao${getBaseUrl("KAKAO_NATIVE_APP_KEY")}"
}

buildTypes {
Expand Down
14 changes: 14 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,20 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<activity
android:name="com.kakao.sdk.auth.AuthCodeHandlerActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />

<data android:host="oauth"
android:scheme="${kakaoKey}" />
</intent-filter>
</activity>

<activity
android:name=".presentation.view.MainActivity"
android:exported="true">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ interface ApiService {
@Body body: TokenRequestBody
): ApiResult<LoginTokenResponse>

//카카오 로그인
@POST("/token/kakao")
suspend fun userKakaoLogin(
@Body body: TokenRequestBody
): ApiResult<LoginTokenResponse>

// 로그인 테스트
@GET("/api/logintest")
suspend fun apiLoginTest(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ class LoginRepositoryImpl @Inject constructor(
return service.userNaverLogin(naverLoginBody)
}

override suspend fun userKakaoLogin(kakaoLoginBody: TokenRequestBody): ApiResult<LoginTokenResponse>{
return service.userKakaoLogin(kakaoLoginBody)
}

override suspend fun testLogin(token: String): ApiResult<LoginTestResponse> {
return service.apiLoginTest(token)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ import com.example.numberoneproject.data.network.ApiResult
interface LoginRepository {
suspend fun refreshAccessToken(body: TokenRequestBody): ApiResult<LoginTokenResponse>
suspend fun userNaverLogin(naverLoginBody: TokenRequestBody): ApiResult<LoginTokenResponse>
suspend fun userKakaoLogin(kakaoLoginBody: TokenRequestBody) : ApiResult<LoginTokenResponse>
suspend fun testLogin(token: String) : ApiResult<LoginTestResponse>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.example.numberoneproject.domain.usecase

import com.example.numberoneproject.data.model.LoginTokenResponse
import com.example.numberoneproject.data.model.TokenRequestBody
import com.example.numberoneproject.data.network.ApiResult
import com.example.numberoneproject.domain.repository.LoginRepository
import javax.inject.Inject
class KakaoLoginUsecase @Inject constructor(
private val loginRepository: LoginRepository
) {
suspend operator fun invoke(
loginBody: TokenRequestBody
) : ApiResult<LoginTokenResponse>{
return loginRepository.userKakaoLogin(loginBody)
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
package com.example.numberoneproject.presentation.di

import android.app.Application
import com.example.numberoneproject.BuildConfig
import com.kakao.sdk.common.KakaoSdk
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class MyApplication: Application() {

val KAKAO = BuildConfig.KAKAO_NATIVE_APP_KEY
override fun onCreate() {
super.onCreate()
KakaoSdk.init(this,KAKAO)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.example.numberoneproject.BuildConfig
import com.example.numberoneproject.R
import com.example.numberoneproject.data.model.TokenRequestBody
Expand All @@ -14,13 +16,19 @@ import com.example.numberoneproject.presentation.base.BaseActivity
import com.example.numberoneproject.presentation.util.Extensions.repeatOnStarted
import com.example.numberoneproject.presentation.util.TokenManager
import com.example.numberoneproject.presentation.viewmodel.LoginViewModel
import com.kakao.sdk.auth.model.OAuthToken
import com.kakao.sdk.common.model.ClientError
import com.kakao.sdk.common.model.ClientErrorCause
import com.kakao.sdk.user.UserApiClient
import com.navercorp.nid.NaverIdLoginSDK
import com.navercorp.nid.oauth.NidOAuthLogin
import com.navercorp.nid.oauth.OAuthLoginCallback
import com.navercorp.nid.profile.NidProfileCallback
import com.navercorp.nid.profile.data.NidProfileResponse
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding>(R.layout.activity_login) {
Expand Down Expand Up @@ -106,4 +114,33 @@ class LoginActivity : BaseActivity<ActivityLoginBinding>(R.layout.activity_login

NaverIdLoginSDK.authenticate(this, oauthLoginCallback)
}

fun setupKakaoLogin(view:View){
//카카오 계정 로그인
val callback : (OAuthToken?, Throwable?) -> Unit = {token, error->
if(error != null){
Toast.makeText(this,"카카오계정 로그인 실패 ${error}",Toast.LENGTH_SHORT).show()
}
else if(token != null){
loginVM.userKakaoLogin(TokenRequestBody(token.accessToken))
}
}
//카카오톡 어플있다면 카카오톡 로그인 시도
if(UserApiClient.instance.isKakaoTalkLoginAvailable(this)){
UserApiClient.instance.loginWithKakaoTalk(this){token, error->
if(error != null){
Toast.makeText(this,"카카오톡 로그인 실패 ${error}",Toast.LENGTH_SHORT).show()
if(error is ClientError && error.reason == ClientErrorCause.Cancelled){
return@loginWithKakaoTalk
}
UserApiClient.instance.loginWithKakaoAccount(this, callback = callback)
}else if(token != null){
loginVM.userKakaoLogin(TokenRequestBody(token.accessToken))
}
}
}
else{
UserApiClient.instance.loginWithKakaoAccount(this, callback=callback)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,27 @@ import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.example.numberoneproject.R
import com.example.numberoneproject.presentation.util.Extensions.repeatOnStarted
import com.example.numberoneproject.presentation.util.TokenManager
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class SplashActivity : AppCompatActivity() {
private val DURATION_TIME = 2000L // 스플래시 화면 지연시간
private lateinit var cm2 : ConnectivityManager
private val tokenManager: TokenManager = TokenManager(this)

private val networkCallBack = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
// 네트워크가 정상적인 경우
Toast.makeText(this@SplashActivity, "연결성공 $network", Toast.LENGTH_SHORT).show()

checkLogin()
Handler(Looper.getMainLooper()).postDelayed({
startActivity(Intent( this@SplashActivity,LoginActivity::class.java))
//startActivity(Intent( this@SplashActivity,LoginActivity::class.java))
finish()
}, DURATION_TIME)
}
Expand All @@ -38,12 +45,29 @@ class SplashActivity : AppCompatActivity() {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)


val builder = NetworkRequest.Builder()

cm2 = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
cm2.registerNetworkCallback(builder.build(),networkCallBack)
}

//자동로그인 가능한지 확인
fun checkLogin(){
lifecycleScope.launch{
tokenManager.accessToken.collectLatest {
if(it.isNotEmpty()){
val intent = Intent(this@SplashActivity,MainActivity::class.java)
startActivity(intent)
}
else{
val intent = Intent(this@SplashActivity,LoginActivity::class.java)
startActivity(intent)
}
}
}
}

Comment on lines +55 to +70
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#11 자동로그인 로직 옮겨야 할 것 같았던 부분인데 이렇게 하면 좋을 것 같아요

override fun onDestroy() {
super.onDestroy()
cm2 = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import com.example.numberoneproject.data.model.TokenRequestBody
import com.example.numberoneproject.data.network.ApiResult
import com.example.numberoneproject.data.network.onFailure
import com.example.numberoneproject.data.network.onSuccess
import com.example.numberoneproject.domain.usecase.KakaoLoginUsecase
import com.example.numberoneproject.domain.usecase.NaverLoginUseCase
import com.example.numberoneproject.domain.usecase.RefreshAccessTokenUseCase
import com.example.numberoneproject.domain.usecase.TestUseCase
Expand All @@ -22,6 +23,7 @@ import javax.inject.Inject
class LoginViewModel @Inject constructor(
private val tokenManager: TokenManager,
private val naverLoginUseCase: NaverLoginUseCase,
private val kakaoLoginUsecase: KakaoLoginUsecase,
private val testLoginUseCase: TestUseCase,
private val refreshAccessTokenUseCase: RefreshAccessTokenUseCase
) : ViewModel() {
Expand All @@ -41,6 +43,18 @@ class LoginViewModel @Inject constructor(
}
}

fun userKakaoLogin(loginBody: TokenRequestBody) {
viewModelScope.launch {
kakaoLoginUsecase(loginBody)
.onSuccess {
tokenManager.writeLoginTokens(it.accessToken, it.refreshToken)
}
.onFailure {
_loginErrorState.value = it
}
}
}

/** loginTest 관련 코드는 지금은 테스트 용도고 금방 지워질 코드 **/
fun loginTest() {
viewModelScope.launch {
Expand Down
3 changes: 2 additions & 1 deletion app/src/main/res/layout/activity_login.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
android:textSize="24sp"
android:textStyle="bold"
android:textColor="#FFEB3B"
android:text="카카오 로그인" />
android:text="카카오 로그인"
android:onClick="@{(v) -> activity.setupKakaoLogin(v)}"/>

<TextView
android:id="@+id/btn_naver_login"
Expand Down