RadStudio BaaS with Kinvey

delphi-plus-kinvey

Introduction to BaaS

BaaS stands for Back-end As A Service.

In software architecture the terms ‘Back End’ and ‘Front-End’ are used to describe different layers of a software solution. The back end layer of a solution is responsible for handling data, where as the front end is responsible for presenting that data to the end-user.

These distinctions are often an over simplification as many software solutions have several such layers in which the data, logic, or presentation are handled. Due to this simplification the term Back End is now commonly used to refer to logic layers also.

One of the earliest reasons for the separation of data, logic and presentation in a software solution was processing capacity. In early unix style systems, a central mainframe computer could be used to process large amounts of data, while smaller and less capable systems offered user access to that mainframe.

This same reason stands true today. The two tier Back-End / Front-End paradigm is often used as the architecture for apps on mobile devices such as cell phones or tablets. Mobile devices are limited in their processing and storage capacity, and so it is common to move the heavy lifting of data processing, or business logic to a more capable system.

This leaves software developers with a problem. In order to sustain their mobile app, developers require a back end system with sufficient processing capabilities to service all of the app users, but such systems require expensive servers, air conditioned hosting facilities, monitoring technologies, uninterruptible power supplies, service engineers, redundancy and backup for sensitive data. Running your own back end, depending upon the size of your customer base (or user base), can become a significant overhead cost.

This is where BaaS comes in. Suppose, instead of purchasing one or many expensive servers, the hosting facilities, and staff to service it, you could contract that out to a third party. Well, you can. There are many BaaS providers which offer a software platform for you to build on which is hosted on their hardware infrastructure.

Such providers are able to consolidate the costs of running your back end, with the cost of running the back end of their other customers. This helps to keep their costs low, and therefore, they are quite competitively priced, and can be a great saving on running your own dedicated infrastructure.

RadStudio comes with several components for working with BaaS providers, including some excellent REST components for working with providers for which there aren’t already components installed within the IDE. There are also specific components for two service providers, Kinvey and Parse, with provisioning to add additional providers if required.

In this article, we’re going to get started using Kinvey as our BaaS provider, though much of the information contained within should be relevant to other providers also.

We’ll be looking at user authentication with Kinvey by building an authentication application step-by-step using RadStudio.

Signing up to Kinvey.

Kinvey, as with many cloud-based service providers, offer a multi-level pricing model based on the volume of service you consume. The entry level of this service is provided for free, enabling you to build your application with no service cost, and then to move up to a paid model as your application is released and your user base (hopefully) increases.

Visit http://www.kinvey.com and click on the “Login / Signup” button located top-right on the page…

ResizedImage600438-01

You’ll be presented with the Signup options (left) and Login options (right). Go ahead and enter an email address and your choice of password, then click the “Signup” button to begin the sign-up process.

ResizedImage600437-02

On the next screen, Kinvey asks you to identify yourself as an Individual or Business. Note: I’ve always selected “Individual” as I don’t require an SLA for this application, and I would guess the next screen will involve payment options if you do. For the purposes of this tutorial, Individual should suffice, and I’m sure Kinvey will be happy to upgrade you to a business contract later should you need it.

Go ahead and select the most appropriate option…

ResizedImage600407-03

On the next screen, you’ll be prompted to provide a name for your application. This name is used to identify the application to Kinvey and therefore need not be the actual application name, a code-name will suffice.

You’ll also be asked to specify the platform that you’re developing for. As RadStudio is a mutli-platform development tools, I’m going to select “Rest API”, it doesn’t appear to alter the functionality of Kinvey at all, and so this question appears to be data collection for Kinvey marketing purposes.

Go ahead and populate this information and click the button to continue.

ResizedImage600407-04

You’ll now be presented with the Kinvey Console. This is the screen that you’ll see when you login to Kinvey in the future, however, as this is the first time you’ve seen it there is an overlay to indicate where you’ll find certain important features.

