• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
seegatesite header

Seegatesite.com

Seegatesite.com - Programming Tutorial , Sharing , How and Learn Together

  • TOOLS
    • Bootstrap Navbar Online Generator
    • Customize Sidebar Menu Bootstrap 3
    • Bootstrap Demo
  • ADVERTISE
  • CATEGORIES
    • Android
    • Blogging Tips
    • Database
    • CSS
    • Info Gadget
    • Javascript
    • Linux
    • PHP
    • Various
    • WordPress
  • Q&A
  • PHP
  • JAVASCRIPT
  • JQUERY
  • ANGULAR
  • WORDPRESS
  • SEO
  • REACT
🏠 » Javascript » Tutorial Create Form Login And Authentication on MySQL, Node.js, Express, AdminLTE For Beginner

Tutorial Create Form Login And Authentication on MySQL, Node.js, Express, AdminLTE For Beginner

By Sigit Prasetya Nugroho ∙ December 2, 2016 ∙ Javascript ∙ 2 Comments

Share : TwitterFacebookTelegramWhatsapp

Create a login form and authentication middlewares using node.js and MySQL database. Through the login form, the server performs security checks and permissions of each user to be entered into the system. Before I share a tutorial to make a dynamic menu in node.js, express, and adminLTE, we must first complete the node js login system and authentication middlewares. In this article I will discuss how to create a login page adminLTE with jade template, create a session on node.js, checking whether the user is already logged in or not. Let’s begin my node js authentication tutorial.

In order to follow this article well, you should read my previous articles about :

  • Tutorial Create CRUD With MySQL, Node.Js , Express, AdminLTE For Beginner.
  • How To Transfer AdminLTE To Jade Template Engine In Express.js.

Because this article is a continuation of the article above.

Table of Contents

  • 1 Let’s start this article how to create a login form and authentication with MySQL, node.js, express and adminLTE for beginners.
    • 1.1 Prepare user table.
    • 1.2 Create an adminLTE login page with jade templating engine
    • 1.3 Checks on customers page

Let’s start this article how to create a login form and authentication with MySQL, node.js, express and adminLTE for beginners.

Package.json that I used

Related Articles :

  • Tutorial Create Dynamic Sidebar Menu on MySQL, Node.js, Express, AdminLTE For Beginner
  • Tutorial Create CRUD With Node.Js , Express, MySQL And AdminLTE For Beginner

Package Json Tutorial How To Create Login Form In Node Js Express Adminlte And Mysql

Prepare user table.

In previous articles, I have created a database with the name node.js. Add a user table. Add new fields with the following parameters :

Create Table User Tutorial Create Form Login And Authentication In Nodejs Mysql Express And Adminlte

Then add a new record with the following code :

1
INSERT INTO USER VALUES('test@test.com',MD5('123456'))

In my previous tutorial, I have made express project under the name “expressproject“. If you do not follow my previous tutorial, please download the last expressproject project here. Go into the folder and open expressproject/app.js , and copy the following script

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var flash = require('express-flash');
var session = require('express-session');
var index = require('./routes/index');
var users = require('./routes/users');
var customers = require('./routes/customers');
var expressValidator = require('express-validator');
var methodOverride = require('method-override');
 
 
var connection  = require('express-myconnection');
var mysql = require('mysql');
 
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
 
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({secret:"secretpass123456"}));
app.use(flash());
app.use(expressValidator());
app.use(methodOverride(function(req, res){
if (req.body && typeof req.body == 'object' && '_method' in req.body)
{
  var method = req.body._method;
  delete req.body._method;
  return method;
}
}));
 
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
 
/*------------------------------------------
    connection peer, register as middleware
    type koneksi : single,pool and request
    -------------------------------------------*/
    app.use(
      connection(mysql,{
        host: 'localhost',
        user: 'root', // your mysql user
        password : '123456', // your mysql password
        port : 3306, //port mysql
        database:'nodejs' // your database name
    },'pool') //or single
 
      );
 
 
 
    app.use('/', index);
    app.use('/customers', customers);
    app.use('/users', users);
 
 
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});
 
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
 
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
 
 
module.exports = app;

The next step is to make express middlewares authentication that will be used as a login authentication. Essentially, every time we open a URL page, this module will check whether we have logged in or not.

Create a folder named middlewares and then create a js file with the name authentication.js as shown below :

Create Middlewares Authentication Tutorial Create Form Login And Authentication Nodejs Express

And copy the following code to authentication.js

1
2
3
4
5
6
7
8
9
10
11
12
var Auth =
{
is_login: function (req, res, next)
{
if (!req.session.is_login)
{
return res.redirect('/login');
}
next();
},
};
module.exports = Auth;

