Authentication and Authorization

Pre-built customizable chat UI - Authentication

This section will guide you in authenticating users for the pre-built customizable chat UI in your android app which can be Java or Kotlin android project

Alternatively, if you are looking to authenticate users for the "build your own chat UI" using Applozic's features, you can refer to Build your UI from scratch - Authentication

User Registration/Login

🚧

Note

Please remember you have to log in once and only after you log out you must log in again. Use below code to check if the user is already logged in.

You can check if the user is logged in to applozic or not by using:

if(Applozic.isConnected(context)){
  //do something
}
if (Applozic.isConnected(context)) {
    Log.i("ApplozicUser", "User is logged in")
} else {
    Log.i("ApplozicUser", "User is not logged in")
}

Applozic creates a new user if the user doesn't exist. userId is the unique identifier for any user, it can be anything like email, phone number or uuid from your database.

Call the UserLoginTask as below:

User user = new User();          
user.setUserId(userId); //userId it can be any unique user identifier NOTE : +,*,? are not allowed chars in userId.
user.setDisplayName(displayName); //displayName is the name of the user which will be shown in chat messages
user.setEmail(email); //optional
user.setAuthenticationTypeId(User.AuthenticationType.APPLOZIC.getValue());  //User.AuthenticationType.APPLOZIC.getValue() for password verification from Applozic server and User.AuthenticationType.CLIENT.getValue() for access Token verification from your server set access token as password
user.setPassword(""); //optional, leave it blank for testing purpose, read this if you want to add additional security by verifying password from your server https://www.applozic.com/docs/configuration.html#access-token-url
user.setImageLink("");//optional, set your image link if you have 

 Applozic.connectUser(context, user, new AlLoginHandler() {
                @Override
                public void onSuccess(RegistrationResponse registrationResponse, Context context) {
                    // After successful registration with Applozic server the callback will come here 
                }

                @Override
                public void onFailure(RegistrationResponse registrationResponse, Exception exception) {
                    // If any failure in registration the callback  will come here 
             }
   });
val user = User()
user.userId = <USER_ID> // userId it can be any unique user identifier NOTE : +,*,? are not allowed chars in userId.
user.displayName = <DISPLAY_NAME> // displayName is the name of the user which will be shown in chat message
user.authenticationTypeId = User.AuthenticationType.APPLOZIC.getValue() //User.AuthenticationType.APPLOZIC.getValue() for password verification from Applozic server and User.AuthenticationType.CLIENT.getValue() for access Token verification from your server set access token as password
user.password = "" // Optional, Pass the password
user.imageLink = <IMAGE_URL_LINK> // Optional, If you have public image URL of user you can pass here

Applozic.connectUser(context, user, object : AlLoginHandler {
      override fun onSuccess(registrationResponse: RegistrationResponse?, context: Context?) {
          // After successful registration with Applozic server the callback will come here
      }

      override fun onFailure(
          registrationResponse: RegistrationResponse?,
          exception: Exception?
       ) {
          // If any failure in registration the callback  will come here
           if (registrationResponse != null) {
               Log.i("ApplozicLogin", "Login as been failed:" + registrationResponse.message)
           } else if (exception != null) {
               Log.i("ApplozicLogin", "Login as been failed due to exception:" + exception.localizedMessage)
           }
       }
 })

If it is a new user, new user account will get created else existing user will be logged in to the application.

Adding additional fields in User

If you need to add some additional fields to a User object that is not a property of the existing User object then you can set the additional fields in the metadata of the User.
For eg. You need to add some fields like Department, Designation, Team etc to a User, then you can use the User metadata.

Map<String, String> metadata = new HashMap<>();
metadata.put("Department" , "Engineering");
metadata.put("Designation" , "Software Engineer");
metadata.put("Team" , "Device Team");

user.setMetadata(metadata);
val metadata: MutableMap<String, String> = HashMap()
      metadata["Department"] = "Engineering"
      metadata["Designation"] = "Software Engineer"
      metadata["Team"] = "Device Team"
user.setMetadata(metadata)

Then later you can get the data as below:

Contact contact = new AppContactService(context).getContactById(userId);

String department, designation, team = null;

if(contact.getMetadata() != null){
 department = contact.getMetadata().get("Department");
 designation = contact.getMetadata().get("Designation");
 team = contact.getMetadata().get("Team");
}
val contact = AppContactService(context).getContactById(userId)
val department: String?
val designation: String?
var team: String? = null

if (contact.metadata != null) {
    department = contact.metadata["Department"]
    designation = contact.metadata["Designation"]
    team = contact.metadata["Team"]
}

Build your UI from scratch - Authentication

Authentication is required to use the Applozic features.

Initialising Applozic SDK

You need to initialise the SDK with the Applozic App ID obtained from Applozic dashboard.

Applozic.init(context, App-ID);
Applozic.init(context, App-ID)

Creating a User

A User object needs to be initialised and then authenticated to access Applozic's features. A user object has a unique field userId which is also the only mandatory field. You can create a User object as below:

