diff --git a/apps/backend/server.js b/apps/backend/server.js index a891b19..0426ea6 100644 --- a/apps/backend/server.js +++ b/apps/backend/server.js @@ -1042,6 +1042,23 @@ app.put('/api/consents', async (req, res) => { } }); +// Migrate anonymous (session-based) consents to a user account on login/register +async function migrateSessionConsents(userId, sessionId) { + if (!userId || !sessionId) return; + try { + const sessionConsents = await userDbAll('SELECT category, granted FROM user_consents WHERE session_id = ?', [sessionId]); + for (const consent of sessionConsents) { + await userDbRun( + `INSERT INTO user_consents (user_id, category, granted, updated_at) VALUES (?, ?, ?, CURRENT_TIMESTAMP) ON CONFLICT (user_id, category) DO UPDATE SET granted = ?, updated_at = CURRENT_TIMESTAMP`, + [userId, consent.category, consent.granted, consent.granted] + ); + } + await userDbRun('DELETE FROM user_consents WHERE session_id = ?', [sessionId]); + } catch (error) { + console.error('Error migrating consents:', error); + } +} + // ========== RECENT SEARCHES (database-based) ========== const MAX_RECENT = 5; @@ -1302,6 +1319,9 @@ app.post('/api/auth/login', loginLimiter, async (req, res) => { req.session.username = user.username; req.session.isAdmin = Boolean(user.is_admin); + // Migrate anonymous consents to user account + await migrateSessionConsents(user.id, req.sessionID); + appMetrics.loginSuccessTotal.add(1); res.json({ message: 'Login successful', @@ -1352,6 +1372,9 @@ app.post('/api/auth/register', registerLimiter, async (req, res) => { req.session.username = u; req.session.isAdmin = false; + // Migrate anonymous consents to new user account + await migrateSessionConsents(result.lastID, req.sessionID); + res.status(201).json({ message: 'Registered', user: {