routes | index.js | LogSyS
/routes/index.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const bcrypt = require("bcryptjs");
// user model
const User = require('../models/Users');
router.get('/', (req, res) => {
res.render("welcome");
});
// Register page
router.get('/register', (req,res) =>{
res.render("register");
});
router.post('/register', (req,res) =>{
//var email = email which is passed by the client
email = req.body.email
//var password = password which is passed by the client
password = req.body.password
cpassword = req.body.cpassword
console.log(email)
console.log(password)
console.log(cpassword)
console.log("------------------------------------------------------")
// let errors = [];
// check fields
if(!email || !password || !cpassword){
return res.render('register', {msg:' Please fill all the required fields.'});
// errors.push({msg : " Please fill up all fields"});
// console.log(errors.msg);
}
// check password match
if(password !== cpassword){
return res.render('register', {msg: ' Password do not matched'});
}
// check pass length
if(password.length <5){
// errors.push({msg : " Password 5 char"});
return res.render('register', {msg : " Password must be atleast 5 characters."});
}else{
User.findOne({
email: email
}).then(user => {
if (user) {
// return done(null, false, { message: 'That email is not registered' });
//check whether the email is alredy registered or not
res.render('register',{msg: ' Email you entered is already registered.'});
}else{
//created new object as user
const newUser = new User({ email, password });
// hash password
bcrypt.genSalt(18,(err, salt)=>
bcrypt.hash(newUser.password,salt,(err, hash)=>{
if(err){
res.send(err);
}else{
newUser.password = hash ;
}
//save the user
newUser.save()
.then(user =>{
// send success msg to Register page
res.render('welcome', {email, mesg : " You have registered your account."});
})
}))//gensalt
}//else minor
});//then function
}//else major
})//router.post function
// login page
router.get('/login', (req,res) =>{
res.render('login');
});
// login handle
router.post('/login',(req,res,next)=>{
//passport will authenticate the email, password, user
//whether the password is correct or whether the email registered or email already exist.
passport.authenticate('local',{
successRedirect: '/home',
successMessage : 'login page is hrerew',
failureRedirect : '/login',
failureFlash : true,
}
)(req,res,next);
});
// home page
router.get('/home', (req,res) =>{
res.render('home');
});
// logout
router.get('/logout',(req,res)=>{
req.logOut();
res.redirect('/login');
})
module.exports = router;
Comments
Post a Comment