ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 구글 로그인과 Firebase
    앱 만들기/앱 학습 자료들 정리 2023. 6. 3. 00:10

    내가 만드는 앱에 구글 로그인 추가!!!

     

    먼저 구글 로그인을 구현하기 전에 Firebase와의 연동이 필요하다. 이미 많은 자료들이 나와 있으므로 링크를 걸고 생략....

    https://soopeach.tistory.com/77

     

    안드로이드 스튜디오[Android Studio] 파이어베이스(Firebase) 연동하기

    파이어 베이스는 앱, 웹 등 개발할 때 도움을 주는 매우 편리한 백앤드 서비스입니다. 파이어 베이스와 안드로이드 스튜디오 프로젝트를 연동시켜보겠습니다. (이 글은 3월 7일 기준으로 작성되

    soopeach.tistory.com

     

    안드로이드 구글 로그인과 파이어베이스 로그인을 연동하기로 해본다.

     

    1. 파이어 베이스 세팅

    a) 먼저 Firebase에 있는 Authentication에 들어가서 생성해준다.

     

    b). 그 다음 위에 'Sign-in method' 칸 -> '추가 제공업체' -> 'Google' 클릭 

    c) 사용 설정 부분 클릭

    d) 만약 SHA-1 디지털 지문 추가를 안했다면 '프로젝트 설정'에 들어가서 추가하기

     

    Android Studio에서 SHA-1 디지털 지문  찾는 방법 : 오른쪽  gradle 에서 Gradle 아래 & Android_Study_App 위에 맨 왼쪽 클릭해서 'gradle signinReport' 누르고 app대신 실행시키면 나온다.

    e) google-service.json 갱신 -  (d)에서 '프로젝트 설정'에 들어가서 아래로 가면 다운받을수 있다

    2.  코드 부분

    a) build.gradle

    dependencies {
    	...
        
        //----------- firebase 부분  ------------
        implementation platform('com.google.firebase:firebase-bom:32.0.0')
        implementation 'com.google.firebase:firebase-analytics-ktx'
    
        //----------- 구글 로그인 부분  ------------
        implementation 'com.google.firebase:firebase-auth-ktx'
        implementation 'com.google.android.gms:play-services-auth:20.5.0'
    }
    apply plugin: 'com.google.gms.google-services'

    b) LoginActivity.kt

    class LoginActivity : AppCompatActivity() {
        private val TAG = "MainActivity"
    
        private var mGoogleSignInClient: GoogleSignInClient? = null   // 구글api클라이언트
        private var gsa: GoogleSignInAccount? = null     // 구글 계정
    
        private var mAuth: FirebaseAuth? = null  // 파이어베이스 인증 객체 생성
        private lateinit var binding: ActivityLoginBinding // 뷰 바인딩
        private var resultLauncher: ActivityResultLauncher<Intent>? = null
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = ActivityLoginBinding.inflate(layoutInflater)
            setContentView(binding.root)
    
            // 파이어베이스 인증 객체 선언
            mAuth = FirebaseAuth.getInstance()
    
            // 구글 로그인시 callback 되는 부분
            resultLauncher =
                registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
                    if (result.resultCode == RESULT_OK) {
                        // The Task returned from this call is always completed, no need to attach a listener.
                        val task: Task<GoogleSignInAccount> =
                            GoogleSignIn.getSignedInAccountFromIntent(result.data)
                        handleSignInResult(task)
                    }
                }
    
            val googleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.web_client_id))
                .requestEmail()
                .build()
    
            mGoogleSignInClient = GoogleSignIn.getClient(this, googleSignInOptions)
    
            binding.googleLoginBtn.setOnClickListener {
                // 기존에 로그인 했던 계정을 확인한다.
                gsa = GoogleSignIn.getLastSignedInAccount(this)
                if (gsa != null) // 로그인 되있는 경우
                    Toast.makeText(this, "이미 로그인이 되어있습니다.", Toast.LENGTH_SHORT).show()
                else
                    signIn()
            }
    
            binding.logoutBtn.setOnClickListener {
                signOut() //로그아웃
            }
    
        }
    
        //로그인
        private fun signIn() {
            val signInIntent = mGoogleSignInClient!!.signInIntent
            resultLauncher?.launch(Intent(signInIntent))
        }
    
        /* 사용자 정보 가져오기 */
        private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
            try {
                val acct: GoogleSignInAccount = completedTask.getResult(ApiException::class.java)
                firebaseAuthWithGoogle(acct.idToken)
                val personName = acct.displayName
                val personGivenName = acct.givenName
                val personFamilyName = acct.familyName
                val personEmail = acct.email
                val personId = acct.id
                val personPhoto = acct.photoUrl
                Log.d(TAG, "handleSignInResult:personName $personName")
                Log.d(TAG, "handleSignInResult:personGivenName $personGivenName")
                Log.d(TAG, "handleSignInResult:personEmail $personEmail")
                Log.d(TAG, "handleSignInResult:personId $personId")
                Log.d(TAG, "handleSignInResult:personFamilyName $personFamilyName")
                Log.d(TAG, "handleSignInResult:personPhoto $personPhoto")
            } catch (e: ApiException) {
                // The ApiException status code indicates the detailed failure reason.
                // Please refer to the GoogleSignInStatusCodes class reference for more information.
                Log.e(TAG, "signInResult:failed code=" + e.statusCode)
            }
        }
    
    
        // [START auth_with_google]
        private fun firebaseAuthWithGoogle(idToken: String?) {
            val credential = GoogleAuthProvider.getCredential(idToken, null)
            mAuth!!.signInWithCredential(credential)
                .addOnCompleteListener(
                    this
                ) { task: Task<AuthResult?> ->
                    if (task.isSuccessful) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success")
                        Toast.makeText(this, "구글 로그인 성공", Toast.LENGTH_SHORT).show()
                        val user = mAuth!!.currentUser
                        if (user != null) {
                            // 유저 관련 데이터를 받고 무언가 할경우 여기서 하기
                        }
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.exception)
                        Toast.makeText(this, "구글 로그인 실패", Toast.LENGTH_SHORT).show()
    //                    updateUI(null);
                    }
                }
        }
    
        /* 로그아웃 */
        private fun signOut() {
            mGoogleSignInClient!!.signOut()
                .addOnCompleteListener(this) { task: Task<Void?>? ->
                    mAuth!!.signOut()
                    Toast.makeText(this, "구글 로그아웃", Toast.LENGTH_SHORT)
                        .show()
                }
            gsa = null
        }
    
        /* 회원 삭제요청 */
        private fun revokeAccess() {
            mGoogleSignInClient!!.revokeAccess()
                .addOnCompleteListener(
                    this
                ) { task: Task<Void?>? -> }
        }
    }

    c) activity_login.xml

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".LoginActivity">
    
        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/constraintLayout"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintBottom_toTopOf="@+id/guideline"
            app:layout_constraintTop_toTopOf="parent">
        </androidx.constraintlayout.widget.ConstraintLayout>
    
        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.4" />
    
        <com.google.android.gms.common.SignInButton
            android:id="@+id/googleLoginBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/constraintLayout" />
    
        <Button
            android:id="@+id/logoutBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="Logout"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/googleLoginBtn" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>

    '앱 만들기 > 앱 학습 자료들 정리' 카테고리의 다른 글

    카카오 로그인  (0) 2023.06.03
    프로젝트 README.md  (0) 2023.05.29
Designed by Tistory.