punimtag/viewer-frontend/scripts/run-email-verification-migration.ts
Tanya de2144be2a feat: Add new scripts and update project structure for database management and user authentication
This commit introduces several new scripts for managing database operations, including user creation, permission grants, and data migrations. It also adds new documentation files to guide users through the setup and configuration processes. Additionally, the project structure is updated to enhance organization and maintainability, ensuring a smoother development experience for contributors. These changes support the ongoing transition to a web-based architecture and improve overall project functionality.
2026-01-06 13:53:24 -05:00

81 lines
3.1 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { PrismaClient as PrismaClientAuth } from '../node_modules/.prisma/client-auth';
import * as fs from 'fs';
import * as path from 'path';
const prismaAuth = new PrismaClientAuth({
datasourceUrl: process.env.DATABASE_URL_AUTH,
});
async function runMigration() {
try {
console.log('🔄 Running email verification migration...');
console.log('📝 Reading migration file...');
const migrationPath = path.join(__dirname, '../migrations/add-email-verification-columns.sql');
const migrationSQL = fs.readFileSync(migrationPath, 'utf-8');
// Execute each SQL statement individually
const statements = [
`ALTER TABLE users ADD COLUMN IF NOT EXISTS email_verified BOOLEAN NOT NULL DEFAULT true;`,
`ALTER TABLE users ADD COLUMN IF NOT EXISTS email_confirmation_token VARCHAR(255) UNIQUE;`,
`ALTER TABLE users ADD COLUMN IF NOT EXISTS email_confirmation_token_expiry TIMESTAMP;`,
`CREATE INDEX IF NOT EXISTS idx_users_email_confirmation_token ON users(email_confirmation_token);`,
`UPDATE users SET email_verified = true WHERE email_confirmation_token IS NULL;`,
];
console.log(`📋 Executing ${statements.length} SQL statements...`);
for (let i = 0; i < statements.length; i++) {
const statement = statements[i];
try {
await prismaAuth.$executeRawUnsafe(statement);
const desc = statement.split(' ').slice(0, 4).join(' ').toLowerCase();
console.log(`✅ [${i + 1}/${statements.length}] ${desc}...`);
} catch (error: any) {
// Ignore "already exists" errors
if (error.message?.includes('already exists') ||
error.message?.includes('duplicate') ||
error.message?.includes('IF NOT EXISTS')) {
const desc = statement.split(' ').slice(0, 4).join(' ').toLowerCase();
console.log(` [${i + 1}/${statements.length}] ${desc}... (already exists)`);
} else {
console.error(`❌ Error executing statement ${i + 1}:`, error.message);
throw error;
}
}
}
console.log('✅ Migration completed successfully!');
console.log('');
console.log('📊 Verifying migration...');
// Verify the columns were added
const result = await prismaAuth.$queryRawUnsafe<Array<{column_name: string}>>(`
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'users'
AND column_name IN ('email_verified', 'email_confirmation_token', 'email_confirmation_token_expiry')
ORDER BY column_name;
`);
console.log('✅ Found columns:', result.map(r => r.column_name).join(', '));
// Check existing users
const userCount = await prismaAuth.user.count();
const verifiedCount = await prismaAuth.user.count({
where: { emailVerified: true }
});
console.log(`📊 Users: ${userCount} total, ${verifiedCount} verified`);
} catch (error: any) {
console.error('❌ Migration failed:', error.message);
process.exit(1);
} finally {
await prismaAuth.$disconnect();
}
}
runMigration();