I am trying to create a user login [.ejs file] form using passport local session in nodejs. My problem is that I keep on getting bad request when I hit on the submit button,can anyone please check my code and help me out
Here is my nodejs code:
required:
var express = require('express');
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var cookieParser = require('cookie-parser')
var expressSession = require('express-session');
var mongodb = require('mongodb');
var mongoose = require('mongoose');
var app = express();
var MongoClient = mongodb.MongoClient;
app.use(expressSession({
secret: 'secret'
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.set('view engine', 'ejs');
passport:
var user = mongoose.model('val', Schema);
passport.use(new LocalStrategy({
passReqToCallback: true
},
function (firstName, password12, done) {
console.log("entered Function");
user.findOne({
firstName: firstName
},
function (err, firstName) {
if (err) {
return done(err);
}
if (!firstName) {
console.log('User Not Found ' + firstName);
}
if (!isValidPassword(firstName, password12)) {
console.log('Invalid Password');
} else {
console.log('correct');
return done(null, firstName);
}
}
);
}));
login page:
app.get('/login', function (req, res) {
res.render('login');
});
app.post('/login', passport.authenticate('local'), function (req, res){
var userInfo = req.body;
});
I believe you have posted partial Nodejs file code? Where is the code for the authenticate function that you call at
In addition to authenticate method, you need passport.serializeUser and passport.deserializeUser methods. Passport invokes these 2 functions and they are needed.
Here is the demo code. Do write your own code keeping this as reference
if you use this, than add req to code. next line should be:
your post router must be something like this: