Secure registration

To be able to send and receive messages, you must first authenticate against Delivered’s servers. This is done so that only authorised users can communicate using the Delivered SDK. Before you do this make sure you have followed the steps to add the Delivered SDK to your app in the Get Started section.

Currently the Delivered SDK relies on the Firebase authentication provider. To be able to authenticate you must first add Firebase to your project and enable the Firebase Auth feature. To achieve this please refer to the following link: https://firebase.google.com/docs/auth/android/start/.

Once Firebase Auth has been set up and enabled the next step will be authenticating with the Delivered SDK. This could be done for two different cases: logging in existing users or registering new ones.

Registering new users

The first time a user enters your app you must ask for their email, password and a user name. These will in turn be used to authenticate with Firebase. Once this done you will receive a Firebase token which can be retrieved as follows:

private FirebaseAuth mAuth;

...

// 1. Create new user in Firebase.
mAuth.createUserWithEmailAndPassword(userEmail, userPassword)
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {

    // 2. Retrieve Firebase token from response.
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        if (task.isSuccessful()) {
            Log.d(TAG, "Firebase registration successfully completed");
            final FirebaseUser user = task.getResult().getUser();
            final Task<GetTokenResult> tokenTask = user.getIdToken(true);
            tokenTask.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {

                // 3. Authenticate with Delivered using the received Firebase token.
                @Override
                public void onComplete(@NonNull Task<GetTokenResult> task) {
                
                 	// Firebase token can be retrieved this way:
                    String token = task.getResult().getToken();
                    if (!TextUtils.isEmpty(token)) {
                    
                    	/* Here is where you'll use your Firebase token to 
                    	   authenticate with Delivered. */
                    	   
                        ...
                        
                    }
                }
            });
        } else {
            Log.e(TAG, "Registration failed", task.getException());
        }
    }
});

Next, use your Firebase token to authenticate with Delivered calling the DeliveredSdk.registerWithFirebaseToken method. This method takes a user name, a Firebase token and an optional callback you can use to track the authentication result:

DeliveredSdk.registerWithFirebaseToken(userName, firebaseToken, new DeliveredAuthCallback() {

    @Override
    public void onAuthComplete(String deliveredToken) {
        if (!TextUtils.isEmpty(deliveredToken)) {
            Log.d(TAG, "Delivered authentication successful - email: " + userEmail
                    + " token: " + deliveredToken);
        } else {
	        Log.d(TAG, "Delivered authentication failed...);
        }
    }
});

And that’s all you need to do. Once you have registered your users they will be able to log in using the credentials provided in the registration. The login flow is explained in the next section.

Logging in existing users

Once your users have registered they can login again to your app at any time. This will, most likely, happen if the user reinstalls the app or installs it in another device. To achieve this you can provide a login screen and ask your users to input the same email and password they used to register.

Use the user’s credential to log in to Delivered as shown here:

// 1. Attempt to refresh an already stored Delivered auth token.
Log.d(TAG, "Login in. Attempting Delivered token refresh");
DeliveredSdk.refreshDeliveredToken(new TokenRefreshCallback() {

    // 2. If a token is found and successfully refreshed we are all good.
    @Override
    public void onAuthTokenRefreshed(String deliveredToken) {
        if (!TextUtils.isEmpty(deliveredToken)) {
            Log.d(TAG, "Delivered token refresh successfully completed!");
        } else {
            // If no token is found, we sign in with Firebase once more
            // to receive a new token and use it to authenticate with Delivered.
            Log.d(TAG, "Delivered token failed. Re-authenticating...");
            mAuth.signInWithEmailAndPassword(userEmail, userPassword)
                    .addOnCompleteListener(new OnCompleteListener<AuthResult>() {

                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        task.getResult().getUser().getIdToken(true).addOnCompleteListener(
                                new OnCompleteListener<GetTokenResult>() {

                            @Override
                            public void onComplete(@NonNull Task<GetTokenResult> task) {
                                String token = task.getResult().getToken();
                                if (!TextUtils.isEmpty(token)) {
                                    DeliveredSdk.registerWithFirebaseToken(userName, firebaseToken, 
                                        new DeliveredAuthCallback() {

											    @Override
											    public void onAuthComplete(String deliveredToken) {
											        if (!TextUtils.isEmpty(deliveredToken)) {
											            Log.d(TAG, "Delivered authentication successful - email: " 
											            + userEmail + " token: " + deliveredToken);
											        } else {
												        Log.d(TAG, "Delivered authentication failed...);
											        }
											    }
											});
                                }
                            }
                        });
                    } else {
                        Log.e(TAG, "Login failed", task.getException());
                    }
                }
            });
        }
    }
});

Notice the flow of the code above. First we check if we have a token, and if we do, we can attempt to refresh it. This is for cases where you provide a logout mechanism in your app. For fresh installations where no existing token is found, the flow is exactly the same as when registering.

After you have authenticated with Delivered, head up to the Initial setup section to start setting up the necessary Delivered SDK components used for chatting.