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
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
-- CreateIndex
CREATE INDEX "notifications_user_id_idx" ON "notifications"("user_id");

-- CreateIndex
CREATE INDEX "order_items_order_id_idx" ON "order_items"("order_id");

-- CreateIndex
CREATE INDEX "order_items_product_id_idx" ON "order_items"("product_id");

-- CreateIndex
CREATE INDEX "orders_buyer_id_idx" ON "orders"("buyer_id");

-- CreateIndex
CREATE INDEX "products_seller_id_idx" ON "products"("seller_id");

-- CreateIndex
CREATE INDEX "transactions_wallet_id_idx" ON "transactions"("wallet_id");

-- Wallet CHECK Constraints
ALTER TABLE "wallets" ADD CONSTRAINT "real_balance_non_negative" CHECK ("real_balance" >= 0);
ALTER TABLE "wallets" ADD CONSTRAINT "promo_balance_non_negative" CHECK ("promo_balance" >= 0);
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
Warnings:

- A unique constraint covering the columns `[idempotencyKey,category]` on the table `transactions` will be added. If there are existing duplicate values, this will fail.

*/
-- DropIndex
DROP INDEX "transactions_idempotencyKey_key";

-- CreateIndex
CREATE UNIQUE INDEX "transactions_idempotencyKey_category_key" ON "transactions"("idempotencyKey", "category");
9 changes: 8 additions & 1 deletion Backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ model Product {
details ProductDetails?
orderItems OrderItem[]

@@index([sellerId])
@@map("products")
}

Expand All @@ -190,6 +191,7 @@ model Order {
items OrderItem[]
transactions Transaction[]

@@index([buyerId])
@@map("orders")
}

Expand All @@ -203,12 +205,14 @@ model OrderItem {
priceAtPurchase Decimal @db.Decimal(10, 2) @map("price_at_purchase")
createdAt DateTime @default(now()) @map("created_at")

@@index([orderId])
@@index([productId])
@@map("order_items")
}

