Skip to content

Instantly share code, notes, and snippets.

@thiagosouza
Last active May 30, 2019 21:59
Show Gist options
  • Save thiagosouza/ec403a4c0646eef26f066e3adade724a to your computer and use it in GitHub Desktop.
Save thiagosouza/ec403a4c0646eef26f066e3adade724a to your computer and use it in GitHub Desktop.
API Firebase Express
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')
console.log(process.env.NODE_ENV);
if (process.env.NODE_ENV === "production") {
admin.initializeApp();
}
else {
var serviceAccount = require("../../serviceaccount.json"); //ask this file to the project owner
var firebaseApp = admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://PROJECTNAME.firebaseio.com/"
});
}
// export GCLOUD_PROJECT=paradigma-dev-firebase
var db = admin.database();
const express = require('express');
const app = express();
const authenticate = async (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];
try {
const decodedIdToken = await admin.auth().verifyIdToken(idToken);
// console.log(decodedIdToken);
req.user = decodedIdToken;
next();
return;
} catch (e) {
res.status(403).send('Unauthorized');
return;
}
};
// domain restriction
// var whitelist = ["https://SITE.COM"];
// var corsOptions = { origin: (origin, callback) => (whitelist.indexOf(origin) !== -1 || !origin) ? callback(null, true) : callback(new Error('Not allowed by CORS')) }
// open for all domains
var corsOptions = { origin: false }
app.use(cors(corsOptions));
app.use(authenticate);
// var user = {
// name: 'Thiago Souza',
// picture: 'https://lh4.googleusercontent.com/-VdKZ1Kor6ek/AAAAAAAAAAI/XXXAAAXXX98/JZfhKFQ8hfI/photo.jpg',
// premium: true,
// iss: 'https://securetoken.google.com/PROJECT',
// aud: 'PROJECT',
// auth_time: 1558646048,
// user_id: 'UID',
// sub: 'UID',
// iat: 1558646048,
// exp: 1558649648,
// email: 'EMAIL',
// email_verified: true,
// firebase: {
// identities: { 'google.com': [Array], email: [Array] },
// sign_in_provider: 'google.com'
// },
// uid: 'UID'
// }
// GET /api/post/{postId}
// Get details about a message
app.get('/post/:postId', async (req, res) => {
console.log("logged user", req.user);
const { postId } = req.params;
const locale = req.query.locale || "pt-BR";
try {
var post = await firebaseGetData(`/flamelink/environments/production/content/posts/${locale}/${postId}`);
if (!post) res.set('Cache-Control', 'private, max-age=300').status(404).json({ errorCode: 404, errorMessage: `post '${postId}' not found` });
} catch (error) {
console.log('Error getting post details', postId, error.message);
return res.sendStatus(500);
}
return res.status(200).json(post);
});
app.get('/charts/', async (req, res) => {
console.log("logged user", req.user);
// const { postId } = req.params;
const locale = req.query.locale || "pt-BR";
try {
var charts = await firebaseGetDataArray(`/flamelink/environments/production/content/charts/${locale}`);
if (!charts) res.set('Cache-Control', 'private, max-age=300').status(404).json({ errorCode: 404, errorMessage: `charts not found` });
return res.status(200).json(chartsResult);
} catch (error) {
console.log('Error getting post details', error.message);
return res.sendStatus(500);
}
});
// Expose the API as a function
exports.api = functions.https.onRequest(app);
async function firebaseGetData(path) {
console.log("getData", path);
try {
let dataRef = await db.ref(path).limitToLast(50).once("value");
console.log("dataRef.val()", dataRef.val());
return (!dataRef.exists()) ? null : dataRef.val();
} catch (error) {
console.info(error)
return null;
}
}
async function firebaseGetDataArray(path) {
console.log("getData", path);
try {
let dataRef = await db.ref(path).once("value");
var data = [];
dataRef.forEach(item => data.push(item.val()))
return data;
} catch (error) {
console.info(error)
return null;
}
}
{
"name": "functions",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.0",
"firebase-admin": "^8.0.0",
"firebase-functions": "^2.3.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment