Node js user authentication using mysql and express js jwt – tuts make

(a) get the nodejs server running

Add the following to dbServer.js file

const port = process.env.PORTapp.listen(port, 
()=> console.log(`Server Started on port ${port}...`))

Once you save your file, nodemon will refresh and will get your Express JS server up and running!

(b) connect your nodejs app to your mysql db

Create a dbServer.js file as follow,

(c) create a .env file and hide your db credentials in there

Create a .env file as follows

Awesome!! you are now connected to your mysql db!!!

Note: that we use mysql.createPool(), instead of mysql.createConnection(), since we want our application to be PRODUCTION grade.

Step 1: install node express js setup

The following command install express js setup:

express --view=ejs myApp

After open myApp setup with any text editor. And use the following command to enter your myApp app directories, So open your cmd and run the following command:

cd loginSystem

Your node express js app structure looks like:

Next, you need to install some required pacakges, so open again your cmd and run the following commands:

 npm install    
 npm install express-flash --save
 npm install express-session --save
 npm install express-validator --save
 npm install method-override --save
 npm install mysql --save

Step 2: connect node express js app with db

Before connecting DB to your application, create table into your database by using the following SQL query:

CREATE DATABASE IF NOT EXISTS `nodelogin` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `nodelogin`;

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO `users` (`id`, `name`, `password`, `email`) VALUES (1, 'test', 'test', '[email protected]');

ALTER TABLE `users` ADD PRIMARY KEY (`id`);
ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;

Next, you need to create one folder named lib and create a new file name db.js inside lib folder.

Note that, This file is used to connect your node express js app to MySQL db.

Step 3: import packages and routes in app.js

In this step, you need to include all packages in app.js file whose installed above and also initialize the session in this file.

So go to app.js file and update the following code:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressValidator = require('express-validator');
var flash = require('express-flash');
var session = require('express-session');
var bodyParser = require('body-parser');


var mysql = require('mysql');
var connection  = require('./lib/db');

var authRouter = require('./routes/auth');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({ 
    secret: '123456cat',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 }
}))

app.use(flash());
app.use(expressValidator());

app.use('/auth', authRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// 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');
});
// port must be set to 3000 because incoming http requests are routed from port 80 to port 8080
app.listen(3000, function () {
    console.log('Node app is running on port 3000');
});
module.exports = app;

Step 4 – install express and required modules

Execute the following command on terminal to install express express-validator mysql body-parser jsonwebtoken bcryptjs cors into your node js express app:

npm install express express-validator mysql body-parser jsonwebtoken bcryptjs cors --save

Step 4: create route

In this step, you need to create one route file name auth.js inside the routes folder.

Then update the following routes into your routes/auth.js file:

var express = require('express');
var router = express.Router();
var connection  = require('../lib/db');
//display login page
router.get('/', function(req, res, next){    
res.render('auth/login', {
title: 'Login',
email: '',
password: ''      
})
})
//display login page
router.get('/login', function(req, res, next){    
res.render('auth/login', {
title: 'Login',
email: '',
password: ''     
})
})
//authenticate user
router.post('/authentication', function(req, res, next) {
var email = req.body.email;
var password = req.body.password;
connection.query('SELECT * FROM accounts WHERE email = ? AND password = ?', [email, password], function(err, rows, fields) {
if(err) throw err
// if user not found
if (rows.length <= 0) {
req.flash('error', 'Please correct enter email and Password!')
res.redirect('/login')
}
else { // if user found
// render to views/user/edit.ejs template file
req.session.loggedin = true;
req.session.name = name;
res.redirect('/home');
}            
})
})
//display login page
router.get('/register', function(req, res, next){    
res.render('auth/register', {
title: 'Registration Page',
name: '',
email: '',
password: ''     
})
})
// user registration
router.post('/post-register', function(req, res, next){    
req.assert('name', 'Name is required').notEmpty()           //Validate name
req.assert('password', 'Password is required').notEmpty()   //Validate password
req.assert('email', 'A valid email is required').isEmail()  //Validate email
var errors = req.validationErrors()
if( !errors ) {   //No errors were found.  Passed Validation!
var user = {
name: req.sanitize('name').escape().trim(),
email: req.sanitize('email').escape().trim(),
password: req.sanitize('password').escape().trim()
}
connection.query('INSERT INTO users SET ?', user, function(err, result) {
//if(err) throw err
if (err) {
req.flash('error', err)
res.render('auth/register', {
title: 'Registration Page',
name: '',
password: '',
email: ''                    
})
} else {                
req.flash('success', 'You have successfully signup!');
res.redirect('/login');
}
})
}
else {   //Display errors to user
var error_msg = ''
errors.forEach(function(error) {
error_msg  = error.msg   '<br>'
})                
req.flash('error', error_msg)        
/**
* Using req.body.name 
* because req.param('name') is deprecated
*/ 
res.render('auth/register', { 
title: 'Registration Page',
name: req.body.name,
email: req.body.email,
password: ''
})
}
})
//display home page
router.get('/home', function(req, res, next) {
if (req.session.loggedin) {
res.render('auth/home', {
title:"Dashboard",
name: req.session.name,     
});
} else {
req.flash('success', 'Please login first!');
res.redirect('/login');
}
});
// Logout user
router.get('/logout', function (req, res) {
req.session.destroy();
req.flash('success', 'Login Again Here');
res.redirect('/login');
});
module.exports = router;

Step 5: create views

In this step, you need to create one folder name Auth. So go to the views folder in your app and create the Auth folder.

Inside the Auth folder, you need to create two views file. The views file is the following:

(a) create a new folder and initialize your nodejs app

$ mkdir db-practice1
$ cd db-practice1
$ npm init --y
//next we will install some node packages$ npm i express mysql
$ npm i nodemon dotenv --save-dev
//We installed "express" and "mysql", and "nodemon" and "dotenv" as devDependencies
Похожее:  WWW КЛУБ ЛУКОЙЛ РУ ВОЙДИТЕ В ЛИЧНЫЙ КАБИНЕТ

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *