index.js
1 const express = require("express"); 2 const fs = require("fs"); 3 const path = require("path"); 4 const admin = require("firebase-admin"); 5 const cors = require("cors"); 6 7 const app = express(); 8 const PORT = 10000; 9 10 // initialize env files 11 require("dotenv").config(); 12 13 // allow requests from the frontend 14 app.use(cors({ 15 origin: process.env.HOST_URL 16 })); 17 18 // initialize admin if not already 19 if (!admin.apps.length) { 20 admin.initializeApp({ 21 credential: admin.credential.cert(require("./serviceAccount.json")), 22 databaseURL: process.env.FIREBASE_DATABASE_URL 23 }); 24 } 25 26 const db = admin.database(); 27 28 // CORS blocks requests from other urls, however, we can lock this down more 29 // by preventing direct requests! 30 app.use((req, res, next) => { 31 const origin = req.headers.origin || "Unknown origin"; 32 const referer = req.headers.referer || "Unkown referer."; 33 const ip = req.headers["x-forwarded-for"] || req.ip; 34 35 console.log(`[${new Date().toISOString()}] ${req.method} ${req.originalUrl}`); 36 console.log(` Origin: ${origin}`); 37 console.log(` Referer: ${referer}`); 38 console.log(` IP: ${ip}`); 39 40 // if trying to access a restricted api, prevent. 41 // we can allow our host site to access the auride api, but not anyone else 42 if (req.originalUrl.startsWith("/api/auride/") && origin !== process.env.HOST_URL) 43 return res.status(403).json({ status: "You are attempting to access a restricted API. Please do not do this." }); 44 45 // otherwise, keep it going. 46 next(); 47 }); 48 49 // run auride's private backend 50 const aurideRoutes = path.join(__dirname, "auride"); 51 fs.readdirSync(aurideRoutes).forEach(file => { 52 console.log(aurideRoutes); 53 54 console.log(`Starting ${file}...`); 55 if (file.endsWith(".js")) { 56 const route = require(path.join(aurideRoutes, file)); 57 app.use(route); 58 } 59 }); 60 61 // if called the root... 62 app.get("/", (req, res) => { 63 res.json({ message: "Hi! Thanks for your interest in using the Auride API. However, it is currently unavailable for public use. We'll let you know on our profile when it's ready @ https://auride.xyz/u/auride" }) 64 65 // TODO: make a public api 66 //res.json({ message: "Hi! Please feel free to look at our docs to see how to use our API." }); 67 }); 68 69 // simple health check 70 app.get("/health", (req, res) => { 71 res.status(200).json({ status: "OK" }); 72 }); 73 74 // then, run the app 75 app.listen(PORT, "0.0.0.0", () => { 76 console.log(`Auride's server is running successfully at port ${PORT}`); 77 });