I have just started learning express. I am adding basic authentication using passport js. I have followed this documentation. It is working a little bit odd on error messages. When the username is correct and password is wrong, it doesn't add any messages to session. It just has basic info like path.
app.post("/login",(req,res)=>{
const user = new User({
username:req.body.username,
password:req.body.password
});
console.log(req.session);
req.login(user,function(err){
if(err){
console.log(err);
}
else{
passport.authenticate("local",{ failureRedirect: '/login', failureMessage: true })(req,res,function(){
res.redirect("/secrets");
});
}
});
});
When the username is wrong, it adds message to session but it doesn't reload properly. it doesn't reload at all to "/login". I have to literally kill the process and then this session data is added.
It doesn't seem to work at all. Kindly help me with dealing both of errors, i.e. right username wrong password and wrong username wrong password.
I don't think you use that req.login function correctly.
I think you are misunderstand between login and authentication
What you are thinking is if login fail then authenticate again while actually, you need to authenticate user first, then login after
So the flow, step by step will be:
authenticationenter your system. This called loginHere is the document you can follow to understand how passport work.
https://www.passportjs.org/concepts/authentication/downloads/html/ (As you are new to express, make sure you understand the General section thoroughly - Middleware and Strategy are key concepts)
https://www.passportjs.org/tutorials/password/ (this is a practical version of the above document)