T.ME/BIBIL_0DAY
CasperSecurity


Server : Apache/2
System : Linux server-15-235-50-60 5.15.0-164-generic #174-Ubuntu SMP Fri Nov 14 20:25:16 UTC 2025 x86_64
User : gositeme ( 1004)
PHP Version : 8.2.29
Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname
Directory :  /home/gositeme/domains/lavocat.quebec/public_html/scripts/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/gositeme/domains/lavocat.quebec/public_html/scripts/fix-impersonation-sessions.js
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function fixImpersonationSessions() {
  console.log('🔧 Starting fix of impersonation sessions...');
  
  try {
    // Find all active sessions
    const activeSessions = await prisma.impersonationSession.findMany({
      where: {
        isActive: true
      },
      select: {
        id: true,
        originalUserId: true,
        impersonatedUserId: true,
        createdAt: true,
        expiresAt: true
      },
      orderBy: {
        createdAt: 'asc'
      }
    });

    console.log(`📊 Found ${activeSessions.length} active sessions`);

    if (activeSessions.length === 0) {
      console.log('✅ No active sessions found. All good!');
      return;
    }

    // Group sessions by originalUserId to find duplicates
    const sessionsByUser = {};
    activeSessions.forEach(session => {
      if (!sessionsByUser[session.originalUserId]) {
        sessionsByUser[session.originalUserId] = [];
      }
      sessionsByUser[session.originalUserId].push(session);
    });

    let fixedCount = 0;

    // Process each user's sessions
    for (const [userId, sessions] of Object.entries(sessionsByUser)) {
      if (sessions.length > 1) {
        console.log(`⚠️ User ${userId} has ${sessions.length} active sessions. Keeping the most recent one.`);
        
        // Sort by creation date, keep the most recent one
        const sortedSessions = sessions.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
        const sessionsToDeactivate = sortedSessions.slice(1); // All except the first (most recent)
        
        // Deactivate older sessions one by one to avoid unique constraint issues
        for (const session of sessionsToDeactivate) {
          try {
            await prisma.impersonationSession.update({
              where: { id: session.id },
              data: {
                isActive: false,
                endedAt: new Date()
              }
            });
            console.log(`  - Deactivated session ${session.id} (created: ${session.createdAt})`);
            fixedCount++;
          } catch (error) {
            console.log(`  - Failed to deactivate session ${session.id}: ${error.message}`);
          }
        }
      }
    }

    // Also clean up expired sessions one by one
    const expiredSessions = await prisma.impersonationSession.findMany({
      where: {
        isActive: true,
        expiresAt: { lt: new Date() }
      },
      select: {
        id: true,
        originalUserId: true,
        impersonatedUserId: true,
        expiresAt: true
      }
    });

    if (expiredSessions.length > 0) {
      console.log(`📅 Found ${expiredSessions.length} expired sessions to clean up`);
      
      // Update expired sessions one by one to avoid unique constraint issues
      for (const session of expiredSessions) {
        try {
          await prisma.impersonationSession.update({
            where: { id: session.id },
            data: {
              isActive: false,
              endedAt: new Date()
            }
          });
          console.log(`  - Deactivated expired session ${session.id} (expired: ${session.expiresAt})`);
          fixedCount++;
        } catch (error) {
          console.log(`  - Failed to deactivate expired session ${session.id}: ${error.message}`);
        }
      }
    }

    console.log(`✅ Successfully fixed ${fixedCount} sessions`);

    // Verify the fix
    const remainingActiveSessions = await prisma.impersonationSession.findMany({
      where: {
        isActive: true
      },
      select: {
        id: true,
        originalUserId: true,
        impersonatedUserId: true,
        createdAt: true
      }
    });

    console.log(`📊 Remaining active sessions: ${remainingActiveSessions.length}`);
    
    // Check for any remaining duplicates
    const remainingByUser = {};
    remainingActiveSessions.forEach(session => {
      if (!remainingByUser[session.originalUserId]) {
        remainingByUser[session.originalUserId] = [];
      }
      remainingByUser[session.originalUserId].push(session);
    });

    const duplicates = Object.entries(remainingByUser).filter(([userId, sessions]) => sessions.length > 1);
    
    if (duplicates.length > 0) {
      console.log('❌ Still found duplicate active sessions:');
      duplicates.forEach(([userId, sessions]) => {
        console.log(`  - User ${userId}: ${sessions.length} sessions`);
      });
    } else {
      console.log('✅ No duplicate active sessions found. Fix successful!');
    }

  } catch (error) {
    console.error('❌ Error during fix:', error);
    throw error;
  }
}

async function main() {
  try {
    await fixImpersonationSessions();
    console.log('🎉 Impersonation sessions fix completed successfully');
  } catch (error) {
    console.error('💥 Fix failed:', error);
    process.exit(1);
  } finally {
    await prisma.$disconnect();
  }
}

// Run if called directly
if (require.main === module) {
  main();
}

module.exports = { fixImpersonationSessions }; 

CasperSecurity Mini