I have a Node JS functions created in webtask with serverless framework. The API routes are protected and to use it I need to pass a firebase token that I send from client side. That part is working fine, the token gets verified and then I can access the routes.
My problem is with certain routes in which I use axios
or coin-ticker
. The function works fine until it has to execute the axios code and then I get an error.
It just happens when the routes are protected because if I try to execute the same code without protecting the routes, then the code works fine.
'use strict';
const admin = require('firebase-admin');
const express = require('express');
var fromExpress = require('webtask-tools').fromExpress;
const app = express();
var bodyParser = require('body-parser');
const axios = require('axios');
const coinTicker = require('coin-ticker');
admin.initializeApp({
credential: admin.credential.cert({
projectId: "<PROJECT_ID>",
clientEmail: "foo@<PROJECT_ID>.iam.gserviceaccount.com",
privateKey: "-----BEGIN PRIVATE KEY-----\n<KEY>\n-----END PRIVATE KEY-----\n"
}),
databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});
const authenticate = (req, res, next) => {
if (!req.headers.authorization/* || !req.headers.authorization.startsWith('Bearer ')*/) {
res.status(403).send('Unauthorized!');
return;
}
const idToken = req.headers.authorization/*.split('Bearer ')[1]*/;
admin.auth().verifyIdToken(idToken).then(decodedIdToken => {
req.user = decodedIdToken;
next();
}).catch(error => {
res.status(403).send('Unauthorized');
});
};
app.use(authenticate);
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/messages', (req, res) => {
res.send(req.body.numero)
});
app.post('/messages', (req, res) => {
res.send(req.body.numero)
});
//THIS IS THE ONE FAILING
//I know this code it's not useful but it's just an example
app.post('/ltc', (req,res) => {
axios.get('https://www.surbtc.com/api/v2/markets/btc-clp/ticker')
.then(res => {
res.send(res)
})
.catch(error => {
res.sendStatus(500)
})
});
module.exports = fromExpress(app);
Thanks for your help!
PS: I'm using the google credentials.