diff --git a/index.js b/index.js index 1b2c8c3..b233702 100644 --- a/index.js +++ b/index.js @@ -8,16 +8,38 @@ const cleanup = require("./queries/cleanup"); const app = express(); -app.set("trust proxy", "127.0.0.1"); +const allowedOrigins = + process.env.NODE_ENV === "production" + ? ["https://pg-sql.com", "https://notes.pg-sql.com"] + : ["http://localhost:3000"]; + +app.set("trust proxy", process.env.NODE_ENV === "production" ? 1 : 0); app.use( cors({ - origin: - process.env.NODE_ENV === "production" - ? ["https://pg-sql.com", "https://notes.pg-sql.com"] - : ["http://localhost:3000"], + origin: function (origin, callback) { + if (!origin) { + return callback(null, true); + } + if (allowedOrigins.indexOf(origin) === -1) { + const msg = + "The CORS policy for this site does not allow access from the specified origin"; + return callback(new Error(msg), false); + } + return callback(null, true); + }, credentials: true, }) ); + +// app.use( +// cors({ +// origin: +// process.env.NODE_ENV === "production" +// ? ["https://pg-sql.com", "https://notes.pg-sql.com"] +// : ["http://localhost:3000"], +// credentials: true, +// }) +// ); app.use(express.json()); app.use( cookieSession({ @@ -25,10 +47,18 @@ app.use( keys: [keys.cookieKey], sameSite: "Lax", httpOnly: true, - domain: "pg-sql.com", + domain: process.env.NODE_ENV === "production" ? "pg-sql.com" : undefined, }) ); +app.use((req, res, next) => { + console.log("Session:", req.session); + if (!req.session) { + return next(new Error("Session is not set up properly")); + } + next(); +}); + app.post("/provision", require("./provision")); app.post("/query", require("./query")); app.post("/reset", require("./reset")); diff --git a/query.js b/query.js index 4823fd0..a0d05c8 100644 --- a/query.js +++ b/query.js @@ -5,6 +5,11 @@ const touchLogin = require("./queries/touch-login"); module.exports = async (req, res) => { const { id } = req.session; + + console.log("Session:", id); + if (!id) { + return res.status(400).json({ error: "Session ID is missing" }); + } validateId(id); if (!(await dbExists(id))) { @@ -15,6 +20,7 @@ module.exports = async (req, res) => { const client = await createClient(id); try { + console.log("Query:", req.body.query); const result = await client.query(req.body.query); if (Array.isArray(result)) { @@ -36,6 +42,9 @@ module.exports = async (req, res) => { }, ]); } + } catch (err) { + console.error("Query Execution Error:", err); + res.status(500).json({ error: err.message }); } finally { await client.end(); }