Showing posts with label MySQL. Show all posts
Showing posts with label MySQL. Show all posts

Tuesday, November 17, 2015

Registration and login application using Express.js

In this post I am going to show how to create a simple registration and login form using Express.js, a web application framework of Node.js.

I used MySQL to store the data.

BCrypt module of Node.js to encrypt passwords.

Body-Parser module of Node.js to handle post parameters of Http requests.

Below is my Node.js code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// bcrypt
var bcrypt = require("bcrypt");

// body-parser
var bodyParser = require("body-parser");
var urlEncodedParser = bodyParser.urlencoded({extended: false});

// express
var express = require("express");
var app = express();

//mysql
var mysql = require("mysql");
// connect strings for mysql
var connection = mysql.createConnection({
 host: "localhost",
 user: "root",
 password: "somePass",
 database: "mysql"
});

// connecting ......
connection.connect();

// requesting express to get data as text
app.use(bodyParser.text());

// using express for post method
app.post("/somePage", urlEncodedParser, function(request, response) {
 if(request.url!="/favicon.ico") {
  if(request.body.regOrLogin=="Register") {
   bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(request.body.pwd, salt, function(err, hash) {
     var body = request.body;
     var date = new Date();
     var currentDate = date.getFullYear()+"-"+date.getMonth()+"-"+date.getDay();
     var postVars = {username: body.username, password: hash, dob: body.dob, reg_date: currentDate};
     // insertion into MySQL
     connection.query("INSERT INTO REG_NODEJS set ?", postVars, function(err, result) {
      if(err) throw err;
     });
    });
   });
   console.log("user registered");
   response.sendFile( "/js/nodejs/folder1/regSuccess.html");
  } else if (request.body.regOrLogin=="Login") {
   var  body = request.body;
   console.log(body.username+": username");
   connection.query("SELECT * FROM REG_NODEJS WHERE username='"+body.username+"'", function(err, res, fields){
    if(err) { 
     response.sendFile( "/js/nodejs/folder1/unauthorised.html");
    } else {
     bcrypt.compare(body.pwd, res[0].password, function(err, res) {
      if(res) {
       console.log("authorised user");
       response.sendFile( "/js/nodejs/folder1/authorised.html");
      } else {
       console.log("not an authorised user");
       response.sendFile( "/js/nodejs/folder1/unauthorised.html");
      }
     });
    }
   });
  }
 }
});

app.listen(3000);

My HTML documents:

HTML for registration:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Josefin+Slab">
<style>
body { 
 font-family: 'Josefin Slab';
 font-size: 35px;
 color:white;
 background-color: #007a99;
}
table {
 font-size:30px;
 position:relative;
 bottom:-10px;
}
</style>
</head>
<body>
<center>
<h1>Register</h1>
<p>Enter your username and password</p>
<table>
<form action="http://localhost:3000/somePage" method="post">
<tr>
<td>Username</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td>Date of birth:</td>
<td>
<input type="date" name="dob"/></td>
</td>
</tr>
<tr>
<td align="center" colspan="2"><input type="submit"value="Register" name="regOrLogin"/></td>
</tr>
</form>
</table>
</center>
</body>
</html>

Rendering:













Objective here is basically to let a user enter data in this form and once the user clicks Register, the data will be saved into MySQL database and a success HTML page along with Login form is shown.

Registration success and Login form HTML:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Josefin+Slab">
<style>
body {
 font-family: "Josefin Slab";
 font-size: 35px;
 color: #cc9900;
 background-color: #00ff99;
}
.class1 {
 width:200px;
 height:30px; 
 border-radius: 60px;
 background-color: #ff3300;
 color: white;
 font-size:20px;
}
table {
 font-weight: bold;
 font-size: 25px;
}
p{
 font-weight: bold;
}
</style>
</head>
<body>
<center>
<h1>Registration Successful</h1>
<p>Login below</p>
<table>
<form action="http://localhost:3000/somePage" method="post">
<tr>
<td>Username: </td>
<td><input type="username" name="username"/></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Login" name="regOrLogin" class="class1"/>
</tr>
</form>
</table>
</center>
</body>
</html>

Rendering:












Once user enters data and clicks submit in registration form, one will be navigated to the registration success form, as shown above.

User can login with the credentials entered at the time of registration.

Upon entering correct credentials, the user will be navigated to the page which shows the user is an authorized one.

Login success HTML:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Josefin+Slab">
<style>
body {
 font-family: "Josefin Slab";
 font-size: 45px;
 font-weight: bold;
 color: white;
 background-color: #9966ff;
}
h1 {
 position:relative;
 bottom:-50px;
}
</style>
</head>
<body>

</body>
<center>
<h1>voila un utilisateur autoris&#232;</h1>
</center>
</html>

Rendering:






If the user enters wrong password, user will be navigated to login failure HTML.

Login failure HTML:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Josefin+Slab">
<style>
body {
 font-family: "Josefin Slab";
 font-size: 45px;
 font-weight: bold;
 color: white;
 background-color: #ff0000;
}
h1 {
 position:relative;
 bottom:-50px;
}
</style>
</head>
<body>

</body>
<center>
<h1>pas un utilisateur autoris&#232;</h1>
</center>
</html>

Rendering:







The user gets the above message page when the login credentials are wrong.

Process:

User enters data into registration HTML as below and clicks Register button.













The request in the form goes to Node.js server and Node.js is written in Express here. It takes the post request and inserts the data into MySQL.

