var admin = require("firebase-admin"); const path = require("path"); require("dotenv").config({ path: path.resolve( process.cwd(), `.env.${process.env.NODE_ENV || "development"}` ), }); var serviceAccount = require(process.env.FIREBASE_ADMINSDK_JSON); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: process.env.FIREBASE_DATABASE_URL, }); exports.admin = admin; exports.sendNotification = (req, res) => { var registrationToken = "fqIWg8ENDFyrRrMWJ1sItR:APA91bHirdZ05Zo66flMlvala97SMXoiQGwP4oCvMwd-vVrSauD_WoNim3kXHGqyP-bzENjkXwA5icyUAReFbeHn6dIaPcbpcsXuY73-eJAXvZiu1gIsrd1BOsnj3dEMT7Q4F6mTPth1"; var message = { notification: { title: "The Title", body: "The Body" }, data: { jobid: "1234", }, token: registrationToken, }; // Send a message to the device corresponding to the provided // registration token. admin .messaging() .send(message) .then((response) => { // Response is a message ID string. console.log("Successfully sent message:", response); }) .catch((error) => { console.log("Error sending message:", error); }); res.sendStatus(200); }; exports.validateFirebaseIdToken = async (req, res, next) => { console.log("Check if request is authorized with Firebase ID token"); if ( (!req.headers.authorization || !req.headers.authorization.startsWith("Bearer ")) && !(req.cookies && req.cookies.__session) ) { console.error("Unauthorized attempt. No authorization provided."); res.status(403).send("Unauthorized"); return; } let idToken; if ( req.headers.authorization && req.headers.authorization.startsWith("Bearer ") ) { // console.log('Found "Authorization" header'); // Read the ID Token from the Authorization header. idToken = req.headers.authorization.split("Bearer ")[1]; } else if (req.cookies) { //console.log('Found "__session" cookie'); // Read the ID Token from cookie. idToken = req.cookies.__session; } else { // No cookie console.error("Unauthorized attempt. No cookie provided."); res.status(403).send("Unauthorized"); return; } try { const decodedIdToken = await admin.auth().verifyIdToken(idToken); //console.log("ID Token correctly decoded", decodedIdToken); req.user = decodedIdToken; next(); return; } catch (error) { console.error("Error while verifying Firebase ID token:", error); res.status(403).send("Unauthorized"); return; } };