Explanation :

The above code will be on call every time we create a new page that requires a login. The server will check whether the  is_login session is true or false. If false, then the user will be redirected to the login page.

Create an adminLTE login page with jade templating engine

Create a new folder with the name “main” into folder views. Add new login.jade file and copy the following code :

Tutorial Create Login Page With Jade Templating Engine

Login Page Adminlte With Node Js Express Mysql Dan Jade Templating

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
doctype html
html
head
title
| #{title}
meta(content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport')
link(rel='stylesheet', href='/adminlte/bootstrap/css/bootstrap.min.css')
link(rel='stylesheet', href='/font-awesome/css/font-awesome.css')
link(rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css')
link(rel='stylesheet', href='/adminlte/dist/css/AdminLTE.min.css')
link(rel='stylesheet', href='/adminlte/plugins/iCheck/square/blue.css')
body.hold-transition.login-page
.login-box
.login-logo
a(href='#')
b
| Admin
| LTE
.login-box-body
p.login-box-msg
| Sign in to start your session
form(action="/login/",method="post")
- if (messages.msg_error)
.alert.alert-danger.alert-dismissable
button.close(type='button', data-dismiss='alert', aria-hidden='true')
| ×
h4
i.icon.fa.fa-ban
| Alert!
| !{messages.msg_error}
.form-group.has-feedback
input(type="email",placeholder="Email",name="txtEmail",value="test@test.com").form-control
span.glyphicon.glyphicon-envelope.form-control-feedback
.form-group.has-feedback
input(type="password",placeholder="Password",name="txtPassword",value="123456").form-control
span.glyphicon.glyphicon-lock.form-control-feedback
.row
.col-xs-8
.checkbox.icheck
label
input(type="checkbox")
|  Remember Me
.col-xs-4
button(type="submit").btn.btn-primary.btn-block.btn-flat
| Sign In
.social-auth-links.text-center
p
| - OR -
a(href='#').btn.btn-block.btn-social.btn-facebook.btn-flat
i.fa.fa-facebook
| Sign in Using Facebook
a(href='#').btn.btn-block.btn-social.btn-google.btn-flat
i.fa.fa-google-plus
| Sign in using Google+
a(href='#')
| I forgot my password
br
a(href='#').text-center
| Register a new membership
 
script(type='text/javascript', src='/adminlte/plugins/jQuery/jquery-2.2.3.min.js')
script(type='text/javascript', src='/adminlte/bootstrap/js/bootstrap.min.js')
script(type='text/javascript', src='/adminlte/plugins/iCheck/icheck.min.js')
script(type='text/javascript', src='/adminlte/dist/js/login.js')

Create new routes with GET method to call the login page. Open index.js in the folder routes/index.js and copy the following code below :

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
var express = require('express');
var router = express.Router();
var modul = require('../modul/modul');
 
var session_store;
/* GET home page. */
router.get('/', function(req, res, next) {
res.redirect('/customers');
});
router.get('/login',function(req,res,next){
res.render('main/login',{title:"Login Page"});
});
router.post('/login',function(req,res,next){
session_store=req.session;
req.assert('txtEmail', 'Please fill the Username').notEmpty();
req.assert('txtEmail', 'Email not valid').isEmail();
req.assert('txtPassword', 'Please fill the Password').notEmpty();
var errors = req.validationErrors();
if (!errors) {
req.getConnection(function(err,connection){
v_pass = req.sanitize( 'txtPassword' ).escape().trim();
v_email = req.sanitize( 'txtEmail' ).escape().trim();
var query = connection.query('select * from user where the_email="'+v_email+'" and the_password=md5("'+v_pass+'")',function(err,rows)
{
if(err)
{
 
var errornya  = ("Error Selecting : %s ",err.code );  
console.log(err.code);
req.flash('msg_error', errornya);
res.redirect('/login');
}else
{
if(rows.length <=0)
{
 
req.flash('msg_error', "Wrong email address or password. Try again.");
res.redirect('/login');
}
else
{
session_store.is_login = true;
res.redirect('/customers');
}
}
 
});
});
}
else
{
errors_detail = "
 
Sory there are error
 
<ul>";
for (i in errors)
{
error = errors[i];
errors_detail += '
 
<li>'+error.msg+'</li>
 
 
';
}
errors_detail += "</ul>
 
 
";
console.log(errors_detail);
req.flash('msg_error', errors_detail);
res.redirect('/login');
}
});
router.get('/logout', function(req, res)
{
req.session.destroy(function(err)
{
if(err)
{
console.log(err);
}
else
{
res.redirect('/login');
}
});
});
module.exports = router;

Explanation :

1
router.get('/', function(req, res, next) {}

When the browser is directed to the URL address localhost:3000, will be redirected to the customers page

1
router.get('/login',function(req,res,next){}

When opening a localhost:3000/login, the server will render the login.jade file

1
router.post('/login',function(req,res,next)

When a user sign in, the server will call the route using POST method. In this router.post will create a new session with the name session_store. If the user successfully login, the system will accommodate a session with the name session_store.is_login with true value.

Checks on customers page

Customers Page

Previously we have made a express authentication to check whether the user has logged in or not. The module will we add to each router on the customers page. Open the file routes/customers.js and add the following 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
var express = require('express');
var router = express.Router();
var authentication_mdl = require('../middlewares/authentication');
var session_store;
/* GET Customer page. */
 
router.get('/',authentication_mdl.is_login, function(req, res, next) {
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM customer',function(err,rows)
{
if(err)
var errornya  = ("Error Selecting : %s ",err );  
req.flash('msg_error', errornya);  
res.render('customer/list',{title:"Customers",data:rows,session_store:req.session});
});
         //console.log(query.sql);
     });
});
 
router.delete('/delete/(:id)',authentication_mdl.is_login, function(req, res, next) {
req.getConnection(function(err,connection){
var customer = {
id: req.params.id,
}
var delete_sql = 'delete from customer where ?';
req.getConnection(function(err,connection){
var query = connection.query(delete_sql, customer, function(err, result){
if(err)
{
var errors_detail  = ("Error Delete : %s ",err);
req.flash('msg_error', errors_detail);
res.redirect('/customers');
}
else{
req.flash('msg_info', 'Delete Customer Success');
res.redirect('/customers');
}
});
});
});
});
router.get('/edit/(:id)',authentication_mdl.is_login, function(req,res,next){
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM customer where id='+req.params.id,function(err,rows)
{
if(err)
{
var errornya  = ("Error Selecting : %s ",err );  
req.flash('msg_error', errors_detail);
res.redirect('/customers');
}else
{
if(rows.length <=0)
{
req.flash('msg_error', "Customer can't be find!");
res.redirect('/customers');
}
else
{
console.log(rows);
res.render('customer/edit',{title:"Edit ",data:rows[0],session_store:req.session});
 
}
}
 
});
});
});
router.put('/edit/(:id)',authentication_mdl.is_login, function(req,res,next){
req.assert('name', 'Please fill the name').notEmpty();
var errors = req.validationErrors();
if (!errors) {
v_name = req.sanitize( 'name' ).escape().trim();
v_email = req.sanitize( 'email' ).escape().trim();
v_address = req.sanitize( 'address' ).escape().trim();
v_phone = req.sanitize( 'phone' ).escape();
 
var customer = {
name: v_name,
address: v_address,
email: v_email,
phone : v_phone
}
 
var update_sql = 'update customer SET ? where id = '+req.params.id;
req.getConnection(function(err,connection){
var query = connection.query(update_sql, customer, function(err, result){
if(err)
{
var errors_detail  = ("Error Update : %s ",err );  
req.flash('msg_error', errors_detail);
res.render('customer/edit',
{
name: req.param('name'),
address: req.param('address'),
email: req.param('email'),
phone: req.param('phone'),
});
}else{
req.flash('msg_info', 'Update customer success');
res.redirect('/customers/edit/'+req.params.id);
}
});
});
}else{
 
console.log(errors);
errors_detail = "
 
Sory there are error
 
<ul>";
for (i in errors)
{
error = errors[i];
errors_detail += '
 
<li>'+error.msg+'</li>
 
 
';
}
errors_detail += "</ul>
 
 
";
req.flash('msg_error', errors_detail);
res.redirect('/customers/edit/'+req.params.id);
}
});
 
