Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
277 changes: 109 additions & 168 deletions package-lock.json

Large diffs are not rendered by default.

27 changes: 18 additions & 9 deletions src/config/jwt.config.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,41 @@
//jwt.config.js
import jwt from 'jsonwebtoken';
import { isBlacklisted } from '../lib/tokenBlacklist.js';

const authenticate = (req, res, next) => {
const userToken = req.cookies.userToken;

const userToken = req.cookies.userToken; //Obtenemos la cookie con el token

if(!userToken) {
if (!userToken) {
return res.status(401).json({
errors: {
auth: {
message: 'No autenticado'
}
}
}); //Enviamos el mensaje de error
});
}

jwt.verify(userToken, process.env.JWT_SECRET, (err, payload) => {
if(err) {
if (err) {
return res.status(401).json({
errors: {
auth: {
message: 'No autenticado'
}
}
});
}

if (isBlacklisted(userToken)) {
return res.status(401).json({
errors: {
auth: {
messsage: 'No autenticado'
message: 'Sesión inválida'
}
}
});
}
//Si el token es valido, continuamos con el proceso
req.user = payload; //Se guarda el payload(id, etc.) en la peticion

req.user = payload;
next();
});
};
Expand Down
10 changes: 10 additions & 0 deletions src/lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export { hashPassword, verifyPassword } from "./utils/password.utils.js";
export { AppError, UnauthorizedError, ValidationError, ForbiddenError, NotFoundError, ConflictError } from "./errors.js";
export { DELIVERY_PHONE_REGEX, DELIVERY_PHONE_MESSAGE, validateDeliveryPhone } from "./phone.js";
export { prisma } from "./prisma.js";
export { getOriginalProductPrice, getOfferProductPrice, getEffectiveProductPrice, getProductPricing } from "./product-pricing.js";
export { WEEKDAY_LABELS, getMondayBasedDayOfWeek, parseTimeToMinutes, formatMinutesToTime, mapBusinessHoursRecord, computeStoreAvailability } from "./store-business-hours.js";
export { default as authenticate } from "../config/jwt.config.js";
export { STORE_TIMEZONE, resolveStoreTimeZone, getStoreLocalWeekdayIndex, getStoreLocalMinutesOfDay } from "./store-timezone.js";
export { addToBlacklist, isBlacklisted, cleanExpiredTokens } from "./tokenBlacklist.js";
export { validateId, parsePositiveInteger } from "./validators.js";
1 change: 0 additions & 1 deletion src/lib/store-timezone.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/** Zona horaria para horarios de comercio (HH:mm ingresados en hora local). */
export const STORE_TIMEZONE =
process.env.STORE_TIMEZONE?.trim() || "America/Asuncion";

Expand Down
31 changes: 31 additions & 0 deletions src/lib/tokenBlacklist.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const blacklist = new Set();
Comment thread
CrisNAC marked this conversation as resolved.
Resolved

/**
* Agrega un token a la blacklist.
* @param {string} token
*/
export const addToBlacklist = (token) => {
blacklist.add(token);
};

/**
* Verifica si un token está en la blacklist.
* @param {string} token
* @returns {boolean}
*/
export const isBlacklisted = (token) => {
return blacklist.has(token);
};

/**
* Limpia tokens expirados de la blacklist para evitar acumulación de memoria.
* Se recomienda llamar periódicamente (ej: cada 30 min).
* @param {Function} isExpired - función que recibe el token y retorna true si expiró
*/
export const cleanExpiredTokens = (isExpired) => {
for (const token of blacklist) {
if (isExpired(token)) {
blacklist.delete(token);
}
}
};
5 changes: 0 additions & 5 deletions src/lib/utils/password.utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ export async function hashPassword(plainPassword) {
try {
return await bcrypt.hash(plainPassword, BCRYPT_ROUNDS)
} catch (error) {
console.error('[PASSWORD_HASH_ERROR]', error.message)
throw new Error('Error al procesar la contraseña')
}
}
Expand Down Expand Up @@ -58,10 +57,6 @@ export async function verifyPassword(plainPassword, hashedPassword) {
try {
return await bcrypt.compare(plainPassword, hashedPassword)
} catch (error) {
// Error técnico de bcrypt (hash corrupto, encoding inválido, etc)
// Loguear para debugging pero retornar false (no lanzar excepción)
// Esto evita que el cliente vea un error 500 por un hash corrupto
console.error('[PASSWORD_VERIFY_ERROR]', error.message)
return false
}
}
4 changes: 0 additions & 4 deletions src/middlewares/errorHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,6 @@ export const errorHandler = (err, req, res, next) => {
});
}

