Real time private chatting app using React, Nodejs, mongodb and Socket.io — Part 2

In this part, we will be Implementing Registration, uniqueness of the username before registration and Login Operation

Shashank Tiwari
9 min readMay 22, 2019

--

Originally published at https://www.codershood.info on May 22, 2019.

This is the second part of the Building Real-time private chatting app using React. In this part, you will implement below-listed features in your application,

  1. Registration.
  2. Checking the uniqueness of the username before registration.
  3. Login.
  4. Checking the Session of a user (when the user navigates to the home page).

In the first part of the series, we did the setup of React and Nodejs application. Since I have created boilerplates for Both React and Nodejs, therefore you don’t have to do the monotonous work for your self.

I assume you have cloned or downloaded the React boilerplate and Nodejs boilerplate. I highly recommend you to clone/download, If you haven’t cloned/downloaded these boilerplates already. If you use Boilerplates, your application will be less prone to mistakes.

Okay, Now install and run both the boilerplates that you have for React application and Nodejs server. I hope to this point, you are with me. And somehow if you are having any trouble let me know.

Setting Up the Authentication Page

In this section first, we will set up the authentication page. In the below Image as you can see we have Tabs for Login and Registration. If you click of Login Tab then you will see the Login form and If you click on Registration page then you will see the Registration Form.

Here we will react-bootstrap to implement the Tabs. In the container of those Tabs, we will render the Login and Registration components. The below code will do the same, open the Authentication.js file and add the below code.

Authentication.js:

Explanation:

  1. First, we imported Tabs and Tab for obvious reasons.
  2. Then we imported Login and Registration components to display them inside the Tab container.
  3. setRenderLoadingState() method will be called from the child component with the help of React Props.
  4. Lastly, we have two tabs container to show both theLogin and Registration component.

Implementing Registration Feature

Let’s start by implementing Registration feature. I don’t think I have much to talk about the importance of the registration feature. First, we’ll write the client side code. Later we will write node APIs and all code related to it.

=> So the first step is writing MarkUp, so open the Registration.js and write down the below code markup in the render() method.

Registration.js:

Explanation:

  1. Form, Form.Group,From.Controland Button components are part of the react-bootstrap library.
  2. The DebounceInput component will be used for a specific purpose, we will talk about this component in the next section.
  3. The checkUsernameAvailability() and handleInputChange() methods will update the state with respective details.
  4. The handleRegistration() will call the Make an Ajax call in order to register the new user.

To make your markup work, you will have to write some code inside your component class. Open the Registration.js and write down the below code.

=> In the below code, we will use ChatHttpServer class to register the new User.

=> The application will redirect the user to the Home Page as soon as the user finishes the registration process.

Resgistration.js:

Explanation:

  1. Let’s start from the top first, we have imported all the necessary components from third-party libraries.
  2. Then we have imported the ChatHttpServer class object.
  3. In the state object, we have two properties username and password. We will directly send this state object to the server while registration.
  4. Once the Registration is successful, then we will redirect the user to the /home page. Also, we will store the userId in local storage so that we can use it later in the application.
  5. The checkUsernameAvailability() and the handleInputChange() methods will update the keys of state object respectively.
  6. If anything goes wrong, we are showing an alert with an error message.

Forgive me for showing ugly messages. For the sake of simplicity, I have used the usual alerts, instead of fancy POPUPs.

To complete the registration process you will have to write code in Nodejs as well. Basically, writing Nodejs code will piece of a cake for you, because you don’t have much to write. Let’s get to it, Open the routes.js and add the below the route.

routes.js:

After that, you have to write a few lines of code inside the registerRouteHandler(), just to handle the request/response and call the method which just inserts the data into Database.

Add the below code, inside the route.handler.jsfile. The registerRouteHandler()will take care of the /register route.

route.handler.js:

Explanation:

  1. In the above code, you will first check the validation. If anything wrong with that, we will send the proper error code with an Error message.
  2. Then we will generate the Password Hash for user entered password.
  3. And the end if everything is valid or in more precise words if the request is valid than you will Register a user by callingregisterUser().
  4. TheregisterUser()is defined inside the query-handler.js.

Open the query-handler.js file and write down the below code. As you have figured it by now, You will just have to insert the records in MongoDB in the below code.

query-handler.js:

Explanation:

  1. In the above code, First thing you will do is return promise. By returning promise you can save yourself from callback hell, and later you can apply Async/Await on this function.
  2. After that, you will connect the MongoDB database and insert the record into the database.
  3. And that’s it. You have created a new user.

Checking for a unique username

It is very important that before registration, you check the uniqueness of username. It’s obvious that you can’t have two users with the same username.

First thing first, let’s add the Markup in Registration.js. Here you don’t have much to write, just an indicator that shows the particular username is taken.

In the below Markup, we have used the React state to hide and show the Message by using the usernameAvailablestate property of Registration Component class.

The above markup will hide/show only if you write something in your input tag.

First of all, add the below property in your state object of Registration Component class,

After that add the below code in Registration Component class, The below code will check the username uniqueness by Making an HTTP request to your Nodejs server. Open the Registration.jsand update the code of checkUsernameAvailability() method,

Registration.js:

