[Firebase] Facebook 로그인 구현 & RealTime DB 사용하기

LeeEunJae·2022년 7월 21일
1

Firebase

목록 보기
1/3

📌 환경 세팅

📌 activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="24dp"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <EditText
        android:id="@+id/emailEditText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
    <EditText
        android:id="@+id/passwordEditText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        app:layout_constraintTop_toBottomOf="@id/emailEditText"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
    <Button
        android:id="@+id/loginButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="로그인"
        app:layout_constraintTop_toBottomOf="@id/passwordEditText"
        app:layout_constraintEnd_toEndOf="parent"/>
    <Button
        android:id="@+id/signUpButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="회원가입"
        android:layout_marginEnd="4dp"
        app:layout_constraintTop_toBottomOf="@id/passwordEditText"
        app:layout_constraintEnd_toStartOf="@id/loginButton"/>

    <com.facebook.login.widget.LoginButton
        android:id="@+id/facebookLoginButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/loginButton"/>
</androidx.constraintlayout.widget.ConstraintLayout>

로그인 화면 xml

📌 Facebook 로그인 버튼 이벤트 처리 메소드

auth = Firebase.auth
// 페이스북 로그인 응답을 처리할 callbackManager 생성
callbackManager = CallbackManager.Factory.create()

auth와 callbackManager 변수를 미리 lateinit var 로 선언해두고 onCreate() 에서 위와 같이 작성해주면 된다.

private fun initFacebookLoginButton(){ // facebook 로그인 버튼 이벤트 처리
        binding.facebookLoginButton.setPermissions("email","public_profile") // 로그인 버튼에 권한 요청(email 과 프로필 가져오기)
        // 로그인 결과에 응답하기 위해서 로그인 버튼에 콜백 등록
        binding.facebookLoginButton.registerCallback(callbackManager, object: FacebookCallback<LoginResult>{
            override fun onSuccess(result: LoginResult) {
                // 로그인 성공
                // Firebase auth 로 값을 전달해서 로그인
                val credential = FacebookAuthProvider.getCredential(result.accessToken.token)
                auth.signInWithCredential(credential) // token 으로 만들어진 credential 을 통해 로그인 시도
                    .addOnSuccessListener {
                        handleSuccessLogin() // 로그인 성공시 DB에 정보를 저장하는 메소드
                    }
                    .addOnFailureListener {
                        Toast.makeText(this@LoginActivity, "페이스북 로그인이 실패했습니다.", Toast.LENGTH_SHORT).show()
                    }

            }
            override fun onCancel() {}

            override fun onError(error: FacebookException) {
                Toast.makeText(this@LoginActivity, "페이스북 로그인이 실패했습니다.", Toast.LENGTH_SHORT).show()
            }


        })
    }

📌 Facebook 로그인 성공시 DB에 userUid를 저장하는 메소드


    private fun handleSuccessLogin(){
        if(auth.currentUser == null){
            Toast.makeText(this, "로그인에 실패했습니다.", Toast.LENGTH_SHORT).show()
            return
        }
        val userId = auth.currentUser!!.uid
        // database의 Users -> userId(현재 로그인한 유저의 uid)
        val currentUserDB = Firebase.database.reference.child("Users").child(userId)
        // DB에 저장할 형태 key-value
        val user = mutableMapOf<String, Any>()
        user["userId"] = userId
        // user 정보를 db에 저장한다 Users -> userId -> user
        currentUserDB.updateChildren(user)
        finish()
    }
Firebase.database.reference.child("Users").child(userId) 
위 코드를 통해 DB를 불러오고 "Users" 안에 userId 안에 데이터를 저장할 것을 지정해준다.
profile
매일 조금씩이라도 성장하자

0개의 댓글