My Node.js code in Express that facilitates Registration and data insertion in MySQL:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
if(request.body.regOrLogin=="Register") {
   bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(request.body.pwd, salt, function(err, hash) {
     var body = request.body;
     var date = new Date();
     var currentDate = date.getFullYear()+"-"+date.getMonth()+"-"+date.getDay();
     var postVars = {username: body.username, password: hash, dob: body.dob, reg_date: currentDate};
     // insertion into MySQL
     connection.query("INSERT INTO REG_NODEJS set ?", postVars, function(err, result) {
      if(err) throw err;
     });
    });
   });
   console.log("user registered");
   response.sendFile( "/js/nodejs/folder1/regSuccess.html");
  }

In the above code I have used body-parser module to get username, password and date of birth from post request of registration HTML.

I used mysql module to insert data into MySQL database.

Before inserting password directly I used bcrypt module to hash the password and passed the hash to the database for password security.

Once user clicks register below happens:










The redirection is handled by Express of course, I used the below code to redirect from registration page to login page.


response.sendFile( "/js/nodejs/folder1/regSuccess.html");


This is where my regSuccess html is present.

Upon receiving the reSuccess page, the user can enter the credentials entered in the registration as below and click Login.











Once the user clicks enter he will be navigated to either success or failure forms based on the credentials entered.

I used the mysql module again to validate the parameters entered by the user.

I used bcrypt module once again in login part to convert the password entered by user in login with the hash in the MySQL database.

Record in MySQL database:








Below is the code containing selecting the password from MySQL and Bcrypt password comparision.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
else if (request.body.regOrLogin=="Login") {
   var  body = request.body;
   console.log(body.username+": username");
   connection.query("SELECT * FROM REG_NODEJS WHERE username='"+body.username+"'", function(err, res, fields){
    if(err) { 
     response.sendFile( "/js/nodejs/folder1/unauthorised.html");
    } else {
     bcrypt.compare(body.pwd, res[0].password, function(err, res) {
      if(res) {
       console.log("authorised user");
       response.sendFile( "/js/nodejs/folder1/authorised.html");
      } else {
       console.log("not an authorised user");
       response.sendFile( "/js/nodejs/folder1/unauthorised.html");
      }
     });
    }
   });
  }

The above example is just a simple way of showing how one can use various modules of Node.js.

One can download the code from GitHub.

Suggestions are well appreciated and Happy learning.

Wednesday, November 11, 2015

Node.js with MySQL

In this post, I am going to put forward the approach to save data we sent by a HTML to Node.js server into MySQL database. 

Simple HTML form:

I created a simple HTML form that accepts username and password and on click of submit, sends the data to node.js server as post parameters.

Here is my HTML:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<html>
 <head>
 <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Josefin+Slab">
 <style>
  body {
    font-family: 'Josefin Slab';
    font-size: 30px;
    color:white;
    background-color:#5882FA;
   }
  table {
    position:relative;
    bottom:-10px;
   }
 </style>
 </head>
 <body>
  <h1 style="text-align:center;">Form to save data to MySQL</h1>
  <p style="text-align:center;font-weight:bold;">Enter the text and click submit.</p>
  <form action="http://localhost:2000/requestServer" method="post" align='center'>
   <table align="center" style="font-size:30px;">
    <tr>
     <td>User Name:</td> <td><input type="input" name="userName"/></td>
    </tr>
    <tr>
     <td>Password :</td> <td><input type="password" name="pwd"/></td>
    </tr>
    <tr><td colspan="2" align="center"><input type="submit" value="submit"/></td></tr>
   </table>
  </form>
 </body>
</html>

Rendering:









My Node.js code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
var http=require("http");
var mysql = require("mysql");
var postDataObject;
//connection to mysql
var connection = mysql.createConnection({
 host: "localhost",
 user: "root",
 password: "somePass",
 database: "mysql"
});
connection.connect();

http.createServer(function(request, response) {
 request.on("data", function(postVars) {
  var dataFromPost = "";
  if(request.url!="/favicon.ico") { 
   var dataFromPostTemp = "";
   dataFromPost+=postVars;
   var userName = dataFromPost.split("&")[0].split("=")[1];
   var password1 = dataFromPost.split("&")[1].split("=")[1];
   var date = new Date();
   var formattedDate = date.getFullYear()+"-"+date.getMonth()+"-"+date.getDay();
   postDataObject = {username: userName, password: password1, date: formattedDate};
   connection.query("insert into users_nodejs set ?", postDataObject, 
   function(err, result) {
    if(err) throw err;
   });
  }
 });
 request.on("end", function() {
  response.writeHead(200, {"Location":"e:/js/nodejs/page1.html"});
  response.write("<p style='color:red;text-align:center;font-size:30px;'>A Node JS Server</p>");
  response.end();
 });
}).listen(2000);
console.log("le succès de démarrage du serveur");

MySQL code:

To acquire node module mysql, one has to use:



1
var mysql = require("mysql");

Once we have got mysql module, we have to pass host, username, password and database name to createConnection of mysql instance as below.


1
2
3
4
5
6
var connection = mysql.createConnection({
 host: "localhost",
 user: "root",
 password: "somePass",
 database: "mysql"
});

I have passed the above to a variable 'connection'.

I used an object and passed the data I have to insert into table of mysql, in the object, data before column is column name and data after column is the data I got from post parameters.

For example from below:


1
2
3
4
5
postDataObject = {username: userName, password: password1, date: formattedDate};
connection.query("insert into users_nodejs set ?", postDataObject, 
   function(err, result) {
    if(err) throw err;
   });

postDataObject has username:userName

here username is the column name in the table, userName is the variable into which I stored the post parameter, (refer to main Node.js program above).

And further there we have query in connection using which we will pass queries to MySQL.

General syntax of sql is 

Syntax specified for mysql module in node.js (from npmjs.com) is:

"Insert into table_name set ? ", obj

obj here is postDataObject that has columns and data.

Test from UI:











On click of submit, we have






In MySQL,







Don't hesitate to drop in any suggestions, happy learning 

Comments

blog comments powered by Disqus