Android + Kotlin で Firebaseによるメール認証

久々にAndroid。Androidにかかわらず、何かサービスなりアプリケーションなり作成しようとすると、ログインの仕組みだとか作るのが面倒くさい、というかそのあたりを作り上げると力尽きてそもそも何がしたかったのかわからなくなることがままある。

自分を含め、という人のために、Baas(Backend as a service) という、バックエンド機構をサービスとして提供する考え方があり、GoogleのBaas、Firebaseを使用して、Androidアプリにメール認証機能を組み込む。

1.Firebaseアカウントを作成しメール認証を有効化

Firebaseにアカウントを登録して、プロジェクトを登録。無料で始められる

https://firebase.google.com/?hl=ja

firebase_auth_getstart

ログインプロバイダ、メール/パスワードを有効にする

firebase_auth_mail_enable

2.Android Studio でプロジェクトを作成しFirebaseアシスタントを使用

https://firebase.google.com/docs/android/setup?authuser=0

Tools から、Firebaseを選択すると、画面の右にチュートリアルが起動

firebase_assistant

Authentication の、Email and password authentication を展開

firebase_assistant2

ウィザード形式で手順が表示されるので、それに従う。

JavaのサンプルコードをなれないKotlinに読み替えつつ。

3.プログラムの作成

とりあえず、画面にメールアドレスとパスワード入力欄、ユーザー作成と、サインインボタンを配置し、MainActivityに上記チュートリアルのコードをKotlinに読み替えつつ、動作を簡易に確認できるレベルで実装してみる。

  1. package info.typea.sentence2
  2.  
  3. import android.support.v7.app.AppCompatActivity
  4. import android.os.Bundle
  5. import android.util.Log
  6. import android.widget.Button
  7. import android.widget.EditText
  8. import android.widget.TextView
  9. import android.widget.Toast
  10. import com.google.android.gms.tasks.Task
  11. import com.google.firebase.auth.AuthResult
  12. import com.google.firebase.auth.FirebaseAuth
  13. import com.google.firebase.auth.FirebaseUser
  14.  
  15. class MainActivity : AppCompatActivity() {
  16. companion object {
  17. const val TAG: String = "MainActivity"
  18. }
  19. private var mAuth: FirebaseAuth? = null
  20.  
  21. override fun onCreate(savedInstanceState: Bundle?) {
  22. super.onCreate(savedInstanceState)
  23. setContentView(R.layout.activity_main)
  24.  
  25. mAuth = FirebaseAuth.getInstance()
  26.  
  27. // ユーザー登録ボタン
  28. var btnCreate: Button = findViewById<Button>(R.id.btnCreate) as Button
  29. btnCreate.setOnClickListener{
  30. var email = (this.findViewById<EditText>(R.id.txtEmail) as EditText).text.toString()
  31. var password = (this.findViewById<EditText>(R.id.txtPassword) as EditText).text.toString()
  32. Log.i(TAG, String.format("create email=%s, password%s", email, password))
  33. createUserWithEmailAndPassword(email, password )
  34. }
  35.  
  36. // サインインボタン
  37. var btnSignIn: Button = findViewById<Button>(R.id.btnSignIn) as Button
  38. btnSignIn.setOnClickListener{
  39. var email = (this.findViewById<EditText>(R.id.txtEmail) as EditText).text.toString()
  40. var password = (this.findViewById<EditText>(R.id.txtPassword) as EditText).text.toString()
  41. Log.i(TAG, String.format("signin email=%s, password%s", email, password))
  42. signInWithEmailAndPassword(email, password)
  43. }
  44. }
  45.  
  46. override fun onStart() {
  47. super.onStart()
  48.  
  49. var currentUser = mAuth?.currentUser
  50. updateUI(currentUser)
  51. }
  52.  
  53. // 画面表示更新
  54. private fun updateUI(currentUser:FirebaseUser?) {
  55. Log.i(TAG, String.format("update ui user=%s", currentUser?.email.toString()))
  56. (findViewById<TextView>(R.id.lblUser) as TextView).text = currentUser?.email.toString()
  57. }
  58.  
  59. // ユーザー登録処理
  60. private fun createUserWithEmailAndPassword(email: String, password: String) {
  61. mAuth?.createUserWithEmailAndPassword(email, password)?.addOnCompleteListener{
  62. task: Task<AuthResult> ->
  63. if (task.isSuccessful) {
  64. Log.d(TAG, "createUserWithEmail:success")
  65. var user = mAuth?.currentUser
  66. updateUI(user)
  67. } else {
  68. Log.w(TAG, "createUserWithEmail:failure")
  69. Toast.makeText(this, "Authentication failed",Toast.LENGTH_SHORT).show()
  70. updateUI(null)
  71. }
  72. }
  73. }
  74.  
  75. // サインイン処理
  76. private fun signInWithEmailAndPassword(email: String, password: String) {
  77. mAuth?.signInWithEmailAndPassword(email, password)?.addOnCompleteListener{
  78. task: Task<AuthResult> ->
  79. if(task.isSuccessful) {
  80. Log.d(TAG, "signInWithEmail:success")
  81. var user = mAuth?.currentUser
  82. updateUI(user)
  83. } else {
  84. Log.w(TAG, "signInWithEmail:failure")
  85. Toast.makeText(this, "Authentication failed",Toast.LENGTH_SHORT).show()
  86. updateUI(null)
  87. }
  88. }
  89. }
  90. }

4.実行

メールアドレスとパスワード(6桁以上)を設定し、CREATEボタンを押下

処理が成功して、画面最上段にメールアドレスが表示された。

firebase_auth_screen

Firebaseの管理画面上にも、入力したメールアドレスが登録された!

これは捗る。

firebase_auth_success

Follow me!

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です