Login Application using NodeJs and MySql?
install Express EJS
File Name :
c:\>npx express --view=ejs login_app
c:\login_app> npm init -y
File Name :
c:\login_app> npm install
c:\login_app> npm install express --save
c:\login_app> npm install express-flash --save
c:\login_app> npm install express-session --save
c:\login_app> npm install express-validator --save
c:\login_app> npm install method-override --save
c:\login_app> npm install mysql --save
c:\login_app> npm install http-errors-enhanced --save
Create Table
File Name :
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
primary key(id),
`name` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Database connection
File Name : lib/db.js
var mysql=require('mysql');
var connection=mysql.createConnection({
host:'localhost',
user:'root',
password:'root',
database:'nodedb'
});
connection.connect(function(error){
if(!!error){
console.log(error);
}else{
console.log('Connected!:)');
}
});
module.exports = connection;
App.js
File Name : app.js
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 indexRouter = require('./routes/index');
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('/', indexRouter);
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;
Create Route
File Name : routes/auth.js
var express = require('express');
var router = express.Router();
var connection = require('../lib/db');
//display login page
router.get('/', function(req, res, next){
// render to views/user/add.ejs
res.render('auth/login', {
title: 'Login',
email: '',
password: ''
})
})
//display login page
router.get('/login', function(req, res, next){
// render to views/user/add.ejs
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 users 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 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;
login page
File Name : viwes/auth/login.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
<% if (messages.error) { %>
<p style="color:red"><%- messages.error %></p>
<% } %>
<% if (messages.success) { %>
<p style="color:green"><%- messages.success %></p>
<% } %>
<form action="/auth/authentication" method="post" name="form1">
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" value="">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Password</label>
<input type="password" name="password" class="form-control" id="password" aria-describedby="emailHelp" placeholder="*********" value="">
</div>
<input type="submit" class="btn btn-primary" value="Add">
</form>
</body>
</html>
Home page
File Name : viwes/auth/home.js
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<% if (messages.error) { %>
<p style="color:red"><%- messages.error %></p>
<% } %>
<% if (messages.success) { %>
<p style="color:green"><%- messages.success %></p>
<% } %>
<div class="card">
<div class="card-header">
Dashboard <b><%= name %></b>
</div>
<div class="card-body">
<h5 class="card-title">Welcome</h5>
<p class="card-text">You have successfully login</p>
<a href="auth/logout" class="btn btn-primary">Logout</a>
</div>
</div>
</div>
</body>
</html>
Test Login Application
Previous
Next