I am reading an article about using passport-local-mongoose for authentication. Article
In this article I found this line of code that do register the user and log them in
app.post('/register', function(req, res) {
Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
if (err) {
return res.render('register', { account : account });
}
passport.authenticate('local')(req, res, function () {
res.redirect('/');
});
});
});
And the part that confuse me is this
passport.authenticate('local')(req, res, function () {
res.redirect('/');
});
First, I don't understand the part that go after passport.authenticate()
. It doesn't look like a callback or IIFE.
Second, as far as I know, passport.authenticate()
is a middleware (sorry if I'm wrong). Should we use it as a function like that.
My best explanation for this is because in the article have defined above
passport.use(new LocalStrategy(Account.authenticate()))
Because of that, passport.authenticate()
now will call Account.authenticate()
. The strange part is, authenticate()
require a password, which we didn't provide it any. Maybe it return a Promise, but the part I said above doesn't look like a Promise.
So what is that part is, and is it a good practice to actually sign a user in?
Lets talk about that weird part first:
TLDR: As the first commenter mentioned passport.authenticate return a function.
How do we call a function? Like this: functionName(param1, param2, callbackMaybe);
. You see no problem with that right?
Now, take a look at the code below
function a() {
return function b() {
console.log("Hi there!");
}
}
Function a
returning function b
. How would you the the Hi there!
in your console? You have to do it like this a()()
.
You can se it in this way:
let b = a(); // Since, a returns a function so, b is now a function.
b();
Same here, passport.authenticate('local')
returning a function that takes 3 parameters where last one is a callback function. In terms of express the 3rd parameter is the next()
function. I believe you know the usage of next()
function. You are sending function () { res.redirect('/'); }
as a callback. What this callback does it redirect you to this '/'
route.
Second part of your question
Now a days, I do not see any website auto login user after signing up.
Hope it helps.