AI Resource Pro / website / scripts / create-supabase-admin.ts
| 1 | import { createClient } from '@supabase/supabase-js'; |
| 2 | import * as readline from 'readline'; |
| 3 | import * as dotenv from 'dotenv'; |
| 4 | import * as path from 'path'; |
| 5 | import * as fs from 'fs'; |
| 6 | |
| 7 | // Load environment variables from .env.local |
| 8 | const envLocalPath = path.resolve(process.cwd(), '.env.local'); |
| 9 | if (fs.existsSync(envLocalPath)) { |
| 10 | console.log(`Loading environment from: ${envLocalPath}`); |
| 11 | dotenv.config({ path: envLocalPath }); |
| 12 | } else { |
| 13 | console.log(`No .env.local file found at: ${envLocalPath}`); |
| 14 | dotenv.config(); // Try loading from default .env |
| 15 | } |
| 16 | |
| 17 | // Create readline interface for user input |
| 18 | const rl = readline.createInterface({ |
| 19 | input: process.stdin, |
| 20 | output: process.stdout |
| 21 | }); |
| 22 | |
| 23 | async function createAdminUser() { |
| 24 | console.log('=== Create Supabase Admin User ==='); |
| 25 | |
| 26 | // Get Supabase URL and service role key |
| 27 | const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; |
| 28 | const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; |
| 29 | |
| 30 | console.log('Environment variables:'); |
| 31 | console.log(`NEXT_PUBLIC_SUPABASE_URL: ${supabaseUrl ? 'Found (starts with ' + supabaseUrl.substring(0, 10) + '...)' : 'Not found'}`); |
| 32 | console.log(`SUPABASE_SERVICE_ROLE_KEY: ${supabaseServiceKey ? 'Found (starts with ' + supabaseServiceKey.substring(0, 10) + '...)' : 'Not found'}`); |
| 33 | |
| 34 | if (!supabaseUrl || !supabaseServiceKey) { |
| 35 | console.error('Missing Supabase environment variables. Please set NEXT_PUBLIC_SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY.'); |
| 36 | rl.close(); |
| 37 | return; |
| 38 | } |
| 39 | |
| 40 | // Create Supabase client with service role key |
| 41 | const supabase = createClient(supabaseUrl, supabaseServiceKey); |
| 42 | |
| 43 | // Prompt for email |
| 44 | const email = await new Promise<string>((resolve) => { |
| 45 | rl.question('Enter email: ', (answer) => { |
| 46 | resolve(answer.trim().toLowerCase()); |
| 47 | }); |
| 48 | }); |
| 49 | |
| 50 | if (!email.includes('@')) { |
| 51 | console.error('Invalid email format'); |
| 52 | rl.close(); |
| 53 | return; |
| 54 | } |
| 55 | |
| 56 | // We'll skip the direct auth.users query as it's not accessible via the Data API |
| 57 | // and go straight to checking if the user exists via the auth API |
| 58 | |
| 59 | let userId: string | undefined; |
| 60 | let userName: string | undefined; |
| 61 | |
| 62 | // Prompt for password (we'll need this even for existing users to ensure we have it) |
| 63 | const password = await new Promise<string>((resolve) => { |
| 64 | rl.question('Enter password (min 6 characters): ', (answer) => { |
| 65 | resolve(answer.trim()); |
| 66 | }); |
| 67 | }); |
| 68 | |
| 69 | if (password.length < 6) { |
| 70 | console.error('Password must be at least 6 characters long'); |
| 71 | rl.close(); |
| 72 | return; |
| 73 | } |
| 74 | |
| 75 | // Prompt for name (optional) |
| 76 | const name = await new Promise<string>((resolve) => { |
| 77 | rl.question('Enter name (optional): ', (answer) => { |
| 78 | resolve(answer.trim()); |
| 79 | }); |
| 80 | }); |
| 81 | |
| 82 | if (name) { |
| 83 | userName = name; |
| 84 | } |
| 85 | |
| 86 | try { |
| 87 | // Try to create the user first |
| 88 | const { data: authData, error: authError } = await supabase.auth.admin.createUser({ |
| 89 | email, |
| 90 | password, |
| 91 | email_confirm: true, |
| 92 | user_metadata: { |
| 93 | name: userName || null, |
| 94 | }, |
| 95 | }); |
| 96 | |
| 97 | if (authError) { |
| 98 | // If user already exists |
| 99 | if (authError.message.includes('already been registered')) { |
| 100 | console.log('User exists in Auth. Trying to get user details...'); |
| 101 | |
| 102 | // Try to get user by email using the auth API |
| 103 | const { data: userData, error: userError } = await supabase.auth.admin.listUsers(); |
| 104 | |
| 105 | if (userError) { |
| 106 | console.error('Error listing users:', userError); |
| 107 | rl.close(); |
| 108 | return; |
| 109 | } |
| 110 | |
| 111 | const existingUser = userData.users.find(u => u.email === email); |
| 112 | |
| 113 | if (!existingUser) { |
| 114 | console.error('Could not find user with this email.'); |
| 115 | rl.close(); |
| 116 | return; |
| 117 | } |
| 118 | |
| 119 | userId = existingUser.id; |
| 120 | console.log(`Found existing user with ID: ${userId}`); |
| 121 | |
| 122 | // Update the user's password if provided |
| 123 | const { error: updateUserError } = await supabase.auth.admin.updateUserById( |
| 124 | userId, |
| 125 | { password, email_confirm: true } |
| 126 | ); |
| 127 | |
| 128 | if (updateUserError) { |
| 129 | console.error('Error updating user password:', updateUserError); |
| 130 | // Continue anyway as we might just want to make them admin |
| 131 | } else { |
| 132 | console.log('Updated user password successfully'); |
| 133 | } |
| 134 | } else { |
| 135 | console.error('Error creating user in Supabase Auth:'); |
| 136 | console.error(authError); |
| 137 | rl.close(); |
| 138 | return; |
| 139 | } |
| 140 | } else { |
| 141 | userId = authData.user.id; |
| 142 | console.log(`Created new user with ID: ${userId}`); |
| 143 | } |
| 144 | |
| 145 | if (!userId) { |
| 146 | console.error('Failed to get user ID'); |
| 147 | rl.close(); |
| 148 | return; |
| 149 | } |
| 150 | |
| 151 | // Now we have a userId, let's make sure they're an admin |
| 152 | // First check if user exists in the users table |
| 153 | const { data: existingUser, error: userCheckError } = await supabase |
| 154 | .from('users') |
| 155 | .select('*') |
| 156 | .eq('id', userId) |
| 157 | .maybeSingle(); |
| 158 | |
| 159 | if (userCheckError) { |
| 160 | console.error('Error checking if user exists in users table:'); |
| 161 | console.error(userCheckError); |
| 162 | |
| 163 | // If the error is about the table not existing, we need to create it |
| 164 | if (userCheckError.message.includes('does not exist')) { |
| 165 | console.log('The users table might not exist. Please run the SQL schema script first.'); |
| 166 | console.log('You can find it at scripts/create-supabase-schema.sql'); |
| 167 | rl.close(); |
| 168 | return; |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | if (existingUser) { |
| 173 | // Update existing user |
| 174 | const { error: updateError } = await supabase |
| 175 | .from('users') |
| 176 | .update({ |
| 177 | is_admin: true, |
| 178 | name: userName || existingUser.name |
| 179 | }) |
| 180 | .eq('id', userId); |
| 181 | |
| 182 | if (updateError) { |
| 183 | console.error('Error updating user as admin:'); |
| 184 | console.error(updateError); |
| 185 | rl.close(); |
| 186 | return; |
| 187 | } |
| 188 | |
| 189 | console.log('User updated as admin successfully'); |
| 190 | } else { |
| 191 | // Insert new user record |
| 192 | const { error: insertError } = await supabase |
| 193 | .from('users') |
| 194 | .insert({ |
| 195 | id: userId, |
| 196 | email, |
| 197 | name: userName || null, |
| 198 | is_admin: true, |
| 199 | }); |
| 200 | |
| 201 | if (insertError) { |
| 202 | console.error('Error inserting user record:'); |
| 203 | console.error(insertError); |
| 204 | rl.close(); |
| 205 | return; |
| 206 | } |
| 207 | |
| 208 | console.log('User added to users table as admin successfully'); |
| 209 | } |
| 210 | |
| 211 | console.log('Admin user setup completed:'); |
| 212 | console.log(`Email: ${email}`); |
| 213 | console.log(`Name: ${userName || '(not provided)'}`); |
| 214 | console.log(`Admin: true`); |
| 215 | console.log(`ID: ${userId}`); |
| 216 | } catch (error) { |
| 217 | console.error('Error setting up admin user:'); |
| 218 | console.error(error); |
| 219 | } finally { |
| 220 | rl.close(); |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | // Run the function |
| 225 | createAdminUser().catch((error) => { |
| 226 | console.error('Unhandled error:'); |
| 227 | console.error(error); |
| 228 | rl.close(); |
| 229 | process.exit(1); |
| 230 | }); |