User user = new User();          
user.setUserId(userId); 
user.setDisplayName(displayName);
user.setEmail(email);
user.setAuthenticationTypeId(User.AuthenticationType.APPLOZIC.getValue());  
user.setPassword("");
user.setImageLink("");
val user = User()
user.userId = <USERID> // UserId to login the user 
user.displayName = <DISPLAY_NAME> // displayName is the name of the user
user.email = <EMAIL_ID> // You can set email id if required.
user.authenticationTypeId = User.AuthenticationType.APPLOZIC.value
user.password = ""
//user.imageLink = ""

Property

Description

userId

Needs to be unique. +,*,? are not allowed chars in userId.

displayName (Optional)

displayName is the name of the user which will be shown in chat messages. If not set, userId will be shown to other users.

email (Optional)

You can set email id if required.

AuthenticationType (Optional)

User.AuthenticationType.APPLOZIC.getValue() for password verification from Applozic server and User.AuthenticationType.CLIENT.getValue() for access Token verification from your server set access token as password

imageLink (Optional)

The url of the image that you want to display for the user. If not set, you can set a placeholder image for the user.

password (Optional)

You can leave it blank for testing purpose, read this if you want to add additional security by verifying password from your server Applozic access token .

📘

Note

If you have set a password for a user, you will need it every time you authenticate a user .

📘

Note

You can also add some additional fields in a User object that are not the property of the existing User object. Refer to this section for details.

Registering/Logging-in the user

You can Authenticate the user with Applozic using the below methods. If the user is a new user, A new account would be created for the same on the other hand if the user is an existing user, he/she will be logged in with Applozic.

Applozic.connectUser(context, user, new AlLoginHandler() {
                @Override
                public void onSuccess(RegistrationResponse registrationResponse, Context context) {
                    // After successful registration with Applozic server the callback will come here 
                }

                @Override
                public void onFailure(RegistrationResponse registrationResponse, Exception exception) {
                    // If any failure in registration the callback  will come here 
             }
   });
Applozic.connectUser(context, user, object : AlLoginHandler {
            override fun onSuccess(registrationResponse: RegistrationResponse?, context: Context?) {
                // After successful registration with Applozic server the callback will come here
            }

            override fun onFailure(
                    registrationResponse: RegistrationResponse?,
                    exception: Exception?
            ) {
                // If any failure in registration the callback  will come here
                if (registrationResponse != null) {
                    Log.i("ApplozicLogin", "Login as been failed:" + registrationResponse.message)
                } else if (exception != null) {
                    Log.i("ApplozicLogin", "Login as been failed due to exception:" + exception.localizedMessage)
                }
            }
 })

You can perform the further actions based on the callback methods. In onSuccess you could launch the chat screen for the user, onFailure you could throw some error message based on the Exception and the Response received in the callback method.

📘

Note

You need to call the connectUser method only once. However the method internally checks if the user is logged in, if he/she is already logged in you would still receive the RegistrationResponse in onSuccess callback with "User already logged in message".

If at some point you need to check if a user is already logged in, you can call the below method:

if (Applozic.isConnected(context)) {

}
if (Applozic.isConnected(context)) {
    Log.i("ApplozicUser", "User is logged in")
} else {
    Log.i("ApplozicUser", "User is not logged in")
}

📘

Have Question Or Suggestion?

You can drop us your query at [email protected]

Token

If access token validation is configured from your server then set your server generated token as the password at the time of user registration.

  • Set Authentication type AuthenticationType in LoginTask.
user.setAuthenticationTypeId(User.AuthenticationType.CLIENT.getValue());
user.authenticationTypeId = User.AuthenticationType.CLIENT.value
  • Set access token generated as a password.
user.setPassword(yourToken);
user.password = yourToken

Password update

You can use the below method to update login user password, you need to pass the old password and new password to update

String response =   UserService.getInstance(this).processUpdateUserPassword(oldpassword, newPassword);

    if(!TextUtils.isEmpty(response) && MobiComKitConstants.SUCCESS.equals(response)){
         //Password updated successfuly
      } else {
         //Password update failed
    }
val response = UserService.getInstance(context).processUpdateUserPassword(oldpassword, newPassword)

        if (!TextUtils.isEmpty(response) && MobiComKitConstants.SUCCESS == response) {
            // Password updated successfully
        } else {
            // Password update failed
        }

❗️

Note :

Call the password update method in an async task or background thread as its server call

Update User Details

You can use the below API method to update login in user details like display Name, profile image URL, user metadata

User user = new User();
 user.setImageLink("IMAGE_URL");
 user.setDisplayName("USER_NEW_DISPLAY_NAME");
 //user.setMetadata(metadata);

 UserService.getInstance(this).updateUser(user, new AlCallback() {
      @Override
       public void onSuccess(Object response) {
           Log.i("User","Update success ");
        }

      @Override
       public void onError(Object error) {
            Log.i("User","Update failed ");
        }
  });
val user = User()
user.imageLink = "IMAGE_URL"
user.displayName = "USER_NEW_DISPLAY_NAME"
//user.setMetadata(metadata);

UserService.getInstance(context).updateUser(user, object : AlCallback {
    override fun onSuccess(response: Any) {
        Log.i("User", "Update success ")
     }

    override fun onError(error: Any) {
       Log.i("User", "Update failed ")
    }
})

Get logged In userId of Applozic

Use the below setting to get the current login userId in Applozic

MobiComUserPreference.getInstance(context).getUserId();
MobiComUserPreference.getInstance(context).userId

What’s Next
Did this page help you?