webupdatev1
This commit is contained in:
@@ -1,21 +1,48 @@
|
||||
const { query } = require("../config/database");
|
||||
|
||||
// Whitelist of allowed table names to prevent SQL injection
|
||||
const ALLOWED_TABLES = [
|
||||
"products",
|
||||
"product_images",
|
||||
"portfolioprojects",
|
||||
"blogposts",
|
||||
"pages",
|
||||
"adminusers",
|
||||
"roles",
|
||||
"uploads",
|
||||
"media_folders",
|
||||
"team_members",
|
||||
"site_settings",
|
||||
"session",
|
||||
];
|
||||
|
||||
// Validate table name against whitelist
|
||||
const validateTableName = (table) => {
|
||||
if (!ALLOWED_TABLES.includes(table)) {
|
||||
throw new Error(`Invalid table name: ${table}`);
|
||||
}
|
||||
return table;
|
||||
};
|
||||
|
||||
const buildSelectQuery = (
|
||||
table,
|
||||
conditions = [],
|
||||
orderBy = "createdat DESC"
|
||||
) => {
|
||||
validateTableName(table);
|
||||
const whereClause =
|
||||
conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
||||
return `SELECT * FROM ${table} ${whereClause} ORDER BY ${orderBy}`;
|
||||
};
|
||||
|
||||
const getById = async (table, id) => {
|
||||
validateTableName(table);
|
||||
const result = await query(`SELECT * FROM ${table} WHERE id = $1`, [id]);
|
||||
return result.rows[0] || null;
|
||||
};
|
||||
|
||||
const getAllActive = async (table, orderBy = "createdat DESC") => {
|
||||
validateTableName(table);
|
||||
const result = await query(
|
||||
`SELECT * FROM ${table} WHERE isactive = true ORDER BY ${orderBy}`
|
||||
);
|
||||
@@ -23,6 +50,7 @@ const getAllActive = async (table, orderBy = "createdat DESC") => {
|
||||
};
|
||||
|
||||
const deleteById = async (table, id) => {
|
||||
validateTableName(table);
|
||||
const result = await query(
|
||||
`DELETE FROM ${table} WHERE id = $1 RETURNING id`,
|
||||
[id]
|
||||
@@ -31,6 +59,7 @@ const deleteById = async (table, id) => {
|
||||
};
|
||||
|
||||
const countRecords = async (table, condition = "") => {
|
||||
validateTableName(table);
|
||||
const whereClause = condition ? `WHERE ${condition}` : "";
|
||||
const result = await query(`SELECT COUNT(*) FROM ${table} ${whereClause}`);
|
||||
return parseInt(result.rows[0].count);
|
||||
@@ -42,4 +71,5 @@ module.exports = {
|
||||
getAllActive,
|
||||
deleteById,
|
||||
countRecords,
|
||||
validateTableName,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user