[JAVA] I tried using "nifty cloud mobile backend" and "Firebase" Authentication on Kotlin + Android

Introduction

As announced at Google I / O 2017, Kotlin has joined the official language of Android, so using mBaaS (mobile Backend as a Service) ncmb (nifty cloud mobile backend) and Firebase, Kotlin immediately I tried Android programming. mBaaS is a service that provides general-purpose functions (user management, data store, push notification, etc.) that are often used for application development from the cloud, but this time we will introduce the user authentication functions of both.

Development environment

ncmb(nifty cloud mobile backend)

Create new app

First, create a new app from the dashboard. 図1.png

スクリーンショット 2017-07-16 13.03.38.png When you create a new app, you will be issued an application key and a client key. スクリーンショット 2017-07-16 12.52.52.png

Email address verification

The flow of ncmb email address authentication is as follows.

  1. User enters email address to request authentication
  2. An email containing the URL to the member registration screen will be sent to the email address you entered.
  3. Register the password on the member registration screen and register as a member.
  4. You can log in with your email address and password

App implementation

MainActivity.kt



class MainActivity : AppCompatActivity(), View.OnClickListener{

    //constant
    companion object Factory {
        // ApplicationKey
        val APP_KEY = "YOUR APP KEY" //Application key setting issued when creating a new application
        // ClientKey
        val CLIENT_KEY = "YOUR CLIENT KEY" //Client key settings issued when creating a new application
    }

    private var mEmailField: EditText? = null
    private var mPasswordField: EditText? = null
    private var loginMailAddress: EditText? = null
    private var loginPassword: EditText? = null

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

        //**********API key setting and SDK initialization**********
        NCMB.initialize(this.baseContext, APP_KEY, CLIENT_KEY)

        //Member registration
        mEmailField = findViewById(R.id.MailAddress) as EditText
        mPasswordField = findViewById(R.id.Password) as EditText
        //Login
        loginMailAddress = findViewById(R.id.login_MailAddress) as EditText
        loginPassword = findViewById(R.id.login_Password) as EditText

        //SIGN UP button
        findViewById(R.id.Button)?.setOnClickListener(this)

        //LOGIN button
        findViewById(R.id.login_Button)?.setOnClickListener(this)

        //LOGOUT button
        findViewById(R.id.logout_Button)?.setOnClickListener(this)
        }
    }

    /**
     *When the button is clicked
     */
    override fun onClick(v : View) {
        val id = v.id
        if(id == (R.id.Button)) {
            //Member registration
            createAccount(mEmailField?.text.toString())
        } else if(id == (R.id.login_Button)) {
            //Login
            signIn(loginMailAddress?.text.toString(), loginPassword?.text.toString())
        } else if(id == (R.id.logout_Button)) {
            //Log out
            signOut()
        }

    }

Member registration process

The member registration process is performed by the createAccount method that has a String type email as an argument, which is called when the SIGN UP button is pressed.

MainActivity.kt


private fun createAccount(email: String) {
        NCMBUser.requestAuthenticationMailInBackground(email) { e ->
                if(e == null) {
                    println("Successful user email authentication")
                } else {
                    println("User email authentication failed")
                }
        }
    }

If you write it in java, it will look like this. It is more verbose than kotlin. NCMBUser's requestAuthenticationMailInBackground method uses the email address entered by the user as an argument and [DoneCallback](http://www.programcreek.com/java-api-examples/index.php?source_dir=ncmb_android-master/ncmb-core/src It takes an interface (/main/java/com/nifty/cloud/mb/core/DoneCallback.java) as an argument. Here [DoneCallback](http://www.programcreek.com/java-api-examples/index.php?source_dir=ncmb_android-master/ncmb-core/src/main/java/com/nifty/cloud/mb/ An anonymous class that implements the core / DoneCallback.java) interface is generated and passed as an argument.

MainActivity.java


private void createAccount(String email) {
  NCMBUser.requestAuthenticationMailInBackground(email, 
   new DoneCallback() {
    @Override
    public void done(NCMBException e) {
        if (e == null) {
            System.out.println("Successful user email authentication");
        } else if {
            System.out.println("User email authentication failed");
        }
      }
   });
 }

