Snippets

vborshchov auth

Created by Victor (King) Borshchov
// Fire a query to your DB and check if the credentials are valid
    var dbUserObj = auth.validate(username, password);
   
    if (!dbUserObj) { // If authentication fails, we send a 401 back
      res.status(401);
      res.json({
        "status": 401,
        "message": "Invalid credentials"
      });
      return;
    }

    if (dbUserObj) {

      // If authentication is success, we will generate a token
      // and dispatch it to the client

      res.json(genToken(dbUserObj));
    }

  },

  validate: function(username, password) {
    var dbUserObj;
    User.findOne({name: username}, function(err, user) {
      if (user) {
        user.comparePassword(password, function(err, isMatch) {
          if (err) next(err);
          if (isMatch) {
            console.log("in validation");
            dbUserObj = {
              name: user.name,
              admin: user.admin
            };
          }
        });
      }
    });
    return dbUserObj;
  },

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.