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
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
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 :
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 :
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 :
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
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
Thus my article about node js and mysql database. If you have any questions and suggestions please fill in the comments below. Thank you 🙂
The in index.js i got error saying
module.js:472
throw err;
^
also
Sign in button not submitting.
var modul = require(‘../modul/modul’);
The in index.js i got error saying
module.js:472
throw err;
^
also
Sign in button not submitting.