router.post('/add',authentication_mdl.is_login, function(req, res, next) {
req.assert('name', 'Please fill the name').notEmpty();
var errors = req.validationErrors();
if (!errors) {
 
v_name = req.sanitize( 'name' ).escape().trim();
v_email = req.sanitize( 'email' ).escape().trim();
v_address = req.sanitize( 'address' ).escape().trim();
v_phone = req.sanitize( 'phone' ).escape();
 
var customer = {
name: v_name,
address: v_address,
email: v_email,
phone : v_phone
}
 
var insert_sql = 'INSERT INTO customer SET ?';
req.getConnection(function(err,connection){
var query = connection.query(insert_sql, customer, function(err, result){
if(err)
{
var errors_detail  = ("Error Insert : %s ",err );  
req.flash('msg_error', errors_detail);
res.render('customer/add-customer',
{
name: req.param('name'),
address: req.param('address'),
email: req.param('email'),
phone: req.param('phone'),
session_store:req.session,
});
}else{
req.flash('msg_info', 'Create customer success');
res.redirect('/customers');
}
});
});
}else{
 
console.log(errors);
errors_detail = "
 
Sory there are error
 
<ul>";
for (i in errors)
{
error = errors[i];
errors_detail += '
 
<li>'+error.msg+'</li>
 
 
';
}
errors_detail += "</ul>
 
 
";
req.flash('msg_error', errors_detail);
res.render('customer/add-customer',
{
name: req.param('name'),
address: req.param('address'),
session_store:req.session
});
}
 
});
 
