LP496 LP496 - 1 year ago 66
Javascript Question

Passport.js Execution

I have been looking at some

tutorials online but haven't grasped a clear understanding of what is happening. Can someone help me clear my doubts below? Please read the paragraph at the bottom first.

So assuming I set up everything correctly, this is the login strategy:

passport.use('login', new LocalStrategy({
passReqToCallback : true
function(req, username, password, done) {
// check in mongo if a user with username exists or not
User.findOne({ 'username' : username },
function(err, user) {
// In case of any error, return using the done method
if (err)
return done(err);
// Username does not exist, log error & redirect back
if (!user){
console.log('User Not Found with username '+username);
return done(null, false,
req.flash('message', 'User Not found.'));
// User exists but wrong password, log the error
if (!isValidPassword(user, password)){
console.log('Invalid Password');
return done(null, false,
req.flash('message', 'Invalid Password'));
// User and password both match, return user from
// done method which will be treated like success
return done(null, user);

Now in my app.js (server) I have this as one of my routes:

/* Handle Login POST */
router.post('/login', passport.authenticate('login', {
successRedirect: '/home',
failureRedirect: '/',
failureFlash : true

Now in my AJS file:

app.controller('loginController', function($scope) {
var user = $resource('/login');

$scope.createUser = function() {
var User = new user();
User.username = $scope.usernameVar;
User.password = $scope.passwordVar;

Please read this first (Instead of going through the code first):

So when the user clicks on the login button on the login page the
function above is run (in my AJS file). Then I create a resource object for the endpoint
and when I call save on that it will run the route for that
endpoint on my server (app.js). Then in my server it will
passport.authenticate('login', ...
which will run the passport middleware.

Now my question is:

In the
strategy where the do values for the variables
req, username, and password
come from in the callback to that strategy. Do I have to explicitly pass the username and password the user enters in the textfield on my front end. Like I have a two way data binding for those two textfields in AJS view. If so how do I pass those username and password values?

Do these two lines in my AJS controller
User.username = $scope.usernameVar;
User.password = $scope.passwordVar;
attach the usernameVar and passwordVar values to the
object on my server for the route

Answer Source

If you have a form with action to post to your path /login, and have input names labeled after your username and password, the submit button will pass the values along to your passport code.

Check out Form in the docs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download