How should i use req inside non-middleware (Passport.js)?

165 views Asked by At

I want to update user's ip every time he or she logs in.

I was informed that only middlewares get req, res, and next parameters, but I am using passportjs, which should come first to authorize the user. How should I update user data?

Below is my code block of passport.js using Basic Strategy.

passport.use(new BasicStrategy(
    function(username, password, callback){
        User.findOne({username:username}, function(err,user){
            if(err){return callback(err);}
            //no user found with the email
            if(!user){return callback(null, false);}
            user.verifyPassword(password, function(err,isMatch){
                if(err){ return callback(err);}
                // password did not match
                if(!isMatch){return callback(null,false);}
                //success

                // UPDATE USER INFO
                user.token = jwt.sign(user.email+Date.now(), "testtoken");//should change later
                user.last_login = Date.now();

                // I AM TRYING TO UPDATE THIS WITH req.ip
                user.last_ip = req.ip;

                user.save(function(err, user1){
                    if(err) return callback(err);
                    return callback(null,user);
                });
            });
        });
    }
));
1

There are 1 answers

0
robertklep On BEST ANSWER

You can configure BasicStrategy to pass the request as first argument:

passport.use(
  new BasicStrategy({ passReqToCallback : true }, function(req, username, password, callback) {
    ...
  })
);

This (sadly) isn't well documented, but I believe most Passport strategies support it (see also).