router.get('/add',authentication_mdl.is_login, function(req, res, next) {
res.render( 'customer/add-customer',
{
title: 'Add New Customer',
name: '',
email: '',
phone:'',
address:'',
session_store:req.session
});
});
 
module.exports = router;

Explanation :

1
router.get('/',authentication_mdl.is_login, function(req, res, next) { }

Middlewares authentication_mdl.is_login called before the function (req, res, next). The server will check whether there is is_login session or not. If no then it will be redirected to the login page.

Create logout route in node.js and express tutorial

Now we will create the “/logout” URL in which we will destroy the session by using the destroy() method. After that will be redirected to the “/login” page with GET method. Now simply add the following route in routes/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
router.get('/logout', function(req, res)
{
req.session.destroy(function(err)
{
if(err)
{
console.log(err);
}
else
{
res.redirect('/login');
}
});
});

Then open the folder layout views/layouts/navigation.jade and add a logout link in a href element to sign out as follows :

1
2
a(href='/logout').btn.btn-default.btn-flat
| Sign out

Until this step, Tutorial Create Form Login And Authentication on Mysql, Node.js, Express, AdminLTE For Beginner has been completed. If you need the complete source code please download via the link below, please share this article to open the download button

Url : Download tutorial create login form and authentication in node js.

Password : seegatesite.com

Thus my article about node js and mysql database. If you have any questions and suggestions please fill in the comments below. Thank you 🙂

Another Javascript Related Post :

  • Adept Using Datatables Plugin In 10 Minutes For Beginners (Tutorial)
  • The Using Of Reactstrap And React-Table, Suitable For Beginners
  • Tutorial Create Simple Block UI Using React JS
  • How To Implement Login Page And Protected Route ReactJS
  • Complete Tutorial React Router Dom For Beginners (Easy-To-Understand)
  • The Right Way Understanding React Lifecycle For Beginners

Avatar for Sigit Prasetya Nugroho

About Sigit Prasetya Nugroho

This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Reader Interactions

Comments

  1. Avatar for Angelo EscasioAngelo Escasio says

    May 9, 2017 at 6:33 am

    The in index.js i got error saying
    module.js:472
    throw err;
    ^

    also
    Sign in button not submitting.

    Reply
  2. Avatar for Angelo EscasioAngelo Escasio says

    May 9, 2017 at 6:34 am

    var modul = require(‘../modul/modul’);
    The in index.js i got error saying
    module.js:472
    throw err;
    ^

    also
    Sign in button not submitting.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Welcome to my Home,

Avatar for Angelo EscasioThis site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.



Popular Articles

Checked checkbox AdminLTE Bootstrap in Jquery

November 4, 2014 By Sigit Prasetya Nugroho 7 Comments

Simple create date format validation with jqueryUI

December 21, 2014 By Sigit Prasetya Nugroho Leave a Comment

Create Simple Progress Bar for Fake Online Generator with Jquery

January 10, 2015 By Sigit Prasetya Nugroho Leave a Comment

22+ Coolest Free Jquery Plugin For Premium Theme

October 3, 2015 By Sigit Prasetya Nugroho Leave a Comment

Easy Build Your Anti Copy Paste Plugin

October 6, 2015 By Sigit Prasetya Nugroho Leave a Comment

Popular Tags

adminlte (15) adsense (13) adsense tips (4) affiliate amazon (13) amazon (12) Android (8) angular (16) angular 4 (12) angular 5 (4) asin grabber (3) Bootstrap (27) codeigniter (5) create wordpress theme (5) crud (8) css (6) free wordpress theme (7) google adsense (4) imacros (4) increase traffic (6) jquery (34) laravel (10) laravel 5 (5) learn android (5) modal dialog (5) mysql (6) nodeJs (4) optimize seo (4) pdo (6) php (30) plugin (53) pos (7) Publisher Tips (5) react (3) Reactjs (7) SEO (37) theme (17) tutorial angular (5) tutorial angular 4 (6) tutorial javascript (10) tutorial javascript beginners (4) twitter (3) widget (3) wordpress (18) wordpress plugin (13) XMLRPC (5)




  • About
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

©2021 Seegatesite.com