User login and registration using nodejs and mysql with example

User login and registration using nodejs and mysql with example

User login and registration using nodejs and mysql with example

In this tutorial, I am going to create simple email and password login authentication and register a user using nodejs and mysql.

I will save simple password in mysql database but this is not good practice for security reason so in next tutorial, you will know the use of BCrypt module of Node.js to encrypt passwords.

This tutorial will explain only how to save a record in mysql table and how to check email exist or not in the table with given password.

To handle post parameters of Http request in Node.js, we use Body-Parser module.

Step1: Table and directory structure

In first step, create a "users" table in the database by running following command in phpmyadmin or in mysql shell :

  1. CREATE TABLE `users` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `name` varchar(255) NOT NULL,
  4. `email` varchar(255) NOT NULL,
  5. `password` varchar(255) NOT NULL,
  6. `created_at` datetime NOT NULL,
  7. `updated_at` datetime NOT NULL,
  8. PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1

Now i will have to setup directory structure in following way :

  1. ├── controllers
  2. │ └── authenticate-controller.js
  3. │ └── register-controller.js
  4. ├── node_modules
  5. ├── config.js
  6. ├── index.js
  7. └── package.json

In Node.js package.json file is used to install all the dependencies.

{
  "name": "login",
  "version": "1.0.0",
  "description": "login authentication",
  "main": "index.js",
  "dependencies": {
    "body-parser": "^1.17.1",
    "express": "^4.14.1",
    "jsonwebtoken": "^7.3.0",
    "mysql": "^2.13.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Step 2: Config.js to configure database connectivity

In this step, i will create mysql connection to work with database.

config.js
  1. var mysql = require('mysql');
  2. var connection = mysql.createConnection({
  3. host : 'localhost',
  4. user : 'root',
  5. password : '',
  6. database : 'test'
  7. });
  8. connection.connect(function(err){
  9. if(!err) {
  10. console.log("Database is connected");
  11. } else {
  12. console.log("Error while connecting with database");
  13. }
  14. });
  15. module.exports = connection;
Step 3: index.js

Now start with index.js file that is entry point of the application.

index.js
  1. var express=require("express");
  2. var bodyParser=require('body-parser');
  3. var app = express();
  4. var authenticateController=require('./controllers/authenticate-controller');
  5. var registerController=require('./controllers/register-controller');
  6. app.use(bodyParser.urlencoded({extended:true}));
  7. app.use(bodyParser.json());
  8. /* route to handle login and registration */
  9. app.post('/api/register',registerController.register);
  10. app.post('/api/authenticate',authenticateController.authenticate);
  11. app.listen(8012);
Step 4: Create Register Controller

In this step, I will register a user in database so that i can login in the application with register user.

controller/register-controller.js
  1. var connection = require('./../config');
  2. module.exports.register=function(req,res){
  3.     var today = new Date();
  4.     var users={
  5.      "name":req.body.name,
  6.      "email":req.body.email,
  7.      "password":req.body.password,
  8.      "created_at":today,
  9.      "updated_at":today
  10.     }
  11.     connection.query('INSERT INTO users SET ?',users, function (error, results, fields) {
  12.      if (error) {
  13.         res.json({
  14.             status:false,
  15.             message:'there are some error with query'
  16.         })
  17.      }else{
  18.          res.json({
  19.             status:true,
  20.             data:results,
  21.             message:'user registered sucessfully'
  22.         })
  23.      }
  24.     });
  25. }

In above code, i run a simple insert query of mysql to save user details in database with created date using date function.

Step 5: Create Authenticate Controller

In this step, i will validate user credentials.

controllers/authenticate-controller.js
  1. var connection = require('./../config');
  2. module.exports.authenticate=function(req,res){
  3.     var email=req.body.email;
  4.     var password=req.body.password;
  5.     connection.query('SELECT * FROM users WHERE email = ?',[email], function (error, results, fields) {
  6.      if (error) {
  7.          res.json({
  8.             status:false,
  9.             message:'there are some error with query'
  10.             })
  11.      }else{
  12.      if(results.length >0){
  13.          if(password==results[0].password){
  14.                 res.json({
  15.                     status:true,
  16.                     message:'successfully authenticated'
  17.                 })
  18.          }else{
  19.              res.json({
  20.                  status:false,
  21.          message:"Email and password does not match"
  22.          });
  23.          }
  24.     
  25.      }
  26.      else{
  27.      res.json({
  28.          status:false,    
  29.      message:"Email does not exits"
  30. });
  31.      }
  32.      }
  33.     });
  34. }

In above code, i check first if email exists in the database and then check password.

Before going with testing with the help of postman or other tools, start server from the command prompt first :

node index.js

Click here to know how to store encrypted password using bcrypt module in Node.js

Hashing passwords with Bcrypt and node.js

Phone: (+91) 8800417876
Noida, 201301