Showing posts with label Web. Show all posts
Showing posts with label Web. 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.

Sunday, August 9, 2015

Some cool String functions in PHP

In this post I am going to discuss some of the cool String functions available in PHP.

Here they go:

1. strlen: Returns the length of the String.
2. str_word_count: Returns the number of words in the given string.
3. strrev: Reverses the string.
4. str_replace: Replaces the String with another value.
5. strpos: Returns the position of the String.
6. bin2hex: Returns the Hexadecimal of the given value.
7. hex2bin: Yes, this does the opposite of Number 6.
8. str_shuffle: This function shuffles the letters of the String.
9. convert_uuencode: Encodes the given String using uuencode encoding.
10. convert_uudecode: This does the opposite of Number 9.
11. str_rot13: This returns the encoding of a given String in ROT 13 encoding. The function also decodes the same String which we gave for encoding.
Let's say we are giving String "Apple", it converts the String as "Nccyr", I hope some of you might have got it, Add 13 to the letter and you convert. A is 1 and 1 + 13 is 14 which is N, following the numbering of letters of 26 English alphabets.
12. crc32: This function calculates and returns 32 bit CRC for a given String.

Here goes the syntax for the above functions:



 <html>  
 <body>  
 <?php  
 function formatHere($a) {  
      echo ("<p style='font-size:20px;'>");  
      echo $a;  
      echo ("</p>");  
 }  
 echo ("<center>");  
 formatHere(strlen("Length of this sentence"));  
 formatHere(str_word_count ("Count The Words Of This Sentence"));  
 formatHere(strrev ("Reverse This"));  
 formatHere(str_replace("replace", "replaced", "String replace"));  
 formatHere(strpos("String Position", "Position"));  
 $a = bin2hex("Convert this");  
 formatHere($a);  
 formatHere(hex2bin($a));  
 formatHere(str_shuffle("Shuffle this"));  
 $b = convert_uuencode("Encode this");  
 formatHere($b);  
 formatHere(convert_uudecode($b));  
 $c = str_rot13("Apple");  
 formatHere($c);  
 formatHere(str_rot13($c));  
 formatHere(crc32("32 bit CRC for this"));  
 echo ("</center>");  
 ?>  
 </body>  
 </html>  


Results returned by String functions in the above code:




Please feel free to drop your suggestions.

Monday, March 11, 2013

Web Services


         Web services is nothing but a resource through which you can convert your application into web application, also it helps data transfer between various platforms and applications and the most recommended format of transferring data is XML. XML has been recognized by W3C to be used exclusively for web services, in other words data is carried out in XMLs.
        Web services basically consists of three elements :
1. SOAP
2. WSDL
3. UDDI

SOAP : SOAP is Simple Object Access Protocol, which enables the transfer of data between various platforms and different languages, so this becomes the main part of web services. It uses HTTP protocol for the transfer of data.
SOAP basically consists of 
  • Envelope
  • Header
  • Body
  • Fault
Envelope : Envelope is the root element of the SOAP message, it consists soap:xmlns namespace which has default value of : 
    ---------------------------------------------------------------------------
    "http://www.w3.org/2001/12/soap-envelope"
    ---------------------------------------------------------------------------

    Example :
    ---------------------------------------------------------------------------------------------------------

    <?xml version="1.0"?>

    <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
    soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
    ............
    Messages that you want to transfer
    ............
    </soap:Envelope>
    ---------------------------------------------------------------------------------------------------------

    If any namespace other than soap:xmlns is used, it will not allow the transfer and generate an error.

    SOAP encoding Style attribute : It is the basic encoding style used in the SOAP
    soap:encodingStyle="URI".

    Header : Header is the first element of Envelope element in the SOAP message. It contains three attributes : 
    • mustUnderstand
    • actor
    • encodingStyle
    Body : This contains the actual message that will be transferred.

    ------------------------------------------------------------------------------------------------------------
    <?xml version="1.0"?>
    <soap:Envelope
    xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
    soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

    <soap:Body>
      <m:GetPrice xmlns:m="http://www.w3schools.com/prices">
        <m:Item>Apples</m:Item>
      </m:GetPrice>
    </soap:Body>

    </soap:Envelope>

    ------------------------------------------------------------------------------------------------------------

    Fault : It is an optional element and it is used to indicate error messages.


    WSDL : Web Services Description Language, is other part of web services which is used to locate and describe the application that is converted into web application. It's simply a link that takes you to the application, in other words you convert the data that is inter-operable between different platforms using SOAP and WSDL takes you to that data.

    UDDI : Universal Description, Discovery and Intergration, is a kind of directory for storing the information about web services it transfers data via SOAP.

    If you want to learn more about Web Services refer : 

    http://w3schools.com/webservices/ws_why.asp

    Comments

    blog comments powered by Disqus