hello there I am new in learning about mongoDB,node js,Passport and express actually I was succefully able to create a working signup page but my problem is the sigin page like every time I am trying to enter correct email and password it always go to failure to redirect knwoing that this is my code for the routers
users.js
var express = require('express');
var router = express.Router();
const { check, validationResult } = require('express-validator');
const User = require('../models/User');
const passport = require('passport');
/* GET users listing. */
router.get('/signup', function (req, res, next) {
var massagesError = req.flash('error')
res.render('signup', { massages: massagesError })
});
router.post('/signup', [
check('name').not().isEmpty().withMessage('Please Enter Your Name'),
check('email').not().isEmpty().withMessage('Please Enter Your Email'),
check('email').isEmail().withMessage('Please Enter Valid Email'),
check('password').not().isEmpty().withMessage('Please Enter your Password'),
check('password').isLength({ min: 8 }).withMessage('Please Enter Password more than 8 characters'),
check('confirm-password').custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('Password and confirm-password do not match');
}
return true;
}),
check('phoneNumber').not().isEmpty().withMessage('Please Enter your Phone Number'),
check('phoneNumber').isMobilePhone().withMessage('please enter Valid Phone Numeber'),
check('userType').isIn(['sponsor', 'student']).withMessage('Please select a valid user type')
], (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
var validationMassages = [];
for (var i = 0; i < errors.errors.length; i++) {
validationMassages.push(errors.errors[i].msg)
}
req.flash('error', validationMassages);
res.redirect('signup')
console.log(validationMassages);
return;
}
const user = new User({
name: req.body.name,
email: req.body.email,
password: new User().hashPassword(req.body.password),
phoneNumber: req.body.phoneNumber,
userType: req.body.userType
})
User.findOne({ email: req.body.email })
.then(result => {
if (result) {
// User with the provided email already exists
req.flash('error', 'this email already exist')
res.redirect('signup')
return;
}
user.save()
.then(doc => {
res.send(doc);
})
.catch(error => {
console.log(error);
res.status(500).send('An error occurred while saving the user');
})
})
})
router.get('/profile', (req, res, next) => {
res.render('profile')
});
router.get('/signin', (req, res, next) => {
res.render('signin');
})
router.post('/signin', passport.authenticate('local-signin',
{session:false,
successRedirect: 'profile',
failureRedirect: 'signin',
failureFlash : true,
}))
module.exports = router;
and this for the passport
passport.js
const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const User = require('../models/User');
passport.use('local-signin', new localStrategy({
usernameField: 'email', // default is username, override to accept email
passwordField: 'password',
passReqToCallback: true // allows us to access req in the call back
}, async (req, email, password, done) => {
// Check if user and password is valid
let user = await User.findBy('email', email)
let passwordValid = user && bcrypt.compareSync(password, user.passwordHash)
// If password valid call done and serialize user.id to req.user property
if (passwordValid) {
return done(null, {
id: user.id
})
}
// If invalid call done with false and flash message
return done(null, false, {
message: 'Invalid email and/or password'
});
}))
and this is my app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const mongoose = require('mongoose');
const expressHbs = require('express-handlebars');
const session = require('express-session');
const flash = require('connect-flash');
const passport =require('passport');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
require('./config/passport');
// view engine setup
app.engine('.hbs', expressHbs.engine({defaultLayout : 'layout' , extname : '.hbs'}));
app.set('view engine', '.hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret : 'Chance_?@!',
saveUninitialized : false,
resave : false,
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(express.static(path.join(__dirname, 'public')));
mongoose.connect('mongodb://localhost/Chance')
.then(() => {
console.log('Connected to MongoDB successfully!');
// You can perform further operations with the connected database here
})
.catch(error => {
console.error('Failed to connect to MongoDB:', error);
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
console.log('Requested URL:', req.url); // Add this line to log the requested URL
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');
});
module.exports = app;
If it possible please help me I am stucked with it for 5 days now
Youssef Hesham Khairat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.