🔒 Implement 'All My Cards' System Collection

 New Feature - Automatic System Collection:
- Every user gets an undeletable 'All My Cards' collection on registration
- Contains all cards marked as owned by the user
- Cannot be deleted, renamed, or made public
- Special 🔒 System indicator in the UI

🗃️ Database Changes:
- Added is_system_collection column to collections table
- Migration script created 'All My Cards' for all existing users (5 users)
- Automatic creation in registration API for new users

🛡️ API Protections:
- DELETE: System collections cannot be deleted
- PUT: System collections cannot be renamed or made public
- Added isSystemCollection field to API responses

🎨 Frontend Updates:
- System collections show 🔒 System badge
- Edit/Delete buttons hidden for system collections
- Special visual indicator for protected collections

🎯 Implementation Details:
- Unique slug generation (all-my-cards, all-my-cards-2, etc.)
- Proper permissions setup for each collection
- Error handling for edge cases
- Non-blocking registration if collection creation fails

Ready for users to have their automatic 'All My Cards' collection! 🚀
This commit is contained in:
Randall Stillwell 2025-07-27 15:17:51 -05:00
parent 5573ebb8d2
commit 603bf5bc89
4 changed files with 227 additions and 39 deletions

View file

@ -1,6 +1,7 @@
import bcrypt from 'bcryptjs'; import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import { sql } from '@vercel/postgres'; import { sql } from '@vercel/postgres';
import { generateUniqueSlug } from '../../../lib/slug-utils.js';
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production'; const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production';
@ -52,6 +53,56 @@ export default async function handler(req, res) {
const user = result.rows[0]; const user = result.rows[0];
// Create the automatic "All My Cards" collection for the new user
try {
// Get existing slugs to ensure uniqueness
const existingSlugsData = await sql`SELECT slug FROM collections WHERE slug IS NOT NULL`;
const existingSlugs = (existingSlugsData.rows || []).map(row => row.slug);
// Generate unique slug for "All My Cards"
const uniqueSlug = await generateUniqueSlug("All My Cards", existingSlugs);
// Create the special collection
const collectionResult = await sql`
INSERT INTO collections (
name,
description,
tcg,
is_public,
user_id,
slug,
is_system_collection,
created_at,
updated_at
)
VALUES (
'All My Cards',
'Automatically contains all cards you mark as owned. This collection cannot be deleted or made public.',
'All',
false,
${user.id},
${uniqueSlug},
true,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
)
RETURNING id
`;
const collection = collectionResult.rows[0];
// Create owner permission for the collection
await sql`
INSERT INTO collection_permissions (collection_id, user_id, role, status, created_at)
VALUES (${collection.id}, ${user.id}, 'owner', 'active', CURRENT_TIMESTAMP)
`;
console.log(`✅ Created "All My Cards" collection for user ${user.email} (ID: ${collection.id})`);
} catch (collectionError) {
console.error('Error creating "All My Cards" collection:', collectionError);
// Don't fail the registration if collection creation fails
}
// Generate JWT token // Generate JWT token
const token = jwt.sign( const token = jwt.sign(
{ userId: user.id, email: user.email, role: user.role }, { userId: user.id, email: user.email, role: user.role },

View file

@ -59,7 +59,6 @@ export default async function handler(req, res) {
GROUP BY c.id, u.email, cp.role GROUP BY c.id, u.email, cp.role
`; `;
} else { } else {
// Numeric ID lookup
const numericId = parseInt(identifier); const numericId = parseInt(identifier);
collectionQuery = sql` collectionQuery = sql`
SELECT DISTINCT SELECT DISTINCT
@ -88,13 +87,13 @@ export default async function handler(req, res) {
`; `;
} }
const result = await collectionQuery; const collectionResult = await collectionQuery;
if (result.rows.length === 0) { if (collectionResult.rows.length === 0) {
return res.status(404).json({ error: 'Collection not found or access denied' }); return res.status(404).json({ error: 'Collection not found or access denied' });
} }
const collection = result.rows[0]; const collection = collectionResult.rows[0];
if (req.method === 'GET') { if (req.method === 'GET') {
const formattedCollection = { const formattedCollection = {
@ -108,6 +107,7 @@ export default async function handler(req, res) {
lastViewed: collection.updated_at, lastViewed: collection.updated_at,
createdAt: collection.created_at, createdAt: collection.created_at,
isPublic: collection.is_public || false, isPublic: collection.is_public || false,
isSystemCollection: collection.is_system_collection || false,
image: collection.image, image: collection.image,
tags: collection.tags ? collection.tags.split(',') : [], tags: collection.tags ? collection.tags.split(',') : [],
creator: collection.creator_email, creator: collection.creator_email,
@ -124,6 +124,16 @@ export default async function handler(req, res) {
const { name, description, isPublic, image, tags } = req.body; const { name, description, isPublic, image, tags } = req.body;
// Prevent system collections from being made public
if (collection.is_system_collection && isPublic === true) {
return res.status(403).json({ error: 'System collections cannot be made public' });
}
// Prevent renaming system collections
if (collection.is_system_collection && name !== undefined && name !== collection.name) {
return res.status(403).json({ error: 'System collections cannot be renamed' });
}
// If name is being changed, generate new slug // If name is being changed, generate new slug
let updateFields = []; let updateFields = [];
let updateValues = []; let updateValues = [];
@ -187,6 +197,7 @@ export default async function handler(req, res) {
name: updateResult.rows[0].name, name: updateResult.rows[0].name,
description: updateResult.rows[0].description, description: updateResult.rows[0].description,
isPublic: updateResult.rows[0].is_public, isPublic: updateResult.rows[0].is_public,
isSystemCollection: updateResult.rows[0].is_system_collection,
image: updateResult.rows[0].image, image: updateResult.rows[0].image,
tags: updateResult.rows[0].tags ? updateResult.rows[0].tags.split(',') : [] tags: updateResult.rows[0].tags ? updateResult.rows[0].tags.split(',') : []
}; };
@ -199,6 +210,11 @@ export default async function handler(req, res) {
return res.status(403).json({ error: 'Only collection owners can delete collections' }); return res.status(403).json({ error: 'Only collection owners can delete collections' });
} }
// Prevent deletion of system collections
if (collection.is_system_collection) {
return res.status(403).json({ error: 'System collections cannot be deleted' });
}
// Delete collection and all related data // Delete collection and all related data
await sql`DELETE FROM collection_cards WHERE collection_id = ${collection.id}`; await sql`DELETE FROM collection_cards WHERE collection_id = ${collection.id}`;
await sql`DELETE FROM collection_permissions WHERE collection_id = ${collection.id}`; await sql`DELETE FROM collection_permissions WHERE collection_id = ${collection.id}`;

View file

@ -491,42 +491,52 @@ export default function Collections() {
{/* Header with name and description - more space */} {/* Header with name and description - more space */}
<div className="space-y-2"> <div className="space-y-2">
<div className="flex items-start justify-between"> <div className="flex items-start justify-between">
<h3 className="text-lg font-semibold leading-tight" style={{ color: 'var(--text-primary)' }}> <div className="flex items-center space-x-2">
{collection.name} <h3 className="text-lg font-semibold leading-tight" style={{ color: 'var(--text-primary)' }}>
</h3> {collection.name}
{/* Edit/Delete buttons moved to hover only */} </h3>
<div className="opacity-0 group-hover:opacity-100 transition-opacity flex space-x-1 ml-2 flex-shrink-0"> {/* System collection indicator */}
<button {collection.isSystemCollection && (
onClick={(e) => { <span className="px-2 py-0.5 text-xs font-medium rounded-full bg-blue-50 text-blue-700 border border-blue-200">
e.stopPropagation(); 🔒 System
setEditingCollection(collection); </span>
}} )}
className="p-1.5 rounded-lg transition-colors hover:scale-105"
style={{
backgroundColor: 'var(--bg-tertiary)',
color: 'var(--text-secondary)'
}}
>
<svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</button>
<button
onClick={(e) => {
e.stopPropagation();
handleDeleteCollection(collection.id);
}}
className="p-1.5 rounded-lg transition-colors hover:scale-105"
style={{
backgroundColor: 'var(--bg-tertiary)',
color: '#ef4444'
}}
>
<svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div> </div>
{/* Edit/Delete buttons - hidden for system collections */}
{!collection.isSystemCollection && (
<div className="opacity-0 group-hover:opacity-100 transition-opacity flex space-x-1 ml-2 flex-shrink-0">
<button
onClick={(e) => {
e.stopPropagation();
setEditingCollection(collection);
}}
className="p-1.5 rounded-lg transition-colors hover:scale-105"
style={{
backgroundColor: 'var(--bg-tertiary)',
color: 'var(--text-secondary)'
}}
>
<svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</button>
<button
onClick={(e) => {
e.stopPropagation();
handleDeleteCollection(collection.id);
}}
className="p-1.5 rounded-lg transition-colors hover:scale-105"
style={{
backgroundColor: 'var(--bg-tertiary)',
color: '#ef4444'
}}
>
<svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
)}
</div> </div>
{collection.description && ( {collection.description && (
<p className="text-sm leading-relaxed" style={{ color: 'var(--text-secondary)' }}> <p className="text-sm leading-relaxed" style={{ color: 'var(--text-secondary)' }}>

View file

@ -0,0 +1,111 @@
#!/usr/bin/env node
import dotenv from 'dotenv';
import { neon } from '@neondatabase/serverless';
import { generateUniqueSlug } from '../lib/slug-utils.js';
dotenv.config({ path: '.env.local' });
async function addSystemCollectionColumn() {
const sql = neon(process.env.POSTGRES_URL);
try {
console.log('🔧 Adding is_system_collection column to collections table...');
// Add the is_system_collection column
await sql`
ALTER TABLE collections
ADD COLUMN IF NOT EXISTS is_system_collection BOOLEAN DEFAULT false
`;
console.log('✅ Added is_system_collection column');
// Get all existing users who don't have an "All My Cards" collection
console.log('👥 Finding users without "All My Cards" collection...');
const usersWithoutAllMyCards = await sql`
SELECT u.id, u.email
FROM users u
WHERE NOT EXISTS (
SELECT 1 FROM collections c
WHERE c.user_id = u.id
AND c.name = 'All My Cards'
AND c.is_system_collection = true
)
`;
console.log(`Found ${usersWithoutAllMyCards.length} users without "All My Cards" collection`);
// Get existing slugs for uniqueness
const existingSlugsData = await sql`SELECT slug FROM collections WHERE slug IS NOT NULL`;
const existingSlugs = (existingSlugsData || []).map(row => row.slug);
// Create "All My Cards" collection for each user
for (const user of usersWithoutAllMyCards) {
try {
console.log(`Creating "All My Cards" for ${user.email}...`);
// Generate unique slug
const uniqueSlug = await generateUniqueSlug("All My Cards", existingSlugs);
existingSlugs.push(uniqueSlug);
// Create the collection
const collectionResult = await sql`
INSERT INTO collections (
name,
description,
tcg,
is_public,
user_id,
slug,
is_system_collection,
created_at,
updated_at
)
VALUES (
'All My Cards',
'Automatically contains all cards you mark as owned. This collection cannot be deleted or made public.',
'All',
false,
${user.id},
${uniqueSlug},
true,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
)
RETURNING id
`;
const collection = collectionResult[0];
// Create owner permission
await sql`
INSERT INTO collection_permissions (collection_id, user_id, role, status, created_at)
VALUES (${collection.id}, ${user.id}, 'owner', 'active', CURRENT_TIMESTAMP)
`;
console.log(` ✅ Created collection ID ${collection.id} with slug "${uniqueSlug}"`);
} catch (error) {
console.error(` ❌ Failed to create collection for ${user.email}:`, error.message);
}
}
console.log('\n🎉 Migration completed successfully!');
console.log('\n📋 Summary:');
console.log(` • Added is_system_collection column to collections table`);
console.log(` • Created "All My Cards" collections for ${usersWithoutAllMyCards.length} existing users`);
console.log(` • New users will automatically get this collection on registration`);
} catch (error) {
console.error('❌ Migration failed:', error.message);
console.error('Full error:', error);
process.exit(1);
}
}
if (import.meta.url === `file://${process.argv[1]}`) {
addSystemCollectionColumn();
}
export { addSystemCollectionColumn };