How to create Forgot and Reset Password using NodeJs with mySql?
Create a Project
c:\> npx express --view=ejs crud_api
Initialise and Configure Our Project
File Name :
c:\crud_api> npm init -y
npm install
Install express and other dependencies
File Name :
c:\crud_api> npm install express --save
install Body Parser :-
File Name :
c:\crud_api> npm install body-parser --save
MySql Install
File Name :
c:\crud_api> npm install mysql --save
Nodemon Install
File Name :
c:\crud_api> npm install --save-dev nodemon
Install All module
File Name :
npm install express-flash --save
npm install express-session --save
npm install method-override --save
npm install mysql --save
npm install rand-token --save
npm install body-parser --save
npm install bcrypt
npm install
If you want to send mail from localhost or without ssl certificate, you can execute the following command on your terminal also:
File Name :
npm config set strict-ssl false --global
set NODE_TLS_REJECT_UNAUTHORIZED=0
create table
File Name :
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
primary key(id),
`name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(250) COLLATE utf8mb4_unicode_ci DEFAULT NULL
);
db.js
File Name : 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 flash = require('express-flash');
var session = require('express-session');
var bodyParser = require('body-parser');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: '123458cat',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}))
app.use(flash());
//app.use('/', indexRouter);
app.use('/', usersRouter);
// 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');
});
app.listen(4000, function () {
console.log('Node app is running on port 4000');
});
module.exports = app;
Create routes
File Name : users.js
var express = require('express');
var router = express.Router();
var connection = require('../database.js');
var nodemailer = require('nodemailer');
var bcrypt = require('bcrypt');
var randtoken = require('rand-token');
//send email
function sendEmail(email, token) {
var email = email;
var token = token;
var mail = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '', // Your email id
pass: '' // Your password
}
});
var mailOptions = {
from: 'tutsmake@gmail.com',
to: email,
subject: 'Reset Password Link - Tutsmake.com',
html: '<p>You requested for reset password, kindly use this <a href="http://localhost:4000/reset-password?token=' + token + '">link</a> to reset your password</p>'
};
mail.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(1)
} else {
console.log(0)
}
});
}
/* home page */
router.get('/', function(req, res, next) {
res.render('index', {
title: 'Forget Password Page'
});
});
/* send reset password link in email */
router.post('/reset-password-email', function(req, res, next) {
var email = req.body.email;
//console.log(sendEmail(email, fullUrl));
connection.query('SELECT * FROM users WHERE email ="' + email + '"', function(err, result) {
if (err) throw err;
var type = ''
var msg = ''
console.log(result[0]);
if (result[0].email.length > 0) {
var token = randtoken.generate(20);
var sent = sendEmail(email, token);
if (sent != '0') {
var data = {
token: token
}
connection.query('UPDATE users SET ? WHERE email ="' + email + '"', data, function(err, result) {
if(err) throw err
})
type = 'success';
msg = 'The reset password link has been sent to your email address';
} else {
type = 'error';
msg = 'Something goes to wrong. Please try again';
}
} else {
console.log('2');
type = 'error';
msg = 'The Email is not registered with us';
}
req.flash(type, msg);
res.redirect('/');
});
})
/* reset page */
router.get('/reset-password', function(req, res, next) {
res.render('reset-password', {
title: 'Reset Password Page',
token: req.query.token
});
});
/* update password to database */
router.post('/update-password', function(req, res, next) {
var token = req.body.token;
var password = req.body.password;
connection.query('SELECT * FROM users WHERE token ="' + token + '"', function(err, result) {
if (err) throw err;
var type
var msg
if (result.length > 0) {
var saltRounds = 10;
// var hash = bcrypt.hash(password, saltRounds);
bcrypt.genSalt(saltRounds, function(err, salt) {
bcrypt.hash(password, salt, function(err, hash) {
var data = {
password: hash
}
connection.query('UPDATE users SET ? WHERE email ="' + result[0].email + '"', data, function(err, result) {
if(err) throw err
});
});
});
type = 'success';
msg = 'Your password has been updated successfully';
} else {
console.log('2');
type = 'success';
msg = 'Invalid link; please try again';
}
req.flash(type, msg);
res.redirect('/');
});
})
module.exports = router;
Create views :- Forget Password Page
File Name : index.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body class="container mt-3">
<% if (messages.error) { %>
<p style="color:red"><%- messages.error %></p>
<% } %>
<% if (messages.success) { %>
<p style="color:green"><%- messages.success %></p>
<% } %>
<h1 class="mb-3"><%= title %></h1>
<form action="/reset-password-email" 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>
<input type="submit" class="btn btn-primary" value="Send Verification Link">
</form>
</body>
</html>
Reset/Update Password Page
File Name : reset-password.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %> - tutsmake.com</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body class="container mt-3">
<% if (messages.error) { %>
<p style="color:red"><%- messages.error %></p>
<% } %>
<% if (messages.success) { %>
<p style="color:green"><%- messages.success %></p>
<% } %>
<h1 class="mb-3"><%= title %></h1>
<form action="/update-password" method="post" name="form1">
<input type="hidden" name="token" class="form-control" value="<%= token %>">
<div class="form-group">
<label for="exampleInputEmail1">Password</label>
<input type="password" name="password" class="form-control" id="password" aria-describedby="emailHelp" placeholder="Please Enter New Password" value="">
</div>
<input type="submit" class="btn btn-primary" value="Update Password">
</form>
</body>
</html>
Run Server
Previous
Next