エンジニア男

勉強したことの忘備録としてつらつら書いていきます。

【Android】Firebase Authenticationの使い方

AndroidでFirebase Authenticationの使い方のメモ

 

・公式ドキュメント

https://firebase.google.com/docs/auth/android/start?hl=ja

 

■EmailとPasswordで認証

 

・build.gradle(app)

dependenciesに下記を追加

dependencies {

implementation 'com.google.firebase:firebase-core:17.0.0'
implementation 'com.google.firebase:firebase-analytics:17.5.0'
// add
implementation 'com.google.firebase:firebase-auth-ktx:19.3.2'
}

 

 

・AuthActivity.kt

class AuthActivity : AppCompatActivity() {

private lateinit var auth: FirebaseAuth
private lateinit var binding: ActivityAuthBinding

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_auth)

auth = Firebase.auth

setup()
}

private fun setup() {
title = "Authentication"

binding.apply {
btnRegister.setOnClickListener {
if (editEmail.text.isNotEmpty() && editPassword.text.isNotEmpty()) {
auth.createUserWithEmailAndPassword(editEmail.text.toString(), editPassword.text.toString()).addOnCompleteListener {
if (it.isSuccessful) {
showHome(it.result?.user?.email ?: "", ProviderType.BASIC)
} else {
showAlert("ユーザ登録に失敗しました")
}
}
} else {
showAlert("メールアドレス または パスワードを入力してください")
}
}
}

binding.apply {
btnLogin.setOnClickListener {
if (editEmail.text.isNotEmpty() && editPassword.text.isNotEmpty()) {
          auth.signInWithEmailAndPassword(editEmail.text.toString(), editPassword.text.toString()).addOnCompleteListener {
if (it.isSuccessful) {
showHome(it.result?.user?.email ?: "", ProviderType.BASIC)
} else {
showAlert("ログインに失敗しました")
}
}
} else {
showAlert("メールアドレス または パスワードを入力してください")
}
}
}
}

private fun showAlert(errorMessage: String) {
val builder = AlertDialog.Builder(this)
builder.setTitle("Error")
builder.setMessage(errorMessage)
builder.setPositiveButton("OK", null)
builder.create().show()
}

private fun showHome(email: String, provider: ProviderType) {
val homeIntent = Intent(this, HomeActivity::class.java).apply {
putExtra("email", email)
putExtra("provider", provider.name)
}
startActivity(homeIntent)
}

}

 

 

・HomeActivity.kt

enum class ProviderType {
BASIC
}

class HomeActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)

val bundle = intent.extras
val email = bundle?.getString("email")
val provider = bundle?.getString("provider")
setup(email ?: "", provider ?: "")
}

private fun setup(email: String, provider: String) {
title = "home"
textEmail.text = email
textProvider.text = provider

btnLogout.setOnClickListener {
FirebaseAuth.getInstance().signOut()
onBackPressed()
}
}

}