Reputation: 791
I'm trying to build in authentication to a small webapp using passport, mongodb, mongoose, express and the passport-local-mongoose plugin. I am being returned a bad request
when trying to log in a user. I am able to register a user and get the data into the DB.
How do I move forward to debug this with error handling? The docs for passport and passport-local-mongoose seems light (and I'm a bit of a noob).
App.js
app.use(passport.initialize())
app.use(passport.session())
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
var User = require('./models/user.js')
passport.use(new LocalStrategy(User.authenticate()));
//passport.use(new LocalStrategy(UserSchema.authenticate()))
// use static serialize and deserialize of model for passport session support
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// Connect to Mongoose
mongoose.connect('mongodb://localhost/users')
Registration route (gets data to the db, but fails to redirect)
// Register a user to the DB
router.post('/register', function(req, res, next){
let firstName = req.body.firstName
let lastName = req.body.lastName
let username = req.body.email
//let password = req.body.password
let homeAirport = req.body.homeAirport
User.register(new User ({
firstName: firstName,
lastName: lastName,
username: username,
homeAirport: homeAirport
}),
req.body.password, function(err, user) {
if (err) {
console.log(err)
return res.render('register', {
user: user
})
}
// both of these works
passport.authenticate('local', { failureRedirect: '/' }),
function(req, res, next) {
res.redirect('/');
}
})
})
Login Route (returns a bad request)
router.post('/login', passport.authenticate('local'), function(req, res) {
res.redirect('/');
});
User Schema
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
passportLocalMongoose = require('passport-local-mongoose');
// Define the scheme
var User = new Schema ({
firstName: {
type: String,
index: true
},
lastName: {
type: String,
index: true
},
email: {
type: String,
index: true
},
homeAirport: {
type: String,
index: true
}
})
User.plugin(passportLocalMongoose)
module.exports = mongoose.model('User', User)
Upvotes: 2
Views: 2938
Reputation: 105
I also had to add it to the schema, like so:
userSchema.plugin(passportLocalMongoose, {
usernameField : "email"});
Upvotes: 1
Reputation: 456
Sorry for the late reply! I too faced a problem like this. The problem was not with passport-local-mongoose, it was with passport. It expects the http request to contain the fields username and password. So if you are using email to register, it responds with bad request.
To fix this, change the userNameField as shown below
passport.use(new LocalStrategy({
usernameField: 'email',
},User.authenticate()));
Hope It Helps
Upvotes: 8