3. Create account, improve auth process with token based security. 
Continuation of the authentication system by adding a user with a unique token.

Topics in this video
Create-account function in Node.js (00:55)
Breakdown of API tasks (01:46)
Checking for unused email in DB (03:54)
Insert new user to the database (05:32)
Setting up frontend (06:35)
Assigning API to the form (08:10)


Hello and welcome to the third episode of AppDrag Academy. I'm Mike Sabbah, and this episode will be a continuation of the previous one, where we started working on our authentication system.

In this episode, we're going to build a create account page that will add the new user's information to our database.

I'm going to open the project we created last episode, and as always, begin with the backend.

Creating a New Account API Using Node.Js
Now, our table is already set, so we dive right into the API. Before anything, I'm going to open my notepad for a minute, and copy the API key.

(Full source code of the function is found at the completion of the scripting section.)

Today's API will be created in Node.js, and here are few things you should know. Node.js uses modules, which are essentially functions included in the application. Some come standard with Node, others need to be installed, which we'll do shortly, but ultimately, you can just go ahead and create your own, which is exactly the way this function begins. By default, it returns "hello from cloudbackend", but we're going to replace that for our own callback.

"Exports" is Node's way of telling the application that you will be using this guy, and "Handler" is the name we gave it right up here. And this module includes three parameters. We're going to focus on "event" and "callback". Event is an object that gathers information from our caller, which, in our case, is the Posted parameters. Then our function will take that information, process it with some logic, send the results back to our caller using the third parameter, which is the callback.

Breakdown of the Five API Tasks
The module we're going to write will do for us the five things we need for our new user to be created.
 - First off, it's going to read our parameters and assign them variables.
 - Second, it'll search the database to make sure the email entered hasn't yet been used.
 - Third, a new and unique token will be generated for our new user.
 - Fourth, it'll insert the values into the table, thus creating our new user.
 - And finally, it will return an object which our browser will use to know that we are indeed securely logged in, allowing     us access to the client area.

Let's put in our input parameters first. We have first name, last name, email, phone, and password.

NPM Library Installation
What we need, before coding anything, is to install a couple of packages that'll be required in our API.

We open the library manager, and we find the first one that we're going to include, which is the AppDrag Cloudbackend. Let's visit the documentation for this package on NPMJS, so we can get the initialization specs.

We're going to need the API key and the app ID. So for the API key, we copied it a few moments ago in our notepad, so let's just pull it out of there, and for the app ID, it's found in the upper left corner and in the URL as well.

The second package we're going to require is the UUID, which will generate for us the unique token for our user.  
Click the plus to install, and check it off to include it.  You can visit the NPM page if you wish, but we're just going to require it right here.

Now, let's step into the handler which will be called upon every API call, and start it off with assigning variables to our values.  In order to ensure that a null parameter returns an empty string, and also to ensure single quotes are escaped, hence avoiding SQL Injections, I'm going to add a function at the end of our script called cleanVar, and call it by each of my parameters. 

Checking for unused email in the Database
In order to avoid multiple users using the same email address, we'll need to  ensure that this email address isn't already in our database.  So to do that, we're going to run a search using the SQL select query from the NPM documentation.

However, in order to ensure that that happens before the insertion of our values, and in order to avoid placing callbacks within callbacks, which is also known as callback hell, we can, since Node.js version 8.10 and above, use the awesome async/await feature in our code.  What that means is that as long as the function we're in is asynchronous, the awaited function will first have to complete before going to the next part of the code. 

To achieve that, we add "async" to our function, and before the email verification function, we simply type "await." 

We're going to replace this query for the query that we need which is to select from our users where the email column contains our email variable.  Once it ran, then we take our response and analyze it using simple logic. The response is a JSON, so once the object parsed, we check to see if it's not null, which would then mean that the email already exists.  And since it does, we need to return an object with an error value of "Email already used" and then stop the execution of the account-creation process.

And in the event that we haven't entered the "if" statement, we enter the "else" statement where we run through the next three steps.  So let's bring those three comments into this block real quick.  And let's clean this up a bit.

Creating a Unique User ID and Insertion into the Database
First thing we're going to do here is create our user his token ID by creating a var that will call the UUID function. And now we move on to the insertion of the variables to the table.  So let's go back to the NPM documentation, and this time copy the SQL raw query. 

Once again, we're going to await this function.  We're going to replace the query for an SQL variable, and write it out right above.  This one will be an insert query into our users table.  Plug in the columns and values.  Just make sure to escape the string quotes by concatenating your variables. 

We move on to the response object that we will return, which will contain 2 keys; the email and the new token.

And we're done!  So before we move onto the front end, let's just first try it out.  I'm going to try first the email address of the user I entered earlier, which was ms@mail.com.  And if we coded properly, we should get the error, which we do!  And if we put in an unused address, we get a success, as well as the email and token object. 

Let's take a look at the table, and there's our user with his token.

Source Code for the Node.Js API

Frontend Development
So now, we move on to the front end.

We're going to add a new page called createAccount, and this time, we're going to remove the header and footer, as well as the menu visibility.

Let's build a nice stylish form.

All right, let's just change some placeholders.  This last one is the password confirmation field, and the way to activate that is by going to the validation of the actual password field and selecting the value match of the Confirm Password field.

And now, the button.  So Action > Cloud Backend, enable the trigger, select our API, and we match the sources to the parameters. What we do, at this point, is enable the JavaScript so we could plug in some logic based on our response; if the email entered already exists or if it was successfully added to the table.

So first off, let's parse the response, as it's a JSON, and now the IF; object.payload.error is equal to "email already used", then alert that the email already exists.  Else, and now we add the email and token to the local storage. Now that they're stored, we could redirect to the Client-Aarea.html
Hit save.  And save one more time.  

Now, let's go back to our login page.  I'm going to add a link below this form that will redirect the new user to the create account page.  

Save and preview.

And now we fill out the form.  Let's put in the same email address that was put in earlier, just to see the error handling.  And there is our alert.  Let's change this email real quick.  And here we are, redirected to our client area.

Other episodes

► 1. Create your first database and API function.

► 2. Create an authentication system

► 3. Create an account form.

► 4. Add a Forgot Password function and an updatable account details page

► 5. List dynamic data from the db and display a detail page for a particular item of the list.

► 6. Event Reservation function, email template with variables, send.