Firebase를 사용하여 이메일/비밀번호
로 로그인 인증하는 기능을 구현해 보겠습니다.
프로젝트 생성 -> 앱 등록 -> json파일 설치 후 앱 모듈에 넣기
다음 단계에 따라 Firebase SDK 추가
콘솔로 이동하여 Authentication
-> 이메일/비밀번호
사용 설정 저장
implementation("com.google.firebase:firebase-auth-ktx")
package com.example.firebasefcmex.auth
import android.content.ContentValues.TAG
import android.os.Bundle
import android.util.Log
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.example.firebasefcmex.R
import com.google.android.material.textfield.TextInputEditText
import com.google.firebase.Firebase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth
class JoinActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_join)
// Initialize Firebase Auth
auth = Firebase.auth
val joinBtn = findViewById<Button>(R.id.joinBtn)
joinBtn.setOnClickListener {
val email = findViewById<TextInputEditText>(R.id.email).text.toString()
val pwd = findViewById<TextInputEditText>(R.id.pwd).text.toString()
auth.createUserWithEmailAndPassword(email, pwd)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "createUserWithEmail:success")
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.exception)
}
}
}
}
}
파이어베이스 유저에 잘 저장된 것을 확인할 수 있습니다.
class LoginActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
auth = Firebase.auth
val loginBtn = findViewById<Button>(R.id.loginBtn)
loginBtn.setOnClickListener {
val email = findViewById<TextInputEditText>(R.id.email).text.toString()
val password = findViewById<TextInputEditText>(R.id.pwd).text.toString()
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithEmail:success")
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.exception)
}
}
}
}
}
로그아웃은 Firebase.auth.signOut()
을 호출하여 간단하게 가능합니다.