Fix jwt-token
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* Migration: Add tenant support to devices table
|
||||
* This migration adds tenant_id field to devices for multi-tenant isolation
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
// Check if tenant_id column already exists
|
||||
const tableDescription = await queryInterface.describeTable('devices');
|
||||
|
||||
if (!tableDescription.tenant_id) {
|
||||
// Add tenant_id column to devices table
|
||||
await queryInterface.addColumn('devices', 'tenant_id', {
|
||||
type: Sequelize.INTEGER,
|
||||
allowNull: true, // Nullable for backward compatibility
|
||||
references: {
|
||||
model: 'tenants',
|
||||
key: 'id'
|
||||
},
|
||||
onUpdate: 'CASCADE',
|
||||
onDelete: 'SET NULL',
|
||||
comment: 'Foreign key to tenants table for multi-tenant isolation'
|
||||
});
|
||||
|
||||
// Add index for tenant_id for better query performance
|
||||
try {
|
||||
await queryInterface.addIndex('devices', ['tenant_id'], {
|
||||
name: 'devices_tenant_id_idx'
|
||||
});
|
||||
console.log('✅ Added index on devices.tenant_id');
|
||||
} catch (error) {
|
||||
if (error.parent?.code === '42P07') { // Index already exists
|
||||
console.log('⚠️ Index devices_tenant_id already exists, skipping...');
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Associate existing devices with default tenant (backward compatibility)
|
||||
const defaultTenant = await queryInterface.sequelize.query(
|
||||
'SELECT id FROM tenants WHERE slug = :slug',
|
||||
{
|
||||
replacements: { slug: 'default' },
|
||||
type: Sequelize.QueryTypes.SELECT
|
||||
}
|
||||
);
|
||||
|
||||
if (defaultTenant.length > 0) {
|
||||
await queryInterface.sequelize.query(
|
||||
'UPDATE devices SET tenant_id = :tenantId WHERE tenant_id IS NULL',
|
||||
{
|
||||
replacements: { tenantId: defaultTenant[0].id },
|
||||
type: Sequelize.QueryTypes.UPDATE
|
||||
}
|
||||
);
|
||||
console.log('✅ Associated existing devices with default tenant');
|
||||
}
|
||||
|
||||
console.log('✅ Added tenant_id field to devices table');
|
||||
} else {
|
||||
console.log('⚠️ Column tenant_id already exists in devices table, skipping...');
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
// Remove index
|
||||
try {
|
||||
await queryInterface.removeIndex('devices', 'devices_tenant_id_idx');
|
||||
} catch (error) {
|
||||
console.log('⚠️ Index devices_tenant_id_idx does not exist, skipping...');
|
||||
}
|
||||
|
||||
// Remove column
|
||||
await queryInterface.removeColumn('devices', 'tenant_id');
|
||||
console.log('✅ Removed tenant_id field from devices table');
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user