I am kinda new in node. recently I decided to create a blog system and it has an authorization system which is created by passport module and local strategy. I used passport documentation and some video tutorials to design it but I can't understand how does it work, I don't understand the logic. I have a login form which has two fields (username,password) and a submit button. you can see my login.jade code here. it is written in jade templating language and used semantic-UI(something like bootstrap).
form.ui.form(method="POST",action="")
div.field
label Username
div.ui.left.icon.input
i.user.icon
input(type="text",name="username",placeholder="username")
div.field
label Password
div.ui.left.icon.input
i.lock.icon
input(type="password",name="password",placeholder="password")
button.ui.primary.button(type="submit") log-in
and here is my passport local strategy
passport.use(new localStrategy(function(username,password,done){
User.checkUserName(username,function(err,user){
if (err) throw err;
if (!user) {
console.log('unknown user');
return done(null,false,{message:'user not found'});
}
if(user.password!=password){
return done(null,false , {message : 'password is wrong'});
}
return done (null,user);
});
}));
checkUserName is a function in my models (user.js) which finds the username in the database.
module.exports.checkUserName= function(username,callback){
User.findOne({username:username},callback);
}
now I don't understand how does the localstrategy work. how does it understand which field in my login form is for username and which field is for the password? it only accepts two arguments (username, password) but I don't know how it specifies where are these arguments come from and how it understands that these must be my login form credentials. I would be very thankful if someone explains to me what is happening here.
If you're using username / password authentication, by default localStrategy() uses input fields with name="username"
and name="password"
. So, your form is correct.
If you want to use other field names, you can change the defaults. Read this. http://www.passportjs.org/docs/username-password/#parameters
I'd like to point out that you should use a hashing scheme for your passwords, rather than storing them in plain text in your database. Because, Ashley Madison.
This is a well-designed robust hashing scheme. There are others.