user7961479
user7961479

Reputation:

where callback is defined in this code

This is a code snippet for authentication using passports js, which is as follow,

// Middleware
passport.use('local-login', new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
}, function(req, email, password, done){
    User.findOne({ email: email }, function(err, user) {
        if(err) return done(err)
        if(!user) {
            return done(null, false, req.flash('loginMessage', 'No user has been found'))
        }
        if(!user.comparePassword(password)) {
            return done(null, false, req.flash('loginMessage', 'Incorrect Username/Password'))
        }
        return done(null, user)
    })
}))

In the above code, done is a callback function used in multiple places, but I want to know where is this (done) callback function defined, what I am seeing is that it is passed as an argument and then called, so my basic question is how can I know what this callback will do or where is it is defined. It is supposed to perform some action. So where it is defined?

Upvotes: 0

Views: 56

Answers (4)

Franceso Russo
Franceso Russo

Reputation: 53

According with http://www.passportjs.org/docs/basic-digest/ you call "done" function to provide an user to passport. If you want to know where fuction is defined, you can read source code of "use" method

Upvotes: -1

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

Passport is a connect based framework. When you define a middle-ware like this done is the next function in the pipeline.

For example in a express route we can use middlewares like this.

app.use('/route', middleWare1, middleWare2,..., route)

now the middlewares are kinda defined like this

const middleWare1 = (req, res, next)=> {
    //do some work
    next()
}

If next is called it will go to the next middleware. done is like that. It will pass the req to the next middleware in the pipeline.

And node has a convention to pass the error as first and data as second argument in a callback.

Upvotes: 0

Tzook Bar Noy
Tzook Bar Noy

Reputation: 11677

You don't need to worry about where the "done" callback is called.

It is an internal callback that is used by "passport"

That is your code way to tell "passport" the result of the "login action"

Is the user verified?

  • if so, call the callback with error=null and user data
  • if not, call the callback with the error

Upvotes: 0

Quentin
Quentin

Reputation: 943230

how can I know what this callback will do

The passport documentation should tell you everything you need to know in order to use it properly.

or where is it is defined

Somewhere in the source code to passport.

Upvotes: 0

Related Questions