Before we can use the Kinvey components in RadStudio, we’ll need to grab some important key information from Kinvey about our application. Click on the “Addons” button (top-left)…

ResizedImage600438-05

From the menu which is presented, select “settings”…

ResizedImage600438-06

You’ll now be presented with the key values that you’ll need in order to consume the Kinvey services. Make a note of the following:

  • App Name :- As you provided
  • Master Secret :- This is a unique key relating to your Kinvey account.
  • App Secret :- This is a unique key relating to your Kinvey application.
  • Password :- Not displayed on this page, it’s the password you provided during sign-up.
  • Username :- As you provided during sign-up, it’s likely your email address.

ResizedImage600437-07

You now have all of the pieces of information required to connect to your Kinvey hosted BaaS through RadStudio.

User Authentication

User authentication is a good candidate for using BaaS because it makes use of a centralized database containing the user accounts and credentials.

Before we can write an application to authenticate a user, we must first have a user account. Many applications therefore provide a sign-up option, as well as a login option. Our application doesn’t exist yet, and so neither the sign-up or login options exist. It might seem obvious to begin by writing a sign-up function first, then create an account with it, and finally write the login function to test the account.  In fact, we’re only going to write the login function.

The chicken and the egg? We need an account to login to before we can test our login function. Thankfully, Kinvey provide a convenient interface to create user accounts. Lets use that to create a user first.

Creating a user

Log in to your Kinvey account, and from the menu, select “Core / Users”…

ResizedImage600406-08

If this is the first time you’ve been to the user accounts page, Kinvey will provide a helpful hint on where to begin.
Click on “Add User” to create a new user account…

ResizedImage600406-09

You will now be presented with a form to complete, to provide the basic details of the user account that you wish to create.

I’m going to create a user named “John Doe” with a username of “johndoe” and a password to match the username…

ResizedImage600428-10

Having clicked the “Create User” button, you’ll see the user is given a unique identifier and is presented as follows…

ResizedImage600428-11

Now we’re ready to begin writing an application which can authenticate against this user account…

Create a new mobile application with RadStudio.

Start by creating a “New FireMonkey Mobile Application – Delphi” from the menu…
(In newer versions of RadStudio this has been changed to “New Multiplatform Application – Object Pascal”)

ResizedImage600360-12

From the application types presented in the next dialog, lets start with a blank application…

ResizedImage600456-13

Now as a matter of simple good practice, select “File -> Save All” and save both the default form that was created, and the project file….

14

The first thing you’ll be asked to save is the form and the code unit behind it….

ResizedImage600480-15

After saving the form, a dialog appears for saving the project file. The name you give here will become the name of your application.

ResizedImage600480-16

Back on the main form in the designer, search the toolbox (bottom right) for the “TKinveyProvider component, and then double click on it to drop it onto the form…

ResizedImage600361-17

Earlier, I asked you to make a note of five pieces of information; MasterSecret, AppSecret, AppKey, Username and Password.
Click on the TKinveyProvider component on the main form to ensure it’s selected, and then look at the properties in the object inspector (bottom left). You’ll notice there are properties for each of the collected pieces of information, go ahead and populate these with the values that you noted earlier.

(Where I’ve entered “W,X,Y and Z” and the Username property)…

ResizedImage600361-18

Next, drop a TBackendUsers component onto the form, and note that the “Provider” property is correctly set to “KinveyProvider1″ automatically…

ResizedImage600361-19

You now have all of the components that you’ll need on the form to authenticate, but no user interface to enable that functionality.

Drop two TLabel controls onto the form…

ResizedImage600361-20

Adjust the ‘Text’ property of each of the labels. The first should read “Username:’ and the second ‘Password:’.

You can also take this opportunity to investigate the other properties of the labels, for example, the TextSettings.HorizAlign property can be set to “Trailing” which adjusts the text to align from the right, which will aid you in positioning the labels as desired.

Drag and position the label controls and play with the alignment settings until you have them as desired…

