Android + Kotlin で Firebaseによるメール認証
久々にAndroid。Androidにかかわらず、何かサービスなりアプリケーションなり作成しようとすると、ログインの仕組みだとか作るのが面倒くさい、というかそのあたりを作り上げると力尽きてそもそも何がしたかったのかわからなくなることがままある。
自分を含め、という人のために、Baas(Backend as a service) という、バックエンド機構をサービスとして提供する考え方があり、GoogleのBaas、Firebaseを使用して、Androidアプリにメール認証機能を組み込む。
1.Firebaseアカウントを作成しメール認証を有効化
Firebaseにアカウントを登録して、プロジェクトを登録。無料で始められる
https://firebase.google.com/?hl=ja
ログインプロバイダ、メール/パスワードを有効にする
2.Android Studio でプロジェクトを作成しFirebaseアシスタントを使用
https://firebase.google.com/docs/android/setup?authuser=0
Tools から、Firebaseを選択すると、画面の右にチュートリアルが起動
Authentication の、Email and password authentication を展開
ウィザード形式で手順が表示されるので、それに従う。
JavaのサンプルコードをなれないKotlinに読み替えつつ。
3.プログラムの作成
とりあえず、画面にメールアドレスとパスワード入力欄、ユーザー作成と、サインインボタンを配置し、MainActivityに上記チュートリアルのコードをKotlinに読み替えつつ、動作を簡易に確認できるレベルで実装してみる。
- package info.typea.sentence2
- import android.support.v7.app.AppCompatActivity
- import android.os.Bundle
- import android.util.Log
- import android.widget.Button
- import android.widget.EditText
- import android.widget.TextView
- import android.widget.Toast
- import com.google.android.gms.tasks.Task
- import com.google.firebase.auth.AuthResult
- import com.google.firebase.auth.FirebaseAuth
- import com.google.firebase.auth.FirebaseUser
- class MainActivity : AppCompatActivity() {
- companion object {
- const val TAG: String = "MainActivity"
- }
- private var mAuth: FirebaseAuth? = null
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_main)
- mAuth = FirebaseAuth.getInstance()
- // ユーザー登録ボタン
- var btnCreate: Button = findViewById<Button>(R.id.btnCreate) as Button
- btnCreate.setOnClickListener{
- var email = (this.findViewById<EditText>(R.id.txtEmail) as EditText).text.toString()
- var password = (this.findViewById<EditText>(R.id.txtPassword) as EditText).text.toString()
- Log.i(TAG, String.format("create email=%s, password%s", email, password))
- createUserWithEmailAndPassword(email, password )
- }
- // サインインボタン
- var btnSignIn: Button = findViewById<Button>(R.id.btnSignIn) as Button
- btnSignIn.setOnClickListener{
- var email = (this.findViewById<EditText>(R.id.txtEmail) as EditText).text.toString()
- var password = (this.findViewById<EditText>(R.id.txtPassword) as EditText).text.toString()
- Log.i(TAG, String.format("signin email=%s, password%s", email, password))
- signInWithEmailAndPassword(email, password)
- }
- }
- override fun onStart() {
- super.onStart()
- var currentUser = mAuth?.currentUser
- updateUI(currentUser)
- }
- // 画面表示更新
- private fun updateUI(currentUser:FirebaseUser?) {
- Log.i(TAG, String.format("update ui user=%s", currentUser?.email.toString()))
- (findViewById<TextView>(R.id.lblUser) as TextView).text = currentUser?.email.toString()
- }
- // ユーザー登録処理
- private fun createUserWithEmailAndPassword(email: String, password: String) {
- mAuth?.createUserWithEmailAndPassword(email, password)?.addOnCompleteListener{
- task: Task<AuthResult> ->
- if (task.isSuccessful) {
- Log.d(TAG, "createUserWithEmail:success")
- var user = mAuth?.currentUser
- updateUI(user)
- } else {
- Log.w(TAG, "createUserWithEmail:failure")
- Toast.makeText(this, "Authentication failed",Toast.LENGTH_SHORT).show()
- updateUI(null)
- }
- }
- }
- // サインイン処理
- private fun signInWithEmailAndPassword(email: String, password: String) {
- mAuth?.signInWithEmailAndPassword(email, password)?.addOnCompleteListener{
- task: Task<AuthResult> ->
- if(task.isSuccessful) {
- Log.d(TAG, "signInWithEmail:success")
- var user = mAuth?.currentUser
- updateUI(user)
- } else {
- Log.w(TAG, "signInWithEmail:failure")
- Toast.makeText(this, "Authentication failed",Toast.LENGTH_SHORT).show()
- updateUI(null)
- }
- }
- }
- }
4.実行
メールアドレスとパスワード(6桁以上)を設定し、CREATEボタンを押下
処理が成功して、画面最上段にメールアドレスが表示された。
Firebaseの管理画面上にも、入力したメールアドレスが登録された!
これは捗る。