Reputation: 2625
I came to know the use of authenticate method in passport.js from the below link http://passportjs.org/guide/authenticate/
In my project I have the below code:
app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { console.log(err); return next(err) }
if (!user) {
return res.json(400, info);
}
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.json(200, {user_id: user._id, url:"/user/home"});
});
})(req, res, next);
});
I have a call to the /login url in another file, like below
$http.post('/login', $scope.user).
success(function(data, status, headers, config) {
$window.location.href= data.url ? data.url : '/';
$scope.view.loading = false;
}).error(function(data, status, headers, config) {
console.log(data);
$scope.view.loading = false;
$scope.view.submitted = true;
$scope.view.serverError=data.message ? data.message : "Server Error!";
});
My doubt here is , how come the passport.authenticate is aware of the user credentials. While calling http.post, we are also sending $scope.user. But that is only 'data'. How come passport.authenticate is aware of the object 'user'?
Upvotes: 2
Views: 4130
Reputation: 34286
Not 100% sure of what you're asking exactly, but I'll give it a shot.
You are responsible for telling Passport if a username/password pair matches, and then giving Passport the user object that corresponds to the given username (or email or whatever). This is done in: passport.use(new LocalStrategy( ... ));
where you specify this logic. (You can find example code on the official website here on how to do this.) Passport then serialises this user object in the session, again by logic that you specify:
passport.serializeUser(function (user, done) {
// Only store the user id in the session
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
// Find the user with the given id
User.find(id).done(function (err, user) {
done(err, user);
});
});
The user
object that passport passes to you in the callback function to passport.authenticate
is the very same user
object that you gave passport as a result of the local strategy.
So here's the breakdown of events:
passport.authenticate(...)
by giving it the req
, res
, and next
objects given to you from the handler.passport.use(new LocalStrategy(...))
. If it was given a valid user
object as a result of the logic process, then passport will pass this object to the callback function so that you can return back details of the user (or whatever).Upvotes: 6