File size: 3,833 Bytes
c904036
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/**
 * Migration Script: Fix User Roles
 * 
 * This script fixes the critical bug where default roles were set as ['student,host']
 * (a single string) instead of ['student'] (an array with one element).
 * 
 * It will:
 * 1. Find all users with the malformed role 'student,host'
 * 2. Replace it with proper ['student'] array
 * 3. Preserve any additional roles (host, verifier, platformAdmin)
 * 4. Report on the changes made
 */

require('dotenv').config();
const mongoose = require('mongoose');
const User = require('../Models/User');

async function fixUserRoles() {
  try {
    console.log('πŸ”§ Starting user roles migration...');
    console.log('Connecting to MongoDB...');
    
    await mongoose.connect(process.env.MONGO_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    
    console.log('βœ… Connected to MongoDB\n');
    
    // Find all users with the malformed role
    const usersWithBadRole = await User.find({
      roles: 'student,host'
    });
    
    console.log(`Found ${usersWithBadRole.length} users with malformed 'student,host' role\n`);
    
    if (usersWithBadRole.length === 0) {
      console.log('βœ… No users need fixing. All roles are properly formatted.');
      await mongoose.disconnect();
      return;
    }
    
    // Process each user
    let fixed = 0;
    const skipped = 0;
    let errors = 0;
    
    for (const user of usersWithBadRole) {
      try {
        console.log(`Processing user: ${user.email} (${user._id})`);
        console.log(`  Current roles: ${JSON.stringify(user.roles)}`);
        
        // Determine correct roles based on user's actual permissions
        const newRoles = ['student'];
        
        // Check if user should be a host
        if (user.canHost || user.hostEligibilityStatus?.status === 'approved') {
          newRoles.push('host');
          console.log('  - User is an approved host, adding \'host\' role');
        }
        
        // Check if user is a verifier
        if (user.verifierEligibilityStatus?.approvedBy) {
          newRoles.push('verifier');
          console.log('  - User is a verifier, adding \'verifier\' role');
        }
        
        // Note: platformAdmin needs manual verification
        // We don't automatically assign it
        
        // Update user
        user.roles = newRoles;
        await user.save();
        
        console.log(`  βœ… Updated roles to: ${JSON.stringify(newRoles)}\n`);
        fixed++;
        
      } catch (error) {
        console.error(`  ❌ Error processing user ${user.email}:`, error.message);
        errors++;
      }
    }
    
    // Summary
    console.log(`\n${  '='.repeat(60)}`);
    console.log('πŸ“Š MIGRATION SUMMARY');
    console.log('='.repeat(60));
    console.log(`Total users processed: ${usersWithBadRole.length}`);
    console.log(`βœ… Successfully fixed: ${fixed}`);
    console.log(`⏭️  Skipped: ${skipped}`);
    console.log(`❌ Errors: ${errors}`);
    console.log(`${'='.repeat(60)  }\n`);
    
    // Verify the fix
    console.log('πŸ” Verifying fix...');
    const stillBroken = await User.find({
      roles: 'student,host'
    });
    
    if (stillBroken.length === 0) {
      console.log('βœ… Verification passed! No users have malformed roles.\n');
    } else {
      console.log(`⚠️  Warning: ${stillBroken.length} users still have malformed roles.\n`);
    }
    
    await mongoose.disconnect();
    console.log('βœ… Migration completed successfully!');
    
  } catch (error) {
    console.error('❌ Migration failed:', error);
    process.exit(1);
  }
}

// Run the migration
if (require.main === module) {
  fixUserRoles()
    .then(() => process.exit(0))
    .catch((error) => {
      console.error('Fatal error:', error);
      process.exit(1);
    });
}

module.exports = fixUserRoles;