/** * Helper script to create a test API key for development * Usage: node scripts/create-test-api-key.js */ require('dotenv').config(); const crypto = require('crypto'); const { query, connectDB } = require('../src/database/connection'); function generateApiKey(type = 'test') { const prefix = type === 'test' ? 'vf_test_' : 'vf_live_'; return prefix + crypto.randomBytes(24).toString('hex'); } async function createTestApiKey() { try { await connectDB(); console.log('✅ Connected to database\n'); // Check if test user exists let testUser = await query( 'SELECT * FROM users WHERE email = $1', ['test@example.com'] ); let userId; if (testUser.rows.length === 0) { // Create test user console.log('Creating test user...'); const bcrypt = require('bcryptjs'); const passwordHash = await bcrypt.hash('testpassword123', 10); const userResult = await query( `INSERT INTO users (email, password_hash, company_name, plan, monthly_quota, quota_reset_date, is_active) VALUES ($1, $2, $3, $4, $5, DATE(NOW() + INTERVAL '1 month'), true) RETURNING id, email, plan`, ['test@example.com', passwordHash, 'Test Company', 'free', 10000] ); userId = userResult.rows[0].id; console.log(`✅ Created test user (ID: ${userId})`); } else { userId = testUser.rows[0].id; console.log(`✅ Using existing test user (ID: ${userId})`); } // Check for existing test API key const existingKeys = await query( `SELECT ak.* FROM api_keys ak WHERE ak.user_id = $1 AND ak.is_test_key = true AND ak.is_active = true`, [userId] ); let apiKey; if (existingKeys.rows.length > 0) { // Show existing key (we can't retrieve the original, so we'll create a new one) console.log('⚠️ Test API key already exists. Creating a new one...'); // Deactivate old keys await query( 'UPDATE api_keys SET is_active = false WHERE user_id = $1 AND is_test_key = true', [userId] ); } // Generate new API key apiKey = generateApiKey('test'); const keyHash = crypto.createHash('sha256').update(apiKey).digest('hex'); await query( `INSERT INTO api_keys (user_id, key_prefix, key_hash, key_hint, name, is_test_key, is_active) VALUES ($1, $2, $3, $4, $5, true, true)`, [userId, 'vf_test_', keyHash, apiKey.slice(-4), 'Test Key'] ); console.log('\n✅ Test API Key Created Successfully!\n'); console.log('=' .repeat(60)); console.log('API Key:'); console.log(apiKey); console.log('=' .repeat(60)); console.log('\nUsage:'); console.log('curl -H "x-api-key: ' + apiKey + '" http://localhost:3000/v1/gst/verify/27AAACM1234A1Z5'); console.log('\nOr use in Postman/Thunder Client:'); console.log('Header: x-api-key'); console.log('Value: ' + apiKey); console.log('\n'); process.exit(0); } catch (error) { console.error('❌ Error:', error.message); console.error(error); process.exit(1); } } createTestApiKey();