const { sequelize } = require('../config/database'); const bcrypt = require('bcrypt'); const migration = { async up() { const queryInterface = sequelize.getQueryInterface(); // Add password column await queryInterface.addColumn('users', 'password', { type: sequelize.Sequelize.STRING, allowNull: true, // Initially null, we'll update existing users }); // Add lastLoginAt column await queryInterface.addColumn('users', 'lastLoginAt', { type: sequelize.Sequelize.DATE, allowNull: true, }); // Update existing users with default passwords and ensure they have proper role setup const users = await sequelize.query('SELECT id, email FROM users', { type: sequelize.QueryTypes.SELECT, }); for (const user of users) { // Hash default password for existing users const defaultPassword = 'changeMe123!'; const hashedPassword = await bcrypt.hash(defaultPassword, 10); // Special handling for daveporter@oliver.agency if (user.email === 'daveporter@oliver.agency') { await sequelize.query( `UPDATE users SET password = :password, preferences = COALESCE(preferences, '{}'::jsonb) || '{"role": "admin", "allowedAgents": null}'::jsonb WHERE id = :id`, { replacements: { password: hashedPassword, id: user.id }, type: sequelize.QueryTypes.UPDATE, } ); } else { // Regular users get no agents by default await sequelize.query( `UPDATE users SET password = :password, preferences = COALESCE(preferences, '{}'::jsonb) || '{"role": "user", "allowedAgents": []}'::jsonb WHERE id = :id`, { replacements: { password: hashedPassword, id: user.id }, type: sequelize.QueryTypes.UPDATE, } ); } } // Make password column required after updating existing records await queryInterface.changeColumn('users', 'password', { type: sequelize.Sequelize.STRING, allowNull: false, }); console.log('✅ Authentication fields added successfully'); console.log('ℹ️ Existing users have been set with default password: changeMe123!'); console.log('ℹ️ daveporter@oliver.agency has been set as admin'); console.log('ℹ️ Other users have been set as regular users with no agent access'); }, async down() { const queryInterface = sequelize.getQueryInterface(); await queryInterface.removeColumn('users', 'password'); await queryInterface.removeColumn('users', 'lastLoginAt'); console.log('✅ Authentication fields removed'); }, }; module.exports = migration;