ResizedImage600361-21

Now we need edit boxes for the user to enter their credentials.

Drop two TEdit controls onto the form…

ResizedImage600361-22

We’ll need to reference these edit boxes in code later, so lets also give them convenient names.

Name the first “edtUsername” and the second “edtPassword”…

ResizedImage600361-23

We also want the password edit box to hide the characters which are typed into it. You wouldn’t want someone looking over your shoulder to read the password as you type it, right? So click on the edit named “edtPassword” and set it’s “Password” property to true.

ResizedImage600360-24

Finally, we need some way to initiate the action of logging in. I find a button usually does the trick!

Drop a TButton on your form and set it’s “Name” property to read “btnLogin” and set it’s “Text” property to read “Login”….

ResizedImage600360-25

There, we have all the components needed to authenticate a user against a Kinvey user database, and we have all of the visual controls necessary to provide a user interface to login.

Something is still missing though, we need to provide the code which does the actual work. Double click on your button “btnLogin” and the IDE will bring you to the OnClick event handler for the button…

ResizedImage600361-26

Alter the text to match the image below (text included so you can copy paste…)


procedure TForm1.btnLoginClick(Sender: TObject);
var
  UserAccount: TBackendEntityValue;
  ID: string;
begin
  try
    BackendUsers1.Users.LoginUser(edtUsername.Text,edtPassword.Text,UserAccount,nil);
    ID := UserAccount.ObjectID;
    ShowMessage('Success!: '+ID);
  except
    on E: Exception do begin
      ShowMessage('Login failed.');
    end;
  end;
end;

ResizedImage600361-27

Reading this code from the line “procedure TForm1….”

  1. The first line is the procedure header, this is required to tell the compiler where the OnClick handler begins, and how to call it. It is generated for you by the IDE.
  2. The next line is where we state that we need two variables (using the “var” keyword)
  3. The next line defines a UserAccount object which will be given to us by our call to the LoginUser() method later..
  4. Then we need a variable to hold the ID of the user after login – this information will be useful when we expand the code later.
  5. Within the begin..end keywords provided by the IDE, we have a try..except..end block. This catches errors (like a failure to login).
  6. BackendUsers1.Users.LoginUser() is a method provided by the TBackendUsers component that we added to our form. This is the method that does the work of calling the TKinveyProvider, which bundles up the request and sends it off (with your appkey, appsecret etc, etc) to Kinvey. It then receives a response from Kinvey indicating the success or failure of the authentication request. We pass in the values of the Username and Password edit boxes, and we get back an object named “UserAccount” (if the call succeeds).
  7. If the authentication is a success, we copy the ID from the “UserAccount” object, and then show a message saying “Success!:” followed by the ID (which should match the ID seen when we created the user account earlier).
  8. If the authentication fails, we show a message saying ‘Login failed.’

Now it’s time to test this login function. Rather than deploy the application to a mobile device, at this time, it’s convenient to test run the application using windows.

Press F12 to get back to the form designer, and add “Win32″ as a deployment target…

ResizedImage600359-28

29

Now you’re ready to test the Authentication system.

Press F9 or click on one of the “Run with debugging” or “Run without debugging” buttons…

ResizedImage600361-30

Try entering username: “johndoe” password “johndoe” as we set for the user earlier, and then click “Login” button…

31

Note that the application will not look the same when running under windows as it will when deployed to a Mobile device. The control styles will be altered to suite the target.

There is just one more step. You should ALWAYS test what happens when the application user does something that you weren’t expecting when writing the application, so go ahead and test to see what happens if you enter incorrect details for login.

If you run this test within the debugger, you may encounter additional error messages before the “Login Failed” dialog pops up – the debugger is catching the failure early and warning you about it, just keep clicking “OK” until you get to the dialog you’re expecting.

Thanks for reading!

Facebooktwitterredditpinterestlinkedintumblrmail

Leave a Comment