bradtraversy / node_passport_login

Node.js login, registration and access control using Express and Passport
1.74k stars 1.29k forks source link

Validation errors not showing up on the top of signup and login form #76

Open rajbukhariya12 opened 4 years ago

rajbukhariya12 commented 4 years ago

if I don't satisfy the validation requirement in the signup form, It doesn't redirect to the next page and 3-4 line gap comes right below my signup and login form heading tags. This means my errors are coming on the top of signup and login form but it is not visible may be some color issues or something.

Please help me fix the issue. i want the validation errors should be dispalyed on top on both the forms

This is my main server.js file

const express = require('express');
const app = express();

const mongoose = require('mongoose');
mongoose
  .connect(
    "mongodb+srv://mongoDB313:mongoDB313@sit313cluster.j1mdh.mongodb.net/userdetails?retryWrites=true&w=majority",
    { useNewUrlParser: true, useUnifiedTopology: true }
  )
  .then(() => console.log('MongoDB is Connected successsfully'))
  .catch(err => console.log(err));

const expressLayouts = require('express-ejs-layouts');
app.use(expressLayouts);
app.set('view engine', 'ejs');

const passport = require('passport');
require('./config/passport')(passport);

const flash = require('connect-flash');
const session = require('express-session');

app.use(express.urlencoded({ extended: true }));

app.use(
  session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
  })
);

app.use(passport.initialize());
app.use(passport.session());

app.use(flash());

app.use(function (req, res, next) {
  res.locals.success_msg = req.flash('success_msg');
  res.locals.error_msg = req.flash('error_msg');
  res.locals.error = req.flash('error');
  next();
});

app.use('/', require('./routes/main.js'));
app.use('/indiviual', require('./routes/indiviual.js'));

const PORT = process.env.PORT || 5000;

app.listen(PORT, console.log(`Server started on port `${PORT}`));`

This is my partial ejs file

<% if(typeof errors != 'undefined'){ %> <% errors.forEach(function(error) { %>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
  <%= error.msg %>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<% }); %> <% } %> <% if(success_msg != ''){ %>
<div class="alert alert-success alert-dismissible fade show" role="alert">
  <%= success_msg %>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<% } %> <% if(error_msg != ''){ %>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
  <%= error_msg %>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<% } %> <% if(error != ''){ %>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
  <%= error %>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<% } %>

This is my routes files

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');
// Load User model
const User = require('../models/User');
const { forwardAuthenticated } = require('../config/auth');

// reqlogin Page
router.get('/reqlogin', forwardAuthenticated, (req, res) => res.render('reqlogin'));

// Register Page
router.get('/register', forwardAuthenticated, (req, res) => res.render('register'));

// Register
router.post('/register', (req, res) => {
  const { country, firstname, lastname, email, password, password2, address, city, state, zip_postal, mobile_number } = req.body;
  let errors = [];

  if (!country || !firstname || !lastname || !email || !password || !password2 || !address || !city || !state || !zip_postal || !mobile_number) {
    errors.push({ msg: 'Please enter all fields' });
  }

  if (password != password2) {
    errors.push({ msg: 'Passwords do not match' });
  }

  if (password.length < 8) {
    errors.push({ msg: 'Password must be at least 8 characters' });
  }

  if (errors.length > 0) {
    res.render('register', {
      errors,
      country,
      firstname,
      lastname,
      email,
      password,
      password2,
      address,
      city,
      state,
      zip_postal,
      mobile_number
    });
  } else {
    User.findOne({ email: email }).then(user => {
      if (user) {
        errors.push({ msg: 'Email already exists' });
        res.render('register', {
          errors,
          country,
          firstname,
          lastname,
          email,
          password,
          password2,
          address,
          city,
          state,
          zip_postal,
          mobile_number
        });
      } else {
        const newUser = new User({
          country,
          firstname,
          lastname,
          email,
          password,
          password2,
          address,
          city,
          state,
          zip_postal,
          mobile_number
        });

        bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(newUser.password, salt, (err, hash) => {
            if (err) throw err;
            newUser.password = hash;
            newUser
              .save()
              .then(user => {
                req.flash(
                  'success_msg',
                  'You are now registered and can log in'
                );
                res.redirect('/indiviual/reqlogin');
              })
              .catch(err => console.log(err));
          });
        });
      }
    });
  }
});

// reqlogin
router.post('/reqlogin', (req, res, next) => {
  passport.authenticate('local', {
    successRedirect: '/reqtask',
    failureRedirect: '/indiviual/reqlogin',
    failureFlash: true
  })(req, res, next);
});

// Logout
router.get('/logout', (req, res) => {
  req.logout();
  req.flash('success_msg', 'You are logged out');
  res.redirect('/indiviual/reqlogin');
});

module.exports = router;
romilpandey13 commented 3 years ago

Suffering from same issue...

sghosh1810 commented 3 years ago

Can you attach the actual login page ejs file?

jack-hags commented 3 years ago

make sure you have:

<% include ./partials/messages %>

above the form tag on the login/signup page

sandip2224 commented 2 years ago

Can you try replacing the "data-dismiss" attribute with "data-bs-dismiss" inside the messages.js file and see if it works or not?