Saturday, 22 April 2017

Creating promise for authorizing http requests on node server

I am trying to create a javascript/nodejs function which should be a promise and returns a successful callback if it validates a user else sends the 403 unauthorized response. The reason to make it async is it needs to call my database to validate the api key for the user.

I am aware of a express middleware but I am not able to use it because of some reason. So I am trying to convert that to the async promise function which validates the request and then executes the request.

My express middleware function currently look like this. Which I am converting to a promise function:

const validateApiKey = (req, res, next) => {

        console.log('Check if request is authorized with API Key');

        if (!req.headers.authorization) {
            res.status(403).send('Unauthorized');
            return;
        }
        const apiKey = req.headers.authorization.split('Key=')[1];
        console.log('api key: ' + apiKey);

        if (apiKeyUserMap[apiKey] != null) {
            admin.database().ref('apiKeyMapping/' + apiKey).once('value', function(dataSnapshot) {
                console.log('user: ' + dataSnapshot.val());
                req.uid = dataSnapshot.val();
                next();
            });
        } else {
            console.error('Error while getting uid from API key');
            res.status(403).send('Unauthorized');
        }
    });
};

As, I am firebase function, the function would look something like this:

exports.helloUser= functions.https.onRequest((req, res) => {
    return validateApiKey(req, res).then((req,res) => {
    // do whatever you like
    });
});

Now, I am getting confused how to handle that res.status(403).send('Unauthorized') part. This validation will be there on all of my functions.

So how to send 403 response. Like, if I send from the Promise function, will the then() function or catch() function be called? Or do I need to handle all 403 inside all of my firebase functions instead of inside validateApiKey function?



via kirtan403

No comments:

Post a Comment