rasilvap
rasilvap

Reputation: 2159

How to consume data from firebase db in a middleware to authenticate users

What I'm trying to do is to consume data from a firebase databse. I'm trying to achieve that from a middleware, but I couldn't do that. I'm wondering if this is the best way to do this. This is my code:

exports.userExist = function (req, res, next) {
  (async () => {
    try {
      var query = db
        .collection("users")
        .where("user", "==", req.query.user)
        .where("password", "==", req.query.password);
      query.get().then(function (querySnapshot) {
        if (querySnapshot.size > 0) {
          res.json(true);
          next();
        } else {
          res.json(false);
          next();
        }
      });
    } catch (error) {
      return res.status(500).send(error);
    }
  })();
};

My doubt is how can I consume this method from my middleware, I'm trying to do something like that:

  function verifyUser(req, res, next) {
      let user= userController.findUser; //Hi have doubt about of how consume the middelware..

      if(user!=null){
       //The rest of the code.
      }
      next();
   }

Is it the correct approach? or maybe I'm trying to achieve this wrong?

Upvotes: 0

Views: 94

Answers (1)

Eric Guan
Eric Guan

Reputation: 15982

Couple of problems with your code.

  1. There is no need for an async IIFE inside a middleware. The middleware function itself can be an async function.
  2. If you call res.json(), that ENDS the request, and sends the response. You likely don't want that behavior here.
exports.userExist = async function (req, res, next) {
    try {
      var query = db
        .collection("users")
        .where("user", "==", req.query.user)
        .where("password", "==", req.query.password);

      const querySnapshot = await query.get()
      if (querySnapshot.size > 0) {
        // assume the query only returns 1 user?
        req.userObj = querySnapshot.docs[0].data()
      }
      
      next();
    } catch (error) {
      return res.status(500).send(error);
    }
};

Then, in downstream handlers:

  function verifyUser(req, res, next) {
      if (req.userObj) {
        // previous middleware found a user
      } else {
        // previous middleware did not find a user
      }
      next();
   }

Example usage:

app.use(userExist)
app.use(verifyUser)

Upvotes: 1

Related Questions