Node Guide

Menu
Menu

Creating a User Login for the Web Application

With the registration set up we'll now look at how user's can login to the CMS.

Setting up the controller's loginUser method

In the src/controllers/logincontrollers.ts file, add the following code to define the loginUser method:

SNIPPET: src/controllers/logincontrollers.ts

In the above code, we define the loginUser method, which handles the login functionality.

Exporting the loginUser Method

Make sure to export the loginUser method by adding the following line of code at the end of the logincontrollers.ts file:

SNIPPET: src/controllers/logincontrollers.ts

Exporting the method allows us to import and use it in other parts of our application.

We have now added the loginUser method to handle user login functionality. Next we need to setup the login routes.

Adding the login Routes

In the src/routes/loginroutes.ts file, we need to define two routes:

SNIPPET: src/routes/loginroutes.ts

These two routes do the following:

The GET route at /login:

The POST route at /login:

By defining these routes, we can handle the rendering of the login view and the submission of the login form separately. The GET route displays the login form, and the POST route processes the form submission and handles the login functionality.

Building the Login View

Create a EJS view to allow user's to login at src/views/login.ejs.

src/views/login.ejs

We should now be able to test the login at localhost:3000/login.

Although correct login details will work we need to add error messages for when a login should be denied. At the moment if incorrect details are entered the user just get redirected to the login page.

Next: Login Error Messages