Home > Back-end >  Passing Variable from Another Module's Function
Passing Variable from Another Module's Function

Time:01-23

I'm new with JS/NodeJs.

I managed to authenticate with Google Firebase

verifyFirebase.js:

  function checkAuth(req, res, next) {
    if (req.header('auth-token')) {
      admin.auth().verifyIdToken(req.header('auth-token'))
        .then((decodedToken) => {
            //return uid
            let uid = decodedToken.uid
          next()
        }).catch((err) => {
            console.log(err);
          res.status(403).send('Unauthorized')
        });
    } else {
       
      res.status(403).send('Unauthorized')
    }
  }



module.exports.checkAuth = checkAuth;

and I'm using it on the another files as below;

routes.js

const verify_firebase = require('./verifyFirebase').checkAuth;


router.get('/', verify_firebase, (req,res) => {
    res.json("verified");
})

The "/" route is protected with verify_firebase function coming from verifyFirebase.js. How can I access uid variable from routes.js? Because I need to access this uid within secured route.

CodePudding user response:

i think this might work

 function checkAuth(req, res, next) {
    if (req.header('auth-token')) {
      admin.auth().verifyIdToken(req.header('auth-token'))
        .then((decodedToken) => {
            //return uid
            let uid = decodedToken.uid
            req.decoded = {
              uid:uid
            };
          next()
        }).catch((err) => {
            console.log(err);
          res.status(403).send('Unauthorized')
        });
    } else {
       
      res.status(403).send('Unauthorized')
    }
  }



module.exports.checkAuth = checkAuth;

CodePudding user response:

You could set the uid variable as req.uid and use it within your routes.js file, like this:

verifyFirebase.js

...
        .then((decodedToken) => {
            //return uid
            req.uid = decodedToken.uid
          next()
        }).catch((err) => {
            console.log(err);
...

routes.js

const verify_firebase = require('./verifyFirebase').checkAuth;


router.get('/', verify_firebase, (req,res) => {
    console.log('my uid:', req.uid);
    res.json("verified");
})

Please, keep in mind that if you're gonna use typescript, you'll also need to define the correct type for it.

  • Related