All files / src/db seed_admin_account.ts

78.37% Statements 58/74
50% Branches 2/4
100% Functions 2/2
78.37% Lines 58/74

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 751x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
// src/db/seed_admin_account.ts
import { Pool } from 'pg';
import bcrypt from 'bcrypt';
 
const pool = new Pool({
  user: process.env.DB_USER,
  host: process.env.DB_HOST,
  database: process.env.DB_NAME,
  password: process.env.DB_PASSWORD,
  port: parseInt(process.env.DB_PORT || '5432', 10), // Keep fallback for port
});
 
const ADMIN_EMAIL = 'admin@example.com';
const ADMIN_PASSWORD = 'adminpass'; // The plain text password for development/testing
 
async function seedAdminUser() {
  const client = await pool.connect();
  console.log('Connected to the database.');
 
  try {
    // Check if the admin user already exists
    const existingUserRes = await client.query(
      'SELECT user_id FROM public.users WHERE email = $1',
      [ADMIN_EMAIL],
    );
 
    if (existingUserRes.rows.length > 0) {
      const userId = existingUserRes.rows[0].user_id;
      console.log(`Admin user '${ADMIN_EMAIL}' already exists with ID: ${userId}.`);

      // Ensure the user has the 'admin' role
      const profileRes = await client.query('SELECT role FROM public.profiles WHERE user_id = $1', [
        userId,
      ]);
      if (profileRes.rows.length === 0 || profileRes.rows[0].role !== 'admin') {
        await client.query("UPDATE public.profiles SET role = 'admin' WHERE id = $1", [userId]);
        console.log(`Updated role to 'admin' for user ${userId}.`);
      } else {
        console.log(`User ${userId} already has 'admin' role.`);
      }
      return;
    }
 
    // If user does not exist, create them
    console.log(`Admin user '${ADMIN_EMAIL}' not found. Creating...`);
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(ADMIN_PASSWORD, saltRounds);
 
    // Insert into the users table. The `handle_new_user` trigger will create the profile.
    const newUserRes = await client.query(
      'INSERT INTO public.users (email, password_hash) VALUES ($1, $2) RETURNING user_id',
      [ADMIN_EMAIL, hashedPassword],
    );
 
    const newUserId = newUserRes.rows[0].user_id;
    console.log(`Successfully created user with ID: ${newUserId}.`);
 
    // The trigger creates a profile with the 'user' role. We now update it to 'admin'.
    await client.query("UPDATE public.profiles SET role = 'admin' WHERE user_id = $1", [newUserId]);
 
    console.log(`Successfully set role to 'admin' for user ${newUserId}.`);
    console.log('Admin user seeding complete!');
  } catch (error) {
    console.error('Error during admin user seeding:', error);
  } finally {
    await client.release();
    console.log('Database client released.');
    await pool.end();
    console.log('Connection pool closed.');
  }
}
 
// Execute the seeding function
seedAdminUser();