Explanation:

  1. First, we will update the state property username, then we are calling the loadingState() method using React props.
  2. Then we will call the ChatHttpServer.checkUsernameAvailability(), which eventually make an HTTP request to check the uniqueness of username.
  3. And based on the response of the HTTP server we will set the value of the usernameAvailable property of the state.

This is not complete yet, you still have to code for your Nodejs part. Writing Nodejs routes and its helper will be the same as it was in the last section, In fact, it’s going to be identical for Nodejs routes. So first as usual open the routes.js and add the below the route.

routes.js:

Now our express route is added, let’s write a method to handle that request in the route-handler.js file. Open that file and add the below code,

route-handler.js:

If you notice we have called userNameCheck() method to check the user count of the same usernames. This method will basically check the counts of the given username and returns that count to the callee.

Open the query-handler.js and add the below code, in the below code you just a run a MongoDB query and return the response to caller method.

query-handler.js:

Now, this completes your Checking for a unique username features. Congrats, you have added one more feature to your application.

Implementing Login Feature:

Implementation of Login feature is going to pretty easy and almost identical to above-implemented features. First, we will start with Markup, then component and in the end, we will write some NodeJs just like we did in the last two sections.

The below markup will render the Login form, which will have two fields username and password. Open the Login.jsand add the below code in render() method,

Login.js:

Explanation:

  1. Form,Form.Group,From.ControlandButtoncomponents are part of the react-bootstrap library.
  2. handleInputChange()methods will update the React state with respective details.

Now we will complete the rest if code i.e. left in the Login component. The below code will handle the Login form submission. Open the Login.js and write down the below code,

Login.js:

Explanation:

  1. Let’s start from the top first, we have imported all the necessary components from third-party libraries.
  2. Then we have imported theChatHttpServerclass object.
  3. In the state object, we have two properties username and password. We will directly send this state object to the server while Login.
  4. Once the Login is successful, then we will redirect the user to the/homepage. Also, we will store the userId in local storage so that we can use it later in the application.
  5. ThehandleInputChange()methods will update the keys of state object respectively.

Let’s write the Nodejs part, Here we will do three things First we will add the route. Second, we will add a method to handle the request/response of the route and at the end method to perform the Login.

So let’s just add the route, open the routes.js. and add the below route.

routes.js:

The/loginroute is added to its respective file, now let's write the method to handle the response to the/login route. Open the route-handler.js and add the below code,

route-handler.js:

Explanation:

  1. There is a lot of things going on here, First, we will do the validation if everything goes fine, then we will actually fetch the result from the database and verify it with the data sent from the Angular application.
  2. After validation and stuff, we will fetch the record of the user by using his/her username.
  3. If you get a result from the database using the username, then go ahead compare the password of a user by usingcompareHash() method.
  4. After comparing the password, based on the result you will make the status of the user online.

Checking User’s Session

It is very critical to check the session of the user before allowing the users to chat and read messages. To check the session of the user, we will make an HTTP call. Whenever a user visits the home page of the application we will check the session.

=> Here we will use React’s lifecycle method i.e. componentDidMount(). In this method, we will make an HTTP call to check the session of the user. Open the Home.js and write down the below code,

Home.js:

Explanation:

  1. In this method, first, we will call thesetRenderLoadingState()method to show a loading screen while we make check the session of the user by making an HTTP call.
  2. To check the session of the user, we need the user id of that user. We can get the user ID usinggetUserId() method, which is defined inside theChatHttpServer service.
  3. Once we will get the user ID then we can call theuserSessionCheck() method, this method we will make an HTTP call to check if the user is logged in or not.
  4. If the response says, User is logged in then we will make set the username in our component state.
  5. If the user is not logged in then we will redirect the user to the Home page.

Now let’s add the route for session check service in the routes.js file. Here we will check the online status of the user, and based on the online status we will determine the session of that user. So add the below route in the routes.js file.

routes.js:

As always, we have to write method inside the route-handler.js file to handle the response for the /userSessionCheck route. As you can see, in this case, we are calling userSessionCheckRouteHandler() to handle the response for the /userSessionCheck.

Open the route-handler.js and add the below code,

route-handler.js:

Explanation:

  1. In the above code, First, we will check for the userId validation. If the validation fails, we will send the user not found a response.
  2. If validation passes, then we will check the online status of the user in the Database by using userId.
  3. And depending on the online status we will send the response to Angular Application.

Now to check the online status in the Database you will have to write userSessionCheck() method in QueryHandler class. This method will basically check the online status by executing a MongoDB Query.

Open the query-handler.js file and add the below method,

query-handler.js:

And I assume the above code needs no explanation since you are just executing a MongoDB query and returning a Promise.

That’s it.

Conclusion

Now let’s conclude this part by recapping what we did in this part.

  1. We downloaded the React boilerplate and Nodejs boilerplate and using these created our application.
  2. We implemented a Registration feature.
  3. We implemented a feature to check the uniqueness of the username before registration.
  4. We added Login functionality in our application.
  5. In the end, we added a feature to check the session of a User.

The complete source code is available on Github.

In the next part of the series, we will connect our React application to the socket and implement the Realtime chat list for the application. So stay tuned it’s going to be more interesting.

Feel free to share your opinions in the below comments box. If you like this article do share it and leave a clap.

--

--