File size: 2,111 Bytes
83f4356
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603b587
83f4356
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70a0a13
a4d7990
83f4356
 
 
 
 
 
 
 
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
75
76
77
78
79
80
/**
 * Admin Seed Script — creates the first admin account.
 * Run once: node scripts/seed-admin.js
 *
 * Uses the admin credentials from .env:
 *   ADMIN_EMAIL, ADMIN_PASSWORD, ADMIN_USERNAME
 */

require('dotenv').config();
const { createClient } = require('@supabase/supabase-js');

const supabaseAdmin = createClient(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_SERVICE_ROLE_KEY
);

async function seedAdmin() {
  console.log('🌱 Seeding admin account...\n');

  const email = process.env.ADMIN_EMAIL || 'shard.chogale1983@gmail.com';
  const password = process.env.ADMIN_PASSWORD || 'changeme';
  const username = process.env.ADMIN_USERNAME || 'admin';

  // Check if admin already exists
  const { data: existingProfile } = await supabaseAdmin
    .from('profiles')
    .select('id')
    .eq('role', 'admin')
    .single();

  if (existingProfile) {
    console.log('⚠️  Admin already exists. Skipping seed.');
    process.exit(0);
  }

  // Create auth user
  const { data: authData, error: authError } = await supabaseAdmin.auth.admin.createUser({
    email,
    password,
    email_confirm: true,
  });

  if (authError) {
    console.error('❌ Failed to create admin auth user:', authError.message);
    process.exit(1);
  }

  const userId = authData.user.id;

  // Create profile
  const { error: profileError } = await supabaseAdmin
    .from('profiles')
    .insert({
      id: userId,
      role: 'admin',
      username,
      display_name: 'Green Guard Admin',
      email,
    });

  if (profileError) {
    console.error('❌ Failed to create admin profile:', profileError.message);
    // Rollback auth user
    await supabaseAdmin.auth.admin.deleteUser(userId);
    process.exit(1);
  }

  console.log('✅ Admin account created successfully!');
  console.log(`   Email    : ${email}`);
  console.log('   Username : [REDACTED]');
  console.log('   Role     : admin');
  console.log(`   ID       : ${userId}`);
  console.log('\n   You can now log in via POST /api/auth/login');
}

seedAdmin().catch((err) => {
  console.error('❌ Seed failed:', err);
  process.exit(1);
});