deckhearth/pages/api/cards/[id]/ownership.js
Randall Stillwell f408e151c8 🔒 CRITICAL SECURITY FIX: Implement Proper User Data Isolation
🚨 Fixed Major Data Leakage Issues:
- Replaced hardcoded user_id = 1 with proper JWT authentication
- Fixed collections API to filter by authenticated user
- Fixed card ownership to use user_cards table (not global cards table)
- Fixed decks API to return only user-owned decks
- Fixed card collections/decks APIs to respect user permissions
- Fixed favorites API to use user_favorites table

🛡️ Authentication & Authorization:
- All endpoints now require valid JWT tokens
- Proper user isolation across all data operations
- Collection permissions properly enforced
- User-specific data queries implemented

🔧 Database Schema Fixes:
- Card ownership now uses user_cards table
- Favorites use user_favorites table
- Decks filtered by user_id
- Collections respect ownership and permissions

⚠️ Development Note:
- Added warning for fallback authentication in dev mode
- Should be removed in production deployment

 Data Privacy Secured:
- Users can only see their own collections, decks, and owned cards
- Public collections visible to all (as intended)
- Shared collections respect permission levels
- No cross-user data leakage
2025-07-26 00:29:51 -05:00

70 lines
No EOL
1.8 KiB
JavaScript

import { sql } from '@vercel/postgres';
import { getUserFromRequest } from '../../../../lib/permission-middleware';
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
const { id } = req.query;
const { quantity } = req.body;
try {
// Get authenticated user
const user = await getUserFromRequest(req);
if (!user) {
return res.status(401).json({ error: 'Authentication required' });
}
// Check if card exists
const cardCheck = await sql`
SELECT id, name FROM cards WHERE id = ${id}
`;
if (cardCheck.rows.length === 0) {
return res.status(404).json({ error: 'Card not found' });
}
const card = cardCheck.rows[0];
if (quantity > 0) {
// Insert or update user's card ownership
const result = await sql`
INSERT INTO user_cards (user_id, card_id, quantity)
VALUES (${user.userId}, ${id}, ${quantity})
ON CONFLICT (user_id, card_id)
DO UPDATE SET
quantity = ${quantity},
updated_at = CURRENT_TIMESTAMP
RETURNING *
`;
res.status(200).json({
success: true,
card: {
id: card.id,
name: card.name,
quantity: result.rows[0].quantity
}
});
} else {
// Remove card from user's collection if quantity is 0
await sql`
DELETE FROM user_cards
WHERE user_id = ${user.userId} AND card_id = ${id}
`;
res.status(200).json({
success: true,
card: {
id: card.id,
name: card.name,
quantity: 0
}
});
}
} catch (error) {
console.error('Error updating ownership:', error);
res.status(500).json({ error: 'Failed to update ownership' });
}
}