// Error inesperado: loguear internamente pero NUNCA exponer detalles en respuesta
console.error(`[ERROR INESPERADO] ${req.method} ${req.path}`, err);

// Respuesta: SIEMPRE genérica, sin stack trace ni detalles internos
return res.status(500).json({
error: {
code: 500,
Expand Down
7 changes: 0 additions & 7 deletions src/modules/commerce/commerces/store.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@ export const createStore = async (req, res) => {

return res.status(201).json(store);
} catch (error) {
console.error("Error creando comercio:", error);

if (error.status) {
return res.status(error.status).json({ message: error.message });
}
Expand Down Expand Up @@ -185,7 +183,6 @@ export const deleteStore = async (req, res) => {
//primeramente se hace la comprobacion de que el usuario este autenticado
const token = req.cookies.userToken;
if (!token) {
console.error("Usuario no autenticado.");
return res.status(401).json({ message: "Usuario no autenticado." });
}

Expand All @@ -199,14 +196,10 @@ export const deleteStore = async (req, res) => {

//se ejecuta el servicio delete
await deleteStoreService(id_user, id_store);

//en caso de exito se retorna el emsaje correspondiente
console.info("Se eliminó correctamente el comercio...")
return res.status(204).send();
}
catch (error) {
if (error.status) return res.status(error.status).json({ message: error.message })
console.error("Error al eliminar el comercio: ", error);
return res.status(500).json({ message: "Error interno del servidor." })
}
}
6 changes: 2 additions & 4 deletions src/modules/commerce/commerces/store.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -543,10 +543,8 @@ const deletePreviousStoreLogoFromStorage = async (previousLogo, nextLogo) => {

try {
await fs.unlink(previousLogoPath);
} catch (error) {
if (error.code !== "ENOENT") {
console.warn("No se pudo eliminar el logo anterior:", error.message);
}
} catch {
// silencioso
}
};

Expand Down
2 changes: 0 additions & 2 deletions src/modules/commerce/product-tags/product-tag.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ export const getProductTags = async (req, res) => {

return res.status(200).json(tags);
} catch (error) {
console.error("Error obteniendo tags de productos:", error);

return res.status(error.status || 500).json({
message: error.message || "Error interno del servidor"
});
Expand Down
16 changes: 2 additions & 14 deletions src/modules/commerce/products/product.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ export const createProduct = async (req, res) => {
const product = await createProductService(req.user.id_user, req.body);
return res.status(201).json(product);
} catch (error) {
console.error("Error creando producto:", error);

return res.status(error.status || 500).json({
message: error.message || "Error interno del servidor"
});
Expand All @@ -44,8 +42,6 @@ export const updateProduct = async (req, res) => {

return res.status(200).json(product);
} catch (error) {
console.error("Error actualizando producto:", error);

return res.status(error.status || error.statusCode || 500).json({
message: error.message || "Error interno del servidor"
});
Expand All @@ -61,11 +57,9 @@ export const updateProduct = async (req, res) => {
export const getProductsSearch = async (request, response) => {
try {
const filterProducts = await getProductsSearchService(request.validated ?? request.query);
console.info("Obteniendo productos...")
return response.status(200).json(filterProducts);
}
catch (error) {
console.error("Error al obtener productos:", error);
return response.status(error.status || 500).json({message: error.message || "Error interno del servidor."});
}
};
Expand Down Expand Up @@ -97,11 +91,9 @@ export const getProductById = async (request, response) => {
message:"Producto no encontrado"
});
}
console.info("Obteniendo producto por id...");
return response.status(200).json(product);
}
catch(error){
console.error("Error al obtener producto:", error);
return response.status(error.status || 500).json({
message:error.message || "Error interno del servidor."
});
Expand Down Expand Up @@ -164,7 +156,6 @@ export const compareProducts = async (request, response) => {
pagination: result.pagination
});
} catch (error) {
console.error("Error al comparar productos:", error);
return response
.status(error.status || 500)
.json({ message: error.message || "Error interno del servidor." });
Expand Down Expand Up @@ -197,13 +188,10 @@ export const filterProducts = async (req, res) => {
export const getRelatedProducts = async (request, response) => {
try {
const { id } = request.params;
const { limit } = request.query;

const relatedProducts = await getRelatedProductsService(id, limit);

const { limit } = request.query;
const relatedProducts = await getRelatedProductsService(id, limit);
return response.status(200).json(relatedProducts);
} catch (error) {
console.error("Error al obtener productos relacionados:", error);
return response.status(error.status || 500).json({
message: error.message || "Error interno del servidor"
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,26 +1,5 @@
import { getProductCategoriesService } from "./product-category.service.js";

/**
* ANTES (manejo de error manual en cada controller):
*
* export const getProductCategories = async (req, res) => {
* try {
* const categories = await getProductCategoriesService({ ... });
* return res.status(200).json(categories);
* } catch (error) {
* console.error("Error obteniendo categorias:", error);
* return res.status(error.status || 500).json({
* message: error.message || "Error interno del servidor"
* });
* }
* };
*
* AHORA (el error se delega al middleware global errorHandler via next):
* - El controller solo maneja el caso exitoso
* - next(error) lo captura errorHandler en index.js y responde con formato estandar
* - El service lanza clases de error tipadas (ValidationError, NotFoundError, etc.)
* que errorHandler convierte automaticamente al codigo HTTP correcto
*/
export const getProductCategories = async (req, res, next) => {
try {
const { search, limit } = req.query;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,26 +1,5 @@
import { getStoreCategoriesService } from "./store-category.service.js";

/**
* ANTES (manejo de error manual en cada controller):
*
* export const getStoreCategories = async (req, res) => {
* try {
* const categories = await getStoreCategoriesService();
* return res.status(200).json(categories);
* } catch (error) {
* console.error("Error obteniendo categorias de comercios:", error);
* return res.status(error.status || 500).json({
* message: error.message || "Error interno del servidor"
* });
* }
* };
*
* AHORA (el error se delega al middleware global errorHandler via next):
* - El controller solo maneja el caso exitoso
* - next(error) lo captura errorHandler en index.js y responde con formato estandar
* - El service lanza clases de error tipadas (ValidationError, NotFoundError, etc.)
* que errorHandler convierte automaticamente al codigo HTTP correcto
*/
export const getStoreCategories = async (req, res, next) => {
try {
const categories = await getStoreCategoriesService();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ export const getDistance = async (req, res, next) => {
return res.status(400).json({ error: "Se requieren al menos 2 puntos" });

if (!process.env.ORS_API_KEY) {
console.error("ORS_API_KEY no está configurada");
return res.status(500).json({ error: "Servicio de geolocalización no disponible" });
}

Expand Down
5 changes: 2 additions & 3 deletions src/modules/images/services/product-image.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,8 @@ export async function upsertProductImage(id, file, user) {
if (oldPath && oldPath !== filePath) {
try {
await deleteImage(BUCKET, oldPath)
} catch (cleanupError) {
// El nuevo producto ya está guardado en BD, solo logueamos el fallo de limpieza
console.warn(`[WARN] No se pudo eliminar imagen antigua: ${oldPath}`, cleanupError)
} catch {
// silencioso — la imagen nueva ya está guardada en BD
}
}

Expand Down
9 changes: 3 additions & 6 deletions src/modules/images/services/store-image.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,8 @@ export async function upsertStoreImage(id, file, user) {
if (oldPath && oldPath !== filePath) {
try {
await deleteImage(BUCKET, oldPath)
} catch (cleanupError) {
// El nuevo logo ya está guardado en BD, solo logueamos el fallo de limpieza
console.warn(`[WARN] No se pudo eliminar imagen antigua: ${oldPath}`, cleanupError)
} catch {
// silencioso — el nuevo logo ya está guardado en BD
}
}

Expand All @@ -78,8 +77,6 @@ export async function removeStoreImage(id, user) {
})

if (filePath) {
await deleteImage(BUCKET, filePath).catch((cleanupError) => {
console.warn(`[WARN] No se pudo eliminar logo en storage: ${filePath}`, cleanupError)
})
await deleteImage(BUCKET, filePath).catch(() => {})
}
}
5 changes: 2 additions & 3 deletions src/modules/images/services/user-image.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,8 @@ export async function upsertUserImage(id, file, authUser) {
if (oldPath && oldPath !== filePath) {
try {
await deleteImage(BUCKET, oldPath)
} catch (cleanupError) {
// El nuevo avatar ya está guardado en BD, solo logueamos el fallo de limpieza
console.warn(`[WARN] No se pudo eliminar imagen antigua: ${oldPath}`, cleanupError)
} catch {
// silencioso — el nuevo avatar ya está guardado en BD
}
}

Expand Down
Loading
Loading