model Transaction {
id Int @id @default(autoincrement())
idempotencyKey String? @unique
idempotencyKey String?
walletId Int @map("wallet_id")
wallet Wallet @relation(fields: [walletId], references: [userId], onDelete: Cascade)
orderId Int? @map("order_id")
Expand All @@ -220,7 +224,9 @@ model Transaction {
description String? @db.Text
createdAt DateTime @default(now()) @map("created_at")

@@index([walletId])
@@map("transactions")
@@unique([idempotencyKey, category])
}

model Notification {
Expand All @@ -231,6 +237,7 @@ model Notification {
isRead Boolean @default(false) @map("is_read")
createdAt DateTime @default(now()) @map("created_at")

@@index([userId])
@@map("notifications")
}

Expand Down
File renamed without changes.
22 changes: 11 additions & 11 deletions Backend/src/controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ export const register = async (req, res) => {
try {
// 1. Extract exactly what we expect from the body
const { email, password, role } = req.body;

// 2. Input validation
if (!email || !password) {
return res.status(400).json({ success: false, error: "Email and password are required" });
}

// 3. SECURITY PATCH: Privilege Escalation Prevention
// Only allow 'Seller' or 'Buyer'. If they try to pass 'Admin', default them to 'Buyer'.

// SECURITY: Force role to 'Buyer' on public registration (prevent privilege escalation)
const safeRole = role === 'Seller' ? 'Seller' : 'Buyer';

const safeUserData = {
Expand All @@ -31,16 +31,16 @@ export const register = async (req, res) => {
console.error("Registration Error:", error);

if (error.message === 'WEAK_PASSWORD') {
return res.status(400).json({
success: false,
error: "Password must be at least 8 characters long and include an uppercase letter, a lowercase letter, and a number."
return res.status(400).json({
success: false,
error: "Password must be at least 8 characters long and include an uppercase letter, a lowercase letter, and a number."
});
}

if (error.code === 'P2002') {
return res.status(400).json({ success: false, error: "Email already exists" });
}

res.status(500).json({ success: false, error: "Internal Server Error" });
}
};
Expand All @@ -58,14 +58,14 @@ export const fetchUsers = async (req, res) => {
export const login = async (req, res) => {
try {
const { email, password } = req.body;

// Basic validation
if (!email || !password) {
return res.status(400).json({ success: false, error: "Email and password are required" });
}

const authData = await loginUser(email, password);

res.status(200).json({
success: true,
message: "Login successful!",
Expand All @@ -89,7 +89,7 @@ export const getProfile = async (req, res) => {
return res.status(401).json({ success: false, error: "Unauthorized" });
}

const { userId } = req.user;
const { userId } = req.user;

const user = await getUserProfile(userId);

Expand Down
37 changes: 25 additions & 12 deletions Backend/src/controllers/orderController.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,33 @@ export const createOrder = async (req, res) => {
}

const order = await orderService.processOrder(userId, items, idempotencyKey);

res.status(201).json({ success: true, message: "Order placed successfully!", data: order });
const orderData = order.order || order.transaction?.order || order;
const statusCode = order.alreadyProcessed ? 200 : 201;
res.status(statusCode).json({
success: true,
message: order.alreadyProcessed ? "Duplicate request ignored" : "Order placed successfully!",
data: order.alreadyProcessed ? orderData : order,
alreadyProcessed: order.alreadyProcessed || false
});
} catch (error) {
// Catch PostgreSQL CHECK constraint violation
// if (error.message.includes('stock_non_negative') || error.code === 'P2004' || error.code === 'P2010') {
if (error.code === 'P2002') {
return res.status(409).json({
success: false,
error: "Duplicate request: You have already placed this order. Please refresh the page."
});
}

if (error.code === 'P2002' || error.code === 'P2004' ||
error.code === 'P2010' || error.message.includes('stock')) {
if (error.code === 'P2004' || error.code === 'P2010' || error.message?.includes('stock_non_negative') ||
error.message?.includes('Insufficient wallet balance') || error.message?.includes('unavailable') ||
error.message?.includes('Invalid input')) {
return res.status(400).json({
success: false,
error: "Checkout failed: One or more items in your cart do not have enough stock available."
error: "Checkout failed. An item may be out of stock, or your balance may be insufficient."
});
}

// Catch Wallet & Validation errors
const statusCode = error.message.includes("Insufficient") || error.message.includes("unavailable") ? 400 : 500;
res.status(statusCode).json({ success: false, error: error.message });
console.error('Unhandled order error:', error);
return res.status(500).json({ success: false, error: "Internal server error" });
}
};

Expand All @@ -59,8 +69,11 @@ export const cancelOrder = async (req, res) => {

res.status(200).json({
success: true,
message: "Order cancelled successfully. Funds have been refunded to your wallet.",
data: order
message: order.alreadyProcessed
? "Duplicate request ignored"
: "Order cancelled successfully. Funds have been refunded to your wallet.",
data: order,
alreadyProcessed: order.alreadyProcessed || false
});
} catch (error) {
const statusCode = error.statusCode || 500;
Expand Down
8 changes: 6 additions & 2 deletions Backend/src/controllers/productController.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,18 @@ export const createProduct = async (req, res) => {

const sellerId = req.user.userId;

if (!name || !price || !stock) {
if (
!name ||
price === undefined || price === null || price === '' || isNaN(Number(price)) || Number(price) < 0 ||
stock === undefined || stock === null || stock === '' || isNaN(Number(stock)) || Number(stock) < 0
) {
return res.status(400).json({ success: false, message: "Missing required fields: name, price, and stock are required." });
}

const newProduct = await productService.createProduct({
name,
price: parseFloat(price),
stock: parseInt(stock || 0),
stock: parseInt(stock, 10),
category: category || "General",
sellerId: sellerId
});
Expand Down
5 changes: 1 addition & 4 deletions Backend/src/controllers/walletController.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,16 +212,13 @@ export const getAllWalletsForAdmin = async (req, res) => {

const wallets = await getAllWallets(skip, take, filters);

if (!wallets || wallets.length === 0) {
return res.status(404).json({ success: false, error: "No Wallets found" });
}

res.status(200).json({
success: true,
count: wallets.length,
data: wallets
});
} catch (error) {
console.error('getAllWalletsForAdmin error:', error);
return res.status(error.statusCode || 500).json({
success: false,
error: error.message
Expand Down
3 changes: 2 additions & 1 deletion Backend/src/services/authService.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ export const loginUser = async (email, password) => {
where: { email }
});

if (!user) {
// Reject if user does not exist or has been deactivated/soft-deleted
if (!user || user.isActive === false) {
throw new Error('INVALID_CREDENTIALS');
}

Expand Down
50 changes: 15 additions & 35 deletions Backend/src/services/orderService.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import prisma from '../config/prisma.js';
import crypto from 'crypto';
import { TransactionType, TransactionCategory, OrderStatus } from '../data/constants.js';
import { withIdempotency } from '../utils/idempotency.js';

export const processOrder = async (buyerId, rawItems,idempotencyKey) => {
export const processOrder = async (buyerId, rawItems, idempotencyKey) => {
const bId = parseInt(buyerId);

if (!bId) throw new Error("Invalid input: buyer id is required.");
if (!idempotencyKey) throw new Error("Invalid input: idempotency key is required.");

const consolidatedItems = {};
for (const item of rawItems) {
if (consolidatedItems[item.productId]) {
Expand Down Expand Up @@ -49,27 +50,8 @@ export const processOrder = async (buyerId, rawItems,idempotencyKey) => {
};
});

// 2. Execute the Composite Transaction
return await prisma.$transaction(async (tx) => {
if (idempotencyKey) {
const existing = await tx.transaction.findUnique({
where: { idempotencyKey },
include: { order: { include: { items: true } } }
});

if (existing) {
if (existing.order) {
return existing.order; // Return the successfully processed order
} else {
// Prevent the 500 crash by stopping execution if the key belongs to a Wallet op
const error = new Error("Invalid Idempotency Key: This key has already been used for a different transaction type.");
error.statusCode = 400;
throw error;
}
}
}


// 2. Execute the Composite Transaction with Idempotency
return await withIdempotency(prisma, idempotencyKey, TransactionCategory.PURCHASE, async (tx) => {
// A. Verify Wallet Balance
const wallet = await tx.wallet.findUnique({ where: { userId: bId } });
if (!wallet || parseFloat(wallet.realBalance) < totalAmount) {
Expand Down Expand Up @@ -104,7 +86,7 @@ export const processOrder = async (buyerId, rawItems,idempotencyKey) => {
amount: totalAmount,
type: TransactionType.DEBIT,
category: TransactionCategory.PURCHASE,
idempotencyKey: idempotencyKey ,
idempotencyKey: idempotencyKey,
description: `Payment for Order #${order.id}`,
referenceId: `ORD-PAY-${Date.now()}-${crypto.randomBytes(3).toString('hex').toUpperCase()}`
}
Expand All @@ -119,8 +101,9 @@ export const processOrder = async (buyerId, rawItems,idempotencyKey) => {
});
}

return order;
return { ...order, alreadyProcessed: false };
});

};

export const getOrdersByUserId = async (buyerId) => {
Expand Down Expand Up @@ -170,14 +153,11 @@ export const cancelOrder = async (orderId, userId, role, idempotencyKey) => {
throw err;
}

// 4. The Reverse Composite Transaction
return await prisma.$transaction(async (tx) => {
if (idempotencyKey) {
const existing = await tx.transaction.findUnique({
where: { idempotencyKey: `${idempotencyKey}-REF` }
});
if (existing) return await tx.order.findUnique({ where: { id: oId } });
}
const refundKey = idempotencyKey ? `${idempotencyKey}-REF-${oId}` : `REF-${oId}`;

// 4. The Reverse Composite Transaction with Idempotency

return await withIdempotency(prisma, refundKey, TransactionCategory.REFUND, async (tx) => {
// A. Update Order Status
const updatedOrder = await tx.order.update({
where: { id: oId },
Expand All @@ -198,7 +178,7 @@ export const cancelOrder = async (orderId, userId, role, idempotencyKey) => {
amount: order.totalAmount, // Stored as absolute positive value!
type: TransactionType.CREDIT,
category: TransactionCategory.REFUND,
idempotencyKey: idempotencyKey ? `${idempotencyKey}-REF` : null,
idempotencyKey: refundKey,
description: `Refund for Cancelled Order #${oId}`,
referenceId: `ORD-REF-${Date.now()}-${crypto.randomBytes(3).toString('hex').toUpperCase()}`
}
Expand All @@ -212,6 +192,6 @@ export const cancelOrder = async (orderId, userId, role, idempotencyKey) => {
});
}

return updatedOrder;
return { ...updatedOrder, alreadyProcessed: false };
});
};
Loading
Loading