For those who wrote in kotlin, the DoneCallback interface and the method called done (NCMBException e) are omitted, but this is SAM conversion by the SAM interface. SAM (Single Abstract Method) is an interface that has only one abstract method. [DoneCallback](http://www.programcreek.com/java-api-examples/index.php?source_dir=ncmb_android-master/ncmb-core/src/main/java/com/nifty/cloud/mb/core/ DoneCallback.java) The interface abstract method done (NCMBException e) has a void type as a return value and an NCMBException type as an argument. Therefore, you can omit the type of the function literal and describe it neatly like kotlin by type inference. For function literals, I referred to the article here.

If you can successfully register as a member, your user information will be registered on the member management screen of ncmb. スクリーンショット 2017-07-17 0.52.31.png

Login process

The login process is performed by the signIn method that has a String type email and a String type password as arguments, which are called when the LOGIN button is pressed. You can log in by calling NCMBUser's loginWithMailAddressInBackground method in the signIn method.

MainActivity.kt



private fun signIn(email: String, password: String) {
        NCMBUser.loginWithMailAddressInBackground(email, password) {user, e ->
                if(e == null) {
                    println("Login successful")
                } else {
                    println("Login failure:" + e.message.toString() )
                }
         }
}

After registering your password from the member registration email and registering as a member, you will be able to log in with your email address and password.

Logout process

The logout process calls the signOut method with no arguments, which is called when the logout button is pressed. You can log out by calling NCMBUser's logoutInBackground method in the sighOut method.

MainActivity.kt


    private fun signOut() {
        NCMBUser.logoutInBackground{ e ->
            if (e == null) {
                println("Successful logout")
            } else {
                println("Logout failure")
            }
        }
    }

Dashboard settings

To allow email address password authentication, check "Allow email address / password authentication" from the application settings → member authentication settings on the dashboard and save. スクリーンショット 2017-07-16 21.25.06.png

Firebase

Create new project

Log in to Firebase with your Google account and create a new project. スクリーンショット 2017-07-17 0.35.53.png

Allow email / password authentication

Enable email / password status from the Firebase Authentication administration screen. スクリーンショット 2017-07-17 0.46.26.png

App implementation

MainActivity.kt



class MainActivity : AppCompatActivity(), View.OnClickListener {

    private var mEmailField: EditText? = null
    private var mPasswordField: EditText? = null
    private var loginEmail: EditText? = null
    private var loginPassword: EditText? = null

    private var mAuth: FirebaseAuth? = null

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

        //New user item
        mEmailField = findViewById(R.id.MailAddress) as EditText
        mPasswordField = findViewById(R.id.Password) as EditText
        //Items at login
        loginEmail = findViewById(R.id.login_MailAddress) as EditText
        loginPassword = findViewById(R.id.login_Password) as EditText

        //When pressing the SIGN UP button
        findViewById(R.id.Button)?.setOnClickListener(this)
        //When pressing the LOGIN button
        findViewById(R.id.login_Button)?.setOnClickListener(this)
        //When pressing the LOG OUT button
        findViewById(R.id.logout_Button)?.setOnClickListener(this)

        //Get FirebaseAuth instance
        mAuth = FirebaseAuth.getInstance()
    }

    /**
     *Button click processing
     */
    override fun onClick(v: View) {
        val i = v.id
        if (i == R.id.Button) {
            //When the new button is pressed
            createAccount(mEmailField?.text.toString(), mPasswordField?.text.toString())
        } else if (i == R.id.login_Button) {
            //When the login button is pressed
            signIn(loginEmail?.text.toString(), loginPassword?.text.toString())
        } else if (i == R.id.logout_Button) {
            //When the logout button is pressed
            signOut()
        }
    }

Added Firebase Authentication dependencies to app-level build.gradle

build.gradle


dependencies {
 
     (Omitted)
     
    // Firebase Authentication
    compile 'com.google.firebase:firebase-auth:10.0.1'add to
}

Member registration process

In the createAccount method called when the SIGN UP button is pressed, pass the email address and password entered by the user to the createUserWithEmailAndPassword method of the Firebase instance to create a new account.

MainActivity.kt


private fun createAccount(email: String, password: String) {
        mAuth?.createUserWithEmailAndPassword(email, password)
                ?.addOnCompleteListener(this) { task ->
                    if (task.isSuccessful) {
                        println("Successful user creation")
                        sendEmailVerrification()//Send confirmation email
                    } else {
                        println("User creation failure:" + task.exception.toString())
                    }
                }
    }

** Caution **: In ncmb, a confirmation email was sent at the time of membership registration, and the password was set by clicking the link in the email and the membership registration was completed, but in Firebase, a confirmation email was sent at the time of membership registration. It will not be. Therefore, when a new user is created successfully, a method to send a confirmation email is created and called.

If you can create a user normally, the user information will be saved in the management screen of Firebase. スクリーンショット 2017-07-17 1.59.22.png

Confirmation email sending process

If you have successfully created a new user, call this method to send a confirmation email to the user.

MainActivity.kt


private fun sendEmailVerrification() {
        val user = FirebaseAuth.getInstance().currentUser
        user?.sendEmailVerification()
                ?.addOnCompleteListener(this) { task ->
                    if(task.isSuccessful) {
                        println("Successful email transmission")
                    } else {
                        println("Email transmission failure:" + task.exception.toString())
                    }
                }
    }

Login process

In the dignIn method called when the LOGIN button is pressed, pass the email address and password entered by the user to the signInWithEmailAndPassword method of the Firebase instance as arguments.

MainActivity.kt


private fun signIn(email: String, password: String) {
        mAuth?.signInWithEmailAndPassword(email, password)
                ?.addOnCompleteListener(this) { task ->
                    if(task.isSuccessful) {
                        println("Successful login user:" + mAuth?.currentUser.toString())
                    } else {
                        println("Login failure")
                    }
                }
    }

Logout processing

With the signOut method called when the LOGOUT button is pressed, call the signOut method of the Firebase instance to log out.

MainActivity.kt


private fun signOut() {
        mAuth?.signOut()
 }

Firebase Analytics Firebase also has a tool called Firebase Analytics, which is positioned as Google Analytics specialized for mobile applications, and although I have not investigated it in detail, it seems to be useful for access analysis. Regarding the installation procedure, the article here was easy to understand.

スクリーンショット 2017-07-17 2.12.58.png

Reference material

[NCMB Official Document](http://mb.cloud.nifty.com/doc/current/user/authorize_email_android.html# Implementation in App) Firebase Official Document http://qiita.com/RyotaMurohoshi/items/01b370f34a4bf96f5c39 http://kotlin.hatenablog.jp/entry/2012/12/10/093018

Recommended Posts

I tried using "nifty cloud mobile backend" and "Firebase" Authentication on Kotlin + Android
Try using Firebase Cloud Functions on Android (Java)
[Android] I quit SQLite and tried using Realm
I tried using Scalar DL with Docker
Try using Firebase Cloud Functions on Android (Java)
I tried using YOLO v4 on Ubuntu and ROS
[Android] I tried using Coordinator Layout.
I tried using Junit on Mac VScode Maven
I stumbled on Android DataBinding + Kotlin (more BindingAdapter)
I tried using a database connection in Android development
I tried using Google Cloud Vision API in Java
I tried using Log4j2 on a Java EE server
I installed CentOS 8 on Windows 10 using VirtualBox and Vagrant
I tried using Gson
I tried using TestNG
I tried using Galasa
I tried unit testing Rails app using RSpec and FactoryBot
I tried adding a separator line to TabLayout on Android
I tried to summarize the basics of kotlin and java
[Rails] I tried to implement "Like function" using rails and js
[Android] [Library] I tried using an animation library called "Before After animation".
I tried using the CameraX library with Android Java Fragment
Zip and upload multiple files to Firebase Storage on Android.
I wanted to animate a row when using realm and RecyclerView on Android, but I gave up