Thursday, 11 May 2017

How is it possible for a function handling route to take more than two parameters?

I am new to node js. I was understanding authentication using jwt. As per what I know the request handler in express is something like this

app.post('/login',function(req,res){...});

Below is the snippet that I am confused with.

app.js .

var userController = require('./Controllers/user');
var authController = require('./Controllers/auth');
var tokenController = require('./Controllers/validate');
var deviceController = require('./Controllers/device');

app.post('/login',userController.validate,authController.authorize,userController.login);


If we look carefully, there are 4 parameters to post method. Can anyone please explain how below function works?

app.post('/login',userController.validate,authController.authorize,userController.login);



Also adding the js files that the developer is importing

user.js

exports.validate = function(req,res,next) {
  if(req.body.email === undefined){
      return res.status(401).send({'message':'Email is required'});
  }

  if(req.body.password === undefined){
      return res.status(401).send({'message':'Password is required'});
  }

  next();
};

const login = exports.login = function (req,res){
    User.findOne({email:req.body.email},function(err, user){
        if(err){
            return res.status(401).send(err);
        }
        user.token = jwt.sign(user.password, 'TOPSECRETTTT');
        user.save(function (err,user) {
            if (err) {
                res.send(err);
                return;
            }
            res.status(200).send({email:user.email,loginToken:user.token});
        })
    });
};

auth.js

passport.use(new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password'
    },
    (function(username, password, callback) {
        User.findOne({ email: username }, function(err, user) {
            if (err) {
                return callback(err);
            }

            if (!user) {
                return callback(null, false);
            }

            user.matchPassword(password, function(err, isMatch) {
                if (err) {
                    return callback(err);
                }

                if (!isMatch) {
                    return callback(null, false);
                }

                return callback(null, user);
            });
        });
    })));

exports.authorize = passport.authenticate('local', { session: false });

Let me know if there are any source/links where I can find some more implementation like this.



via Tanmay Awasthi

No comments:

Post a Comment