Skip to content

Commit

Permalink
seguridad en server Cross-Site Scripting (XSS)
Browse files Browse the repository at this point in the history
  • Loading branch information
RyuDSora committed Jul 29, 2024
1 parent 3e73646 commit f96ca80
Show file tree
Hide file tree
Showing 10 changed files with 81 additions and 271 deletions.
46 changes: 24 additions & 22 deletions client/src/AccountComponent.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,29 +25,31 @@ function AccountComponent() {

useEffect(() => {
const fetchUser = async () => {
if (decryptValue(Cookies.get('$3s1.4'),encryptionKey)) {
try {
const response = await axios.get(`${URIUser}${decryptValue(Cookies.get('#gt156'),encryptionKey)}`);
const data = response.data;
const formattedDate = format(new Date(data.birth), 'yyyy-MM-dd');
data.birth = formattedDate;
if (data.role === 'tutor') {
setIsTutor(true);
const fetchTutor = async () => {
try {
const response = await axios.get(`${uritutor}/${data.id}`);
setTutorData(response.data);
setFormDataTutor(response.data);
} catch (error) {
console.log(error);
}
};
fetchTutor();
if(Cookies.get('$3s1.4')){
if (decryptValue(Cookies.get('$3s1.4'),encryptionKey)) {
try {
const response = await axios.get(`${URIUser}${decryptValue(Cookies.get('#gt156'),encryptionKey)}`);
const data = response.data;
const formattedDate = format(new Date(data.birth), 'yyyy-MM-dd');
data.birth = formattedDate;
if (data.role === 'tutor') {
setIsTutor(true);
const fetchTutor = async () => {
try {
const response = await axios.get(`${uritutor}/${data.id}`);
setTutorData(response.data);
setFormDataTutor(response.data);
} catch (error) {
console.log(error);
}
};
fetchTutor();
}
setUser(data);
setFormData(data);
} catch (error) {
console.error(error);
}
setUser(data);
setFormData(data);
} catch (error) {
console.error(error);
}
}
};
Expand Down
18 changes: 10 additions & 8 deletions client/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,16 @@ function App() {
const [userID, setUserID] = useState(0);

useEffect(() => {
const session = decryptValue(Cookies.get('$3s1.4'),encryptionKey)
if (session) {
const storedLoggedIn = localStorage.getItem('token');
if (storedLoggedIn) {
setIsLoggedIn(true);
const id = decryptValue(Cookies.get('#gt156'),encryptionKey);
setUserID(parseInt(id));
}
if(Cookies.get('$3s1.4')){
const session = decryptValue(Cookies.get('$3s1.4'),encryptionKey)
if (session) {
const storedLoggedIn = localStorage.getItem('token');
if (storedLoggedIn) {
setIsLoggedIn(true);
const id = decryptValue(Cookies.get('#gt156'),encryptionKey);
setUserID(parseInt(id));
}
}
}
}, []);

Expand Down
28 changes: 15 additions & 13 deletions client/src/NavBarT.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,21 @@ function NavBarT({ isLoggedIn }) {

//verificacion de sesion activa para verificar el role del usuario logueado
useEffect(() => {
const session = decryptValue(Cookies.get('$3s1.4'),encryptionKey)
if (session) {
const role = decryptValue(Cookies.get('&0l3'),encryptionKey)
setUserL(decryptValue(Cookies.get('@u53r'),encryptionKey) || '');
setUserI(decryptValue(Cookies.get('1m@&34'),encryptionKey))
if (role === 'administrador') {
setAdmin(true);
}
if (role === 'tutor') {
setTutor(true);
}
if (role === 'estudiante') {
setUser(true);
if(Cookies.get('$3s1.4')){
const session = decryptValue(Cookies.get('$3s1.4'),encryptionKey)
if (session) {
const role = decryptValue(Cookies.get('&0l3'),encryptionKey)
setUserL(decryptValue(Cookies.get('@u53r'),encryptionKey) || '');
setUserI(decryptValue(Cookies.get('1m@&34'),encryptionKey))
if (role === 'administrador') {
setAdmin(true);
}
if (role === 'tutor') {
setTutor(true);
}
if (role === 'estudiante') {
setUser(true);
}
}
}
}, []);
Expand Down
23 changes: 12 additions & 11 deletions client/src/PasswordReset.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,18 @@ const PasswordReset = () => {
const [successMessage, setSuccessMessage] = useState("");

useEffect(() => {
if (decryptValue(Cookies.get('$3s1.4'),encryptionKey)) {
const fetchUser = async () => {
try {
const response = await axios.get(`${URIUser}${decryptValue(Cookies.get('#gt156'),encryptionKey)}`);
setUser(response.data);
//setFormData(response.data); // Set formData with initial user data
} catch (error) {
console.log(error);
}
};
fetchUser();
if(Cookies.get('$3s1.4')){
if (decryptValue(Cookies.get('$3s1.4'),encryptionKey)) {
const fetchUser = async () => {
try {
const response = await axios.get(`${URIUser}${decryptValue(Cookies.get('#gt156'),encryptionKey)}`);
setUser(response.data);
} catch (error) {
console.log(error);
}
};
fetchUser();
}
}
}, []);
// Función para manejar el cambio de contraseña
Expand Down
7 changes: 0 additions & 7 deletions client/src/components/Urls.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,7 @@ var originS = 'https://tutorias-five.vercel.app';//partes[0] + ":" + partes[1];
export const url = originS + PuertoBackend;

//urls para trabajar con tablas en general
export const URIgetTablesColumns = url + '/tables/get-tables-columns';
export const URIaddTables = url + '/tables/create-table/'; //crear una tabla en especifico
export const URIcheckTables = url + '/tables/check-table/'; //verificar si una tabla ya esxiste
export const URIgetTables = url + '/tables/get-tables/'; //ver todas las tablas
export const URIdropTables = url + '/tables/drop-table/'; //eliminar una tabla
export const URIUpdateTables = url + '/tables/update-table/'; //actualizar una tabla


export const URUsql = url + '/sql/execute';

//user
Expand Down
22 changes: 12 additions & 10 deletions client/src/hoc/withAuth.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,21 @@ import { encryptionKey, decryptValue } from '../components/hashes';

const withAuth = (WrappedComponent, allowedRoles) => {
return (props) => {
const session = decryptValue(Cookies.get('$3s1.4'),encryptionKey);
const role = decryptValue(Cookies.get('&0l3'),encryptionKey)
const userRole = session ? role || '' : '';
if(Cookies.get('$3s1.4')){
const session = decryptValue(Cookies.get('$3s1.4'),encryptionKey);
const role = decryptValue(Cookies.get('&0l3'),encryptionKey)
const userRole = session ? role || '' : '';

if (!session) {
return <Navigate to="/" replace />;
}

if (!session) {
return <Navigate to="/" replace />;
}
if (!allowedRoles.includes(userRole)) {
return <Navigate to="/" replace />;
}

if (!allowedRoles.includes(userRole)) {
return <Navigate to="/" replace />;
return <WrappedComponent {...props} />;
}

return <WrappedComponent {...props} />;
};
};

Expand Down
184 changes: 4 additions & 180 deletions server/controllers/tableController.js
Original file line number Diff line number Diff line change
@@ -1,181 +1,5 @@
import pool from '../database/db.js';

// Crear una tabla con columnas y claves foráneas opcionales
export const createTable = async (req, res) => {
const { tableName, columns, foreignKeys } = req.body;
const client = await pool.connect();

try {
// Construir la definición de la tabla con columna 'id' como llave primaria
const createTableQuery = `
CREATE TABLE IF NOT EXISTS ${tableName} (
id SERIAL PRIMARY KEY,
${columns.map(column => {
const length = column.length ? `(${column.length})` : '';
return `${column.name} ${column.type}${length}`;
}).join(', ')}
)
`;
await client.query(createTableQuery);

// Agregar claves foráneas si existen
if (foreignKeys && foreignKeys.length > 0) {
for (const fk of foreignKeys) {
const addForeignKeyQuery = `
ALTER TABLE ${tableName}
ADD CONSTRAINT fk_${fk.column}
FOREIGN KEY (${fk.column})
REFERENCES ${fk.references.table}(${fk.references.column})
`;
await client.query(addForeignKeyQuery);
}
}

res.status(201).send(`Table ${tableName} created successfully.`);
} catch (error) {
console.error('Error creating table:', error);
res.status(500).send('Error creating table.');
} finally {
client.release();
}
};



// Verificar si una tabla existe
export const checkTableExists = async (req, res) => {
const { tableName } = req.params;
const client = await pool.connect();
try {
if (!tableName) {
return res.status(400).send('Table name is required.');
}

const checkTableQuery = `
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = $1
);
`;
const result = await client.query(checkTableQuery, [tableName]);
if (result.rows[0].exists) {
res.send(`Table ${tableName} exists.`);
} else {
res.send(`Table ${tableName} does not exist.`);
}
} catch (error) {
console.error('Error checking table existence:', error);
res.status(500).send('Error checking table existence.');
} finally {
client.release();
}
};

// Obtener todos los nombres de las tablas con sus columnas y llaves primarias
export const getAllTables = async (req, res) => {
const client = await pool.connect();
try {
const getTablesQuery = `
SELECT
c.table_name,
c.column_name,
c.data_type,
c.is_nullable,
tc.constraint_type
FROM
information_schema.columns c
LEFT JOIN information_schema.key_column_usage kcu
ON c.table_name = kcu.table_name
AND c.column_name = kcu.column_name
LEFT JOIN information_schema.table_constraints tc
ON kcu.constraint_name = tc.constraint_name
AND tc.constraint_type = 'PRIMARY KEY'
WHERE
c.table_schema = 'public'
ORDER BY
c.table_name, c.ordinal_position;
`;
const result = await client.query(getTablesQuery);
const tables = {};

result.rows.forEach(row => {
if (!tables[row.table_name]) {
tables[row.table_name] = { columns: [] };
}
tables[row.table_name].columns.push({
column_name: row.column_name,
data_type: row.data_type,
is_nullable: row.is_nullable,
is_primary_key: row.constraint_type === 'PRIMARY KEY'
});
});

res.json(tables);
} catch (error) {
console.error('Error fetching table names and columns:', error);
res.status(500).send('Error fetching table names and columns.');
} finally {
client.release();
}
};
// Eliminar una tabla
export const dropTable = async (req, res) => {
const { tableName } = req.params;
const client = await pool.connect();
try {
if (!tableName) {
return res.status(400).send('Table name is required.');
}

const dropTableQuery = `DROP TABLE IF EXISTS ${tableName};`;
await client.query(dropTableQuery);
res.send(`Table ${tableName} has been dropped if it existed.`);
} catch (error) {
console.error('Error dropping table:', error);
res.status(500).send('Error dropping table.');
} finally {
client.release();
}
};

// Actualizar una tabla (agregar/eliminar columnas)
export const updateTable = async (req, res) => {
const { tableName } = req.params;
const { addColumns, dropColumns } = req.body;
const client = await pool.connect();
try {
if (!tableName) {
return res.status(400).send('Table name is required.');
}

let alterTableQuery = `ALTER TABLE ${tableName}`;

if (addColumns && addColumns.length > 0) {
const addColumnsDef = addColumns.map(col => `ADD COLUMN ${col.name} ${col.type}`).join(', ');
alterTableQuery += ` ${addColumnsDef}`;
}

if (dropColumns && dropColumns.length > 0) {
if (addColumns && addColumns.length > 0) {
alterTableQuery += ',';
}
const dropColumnsDef = dropColumns.map(col => `DROP COLUMN ${col}`).join(', ');
alterTableQuery += ` ${dropColumnsDef}`;
}

alterTableQuery += ';';

await client.query(alterTableQuery);
res.send(`Table ${tableName} has been updated.`);
} catch (error) {
console.error('Error updating table:', error);
res.status(500).send('Error updating table.');
} finally {
client.release();
}
};

import escapeHtml from 'escape-html';
// Obtener todas las tablas y sus columnas
export const getTablesAndColumns = async (req, res) => {
const client = await pool.connect();
Expand All @@ -187,7 +11,7 @@ export const getTablesAndColumns = async (req, res) => {
ORDER BY table_name;
`;
const tablesResult = await client.query(tablesQuery);
const tables = tablesResult.rows.map(row => row.table_name);
const tables = tablesResult.rows.map(row => escapeHtml(row.table_name));

const tablesAndColumns = {};

Expand All @@ -198,7 +22,7 @@ export const getTablesAndColumns = async (req, res) => {
WHERE table_name = $1;
`;
const columnsResult = await client.query(columnsQuery, [table]);
tablesAndColumns[table] = columnsResult.rows.map(row => row.column_name);
tablesAndColumns[table] = columnsResult.rows.map(row => escapeHtml(row.column_name));
}

res.json(tablesAndColumns);
Expand All @@ -208,4 +32,4 @@ export const getTablesAndColumns = async (req, res) => {
} finally {
client.release();
}
};
};
Loading

0 comments on commit f96ca80

Please sign in to comment.