I'm trying to set up a login page using passport-local this way, but it wouldn't work:
node server side:
// mongoose
var User = mongoose.model('User', userSchema);
User.find({}).exec(function(err, collection){
if(collection.length === 0) {
User.create({identifiant: '123', motDePasse: '123'});
}
});
// passport-local
passport.use(new LocalStrategy(
function(identifiant, motDePasse, done) {
console.log(identifiant); // It's not logging
User.findOne({identifiant:identifiant}).exec(function(err, user) {
if(user) {
return done(null, user);
} else {
return done(null, false);
}
})
}
));
passport.serializeUser(function(user, done) {
if(user) {
done(null, user._id);
}
});
passport.deserializeUser(function(id, done) {
User.findOne({_id:id}).exec(function(err, user) {
if(user) {
return done(null, user);
} else {
return done(null, false);
}
})
});
// route
app.post('/connexion', function(req, res, next){
var auth = passport.authenticate('local', function(err, user) {
if(err) {return next(err);}
if(!user) {res.send({success: false});}
req.logIn(user, function(err) {
if(err) {return next(err);}
res.send({success: true, user: user});
})
});
auth(req, res, next);
});
angular client:
app.controller('uAsideLoginCtrl', function($scope, $http, uIdentity, uNotifier){
$scope.identity = uIdentity;
$scope.signin = function(identifiant, motDePasse){
$http.post('/connexion', {identifiant: identifiant, motDePasse: motDePasse}).then(function(res){
if(res.data.success) {
uIdentity.currentUser = res.data.user;
uNotifier.success("Vous êtes maintenant connecté!");
} else {
uNotifier.error("L'identifiant ou le mot-de-passe est incorrecte.");
}
});
};
});
Here is the mongodb's user row :
{ "_id" : ObjectId("53df7b3b769827786b32dafe"), "identifiant" : "123", "motDePasse" : "123", "__v" : 0 }
I think that it's comming from LocalStrategy. I'm not getting the result of the console.log.
Any brilliant idea, please?
What's wrong, please ?
The problem's not within the code you showed. My guess is that the parameters used in your request to /connexion (I assume it's a regular form with a POST method) are misnamed, because you set custom field names.
From Passport's official docs :
By default, LocalStrategy expects to find credentials in parameters named username and password. If your site prefers to name these fields differently, options are available to change the defaults.
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'passwd'
},
function(username, password, done) {
// ...
}
));
But your name rings a bell, didn't you ask a similar question yesterday, we helped you, and you deleted your post after that ?