import { createClient } from '@supabase/supabase-js'; import * as readline from 'readline'; import * as dotenv from 'dotenv'; import * as path from 'path'; import * as fs from 'fs'; // Load environment variables from .env.local const envLocalPath = path.resolve(process.cwd(), '.env.local'); if (fs.existsSync(envLocalPath)) { console.log(`Loading environment from: ${envLocalPath}`); dotenv.config({ path: envLocalPath }); } else { console.log(`No .env.local file found at: ${envLocalPath}`); dotenv.config(); // Try loading from default .env } // Create readline interface for user input const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); async function createAdminUser() { console.log('=== Create Supabase Admin User ==='); // Get Supabase URL and service role key const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; console.log('Environment variables:'); console.log(`NEXT_PUBLIC_SUPABASE_URL: ${supabaseUrl ? 'Found (starts with ' + supabaseUrl.substring(0, 10) + '...)' : 'Not found'}`); console.log(`SUPABASE_SERVICE_ROLE_KEY: ${supabaseServiceKey ? 'Found (starts with ' + supabaseServiceKey.substring(0, 10) + '...)' : 'Not found'}`); if (!supabaseUrl || !supabaseServiceKey) { console.error('Missing Supabase environment variables. Please set NEXT_PUBLIC_SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY.'); rl.close(); return; } // Create Supabase client with service role key const supabase = createClient(supabaseUrl, supabaseServiceKey); // Prompt for email const email = await new Promise((resolve) => { rl.question('Enter email: ', (answer) => { resolve(answer.trim().toLowerCase()); }); }); if (!email.includes('@')) { console.error('Invalid email format'); rl.close(); return; } // We'll skip the direct auth.users query as it's not accessible via the Data API // and go straight to checking if the user exists via the auth API let userId: string | undefined; let userName: string | undefined; // Prompt for password (we'll need this even for existing users to ensure we have it) const password = await new Promise((resolve) => { rl.question('Enter password (min 6 characters): ', (answer) => { resolve(answer.trim()); }); }); if (password.length < 6) { console.error('Password must be at least 6 characters long'); rl.close(); return; } // Prompt for name (optional) const name = await new Promise((resolve) => { rl.question('Enter name (optional): ', (answer) => { resolve(answer.trim()); }); }); if (name) { userName = name; } try { // Try to create the user first const { data: authData, error: authError } = await supabase.auth.admin.createUser({ email, password, email_confirm: true, user_metadata: { name: userName || null, }, }); if (authError) { // If user already exists if (authError.message.includes('already been registered')) { console.log('User exists in Auth. Trying to get user details...'); // Try to get user by email using the auth API const { data: userData, error: userError } = await supabase.auth.admin.listUsers(); if (userError) { console.error('Error listing users:', userError); rl.close(); return; } const existingUser = userData.users.find(u => u.email === email); if (!existingUser) { console.error('Could not find user with this email.'); rl.close(); return; } userId = existingUser.id; console.log(`Found existing user with ID: ${userId}`); // Update the user's password if provided const { error: updateUserError } = await supabase.auth.admin.updateUserById( userId, { password, email_confirm: true } ); if (updateUserError) { console.error('Error updating user password:', updateUserError); // Continue anyway as we might just want to make them admin } else { console.log('Updated user password successfully'); } } else { console.error('Error creating user in Supabase Auth:'); console.error(authError); rl.close(); return; } } else { userId = authData.user.id; console.log(`Created new user with ID: ${userId}`); } if (!userId) { console.error('Failed to get user ID'); rl.close(); return; } // Now we have a userId, let's make sure they're an admin // First check if user exists in the users table const { data: existingUser, error: userCheckError } = await supabase .from('users') .select('*') .eq('id', userId) .maybeSingle(); if (userCheckError) { console.error('Error checking if user exists in users table:'); console.error(userCheckError); // If the error is about the table not existing, we need to create it if (userCheckError.message.includes('does not exist')) { console.log('The users table might not exist. Please run the SQL schema script first.'); console.log('You can find it at scripts/create-supabase-schema.sql'); rl.close(); return; } } if (existingUser) { // Update existing user const { error: updateError } = await supabase .from('users') .update({ is_admin: true, name: userName || existingUser.name }) .eq('id', userId); if (updateError) { console.error('Error updating user as admin:'); console.error(updateError); rl.close(); return; } console.log('User updated as admin successfully'); } else { // Insert new user record const { error: insertError } = await supabase .from('users') .insert({ id: userId, email, name: userName || null, is_admin: true, }); if (insertError) { console.error('Error inserting user record:'); console.error(insertError); rl.close(); return; } console.log('User added to users table as admin successfully'); } console.log('Admin user setup completed:'); console.log(`Email: ${email}`); console.log(`Name: ${userName || '(not provided)'}`); console.log(`Admin: true`); console.log(`ID: ${userId}`); } catch (error) { console.error('Error setting up admin user:'); console.error(error); } finally { rl.close(); } } // Run the function createAdminUser().catch((error) => { console.error('Unhandled error:'); console.error(error); rl.close(); process.exit(1); });