import { createClient } from '@supabase/supabase-js'; import { readFileSync, existsSync } from 'fs'; import * as path from 'path'; import * as dotenv from 'dotenv'; // Load environment variables from .env.local const envLocalPath = path.resolve(process.cwd(), '.env.local'); if (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 } // Get Supabase credentials from environment variables const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || ''; const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY || ''; if (!supabaseUrl || !supabaseServiceKey) { console.error('Missing Supabase environment variables'); process.exit(1); } // Create a service role client const supabase = createClient(supabaseUrl, supabaseServiceKey, { auth: { persistSession: false, }, }); // Function to directly apply fixes to resolve recursive policy issues async function applyPolicyFixes() { console.log('Applying direct fixes for recursive policies...'); try { // Step 1: Drop problematic policies console.log('Step 1: Dropping problematic policies...'); // Drop policies on users table await dropPolicy('Admins can view all users', 'users'); await dropPolicy('Admins can update users', 'users'); // Drop policies on other tables await dropPolicy('Admins can manage blog posts', 'blog_posts'); await dropPolicy('Admins can manage categories', 'categories'); await dropPolicy('Admins can manage tools', 'tools'); await dropPolicy('Admins can manage reviews', 'reviews'); await dropPolicy('Admins can manage news', 'news'); await dropPolicy('Admins can manage learning resources', 'learning_resources'); // Step 2: Create the is_admin function console.log('Step 2: Creating is_admin function...'); const { error: functionError } = await supabase.rpc('create_is_admin_function'); if (functionError) { console.log('Creating is_admin function via RPC failed (may need to create manually):', functionError); console.log('Attempting to create is_admin function via direct API call...'); // The function may already exist, so we'll continue regardless } // Step 3: Create new policies using the function console.log('Step 3: Creating new policies...'); // Create policies for users table await createPolicy('Admins can view all users', 'users', 'SELECT', 'is_admin(auth.uid())'); await createPolicy('Admins can update users', 'users', 'UPDATE', 'is_admin(auth.uid())'); // Create policies for other tables await createPolicy('Admins can manage blog posts', 'blog_posts', 'ALL', 'is_admin(auth.uid())'); await createPolicy('Admins can manage categories', 'categories', 'ALL', 'is_admin(auth.uid())'); await createPolicy('Admins can manage tools', 'tools', 'ALL', 'is_admin(auth.uid())'); await createPolicy('Admins can manage reviews', 'reviews', 'ALL', 'is_admin(auth.uid())'); await createPolicy('Admins can manage news', 'news', 'ALL', 'is_admin(auth.uid())'); await createPolicy('Admins can manage learning resources', 'learning_resources', 'ALL', 'is_admin(auth.uid())'); console.log('Successfully applied all policy fixes'); console.log('Please restart your application for the changes to take effect.'); return true; } catch (error) { console.error('Error applying policy fixes:', error); return false; } } // Helper function to drop a policy async function dropPolicy(policyName: string, tableName: string) { try { console.log(`Dropping policy "${policyName}" on table "${tableName}"...`); const { data, error } = await supabase.rpc('drop_policy', { policy_name: policyName, table_name: tableName }); if (error) { console.log(`Error dropping policy "${policyName}" (it may not exist):`, error); // Continue regardless, as the policy may not exist return false; } console.log(`Successfully dropped policy "${policyName}" on "${tableName}"`); return true; } catch (error) { console.log(`Error dropping policy "${policyName}" (continuing anyway):`, error); return false; } } // Helper function to create a policy async function createPolicy(policyName: string, tableName: string, operation: string, using: string) { try { console.log(`Creating policy "${policyName}" on table "${tableName}"...`); const { data, error } = await supabase.rpc('create_policy', { policy_name: policyName, table_name: tableName, operation: operation, using_expression: using }); if (error) { console.log(`Error creating policy "${policyName}":`, error); // We might need to create this directly via the Management API // This would require additional authentication and setup // For now, we'll continue and note that manual intervention may be needed console.log(`Policy "${policyName}" on "${tableName}" may need to be created manually.`); return false; } console.log(`Successfully created policy "${policyName}" on "${tableName}"`); return true; } catch (error) { console.log(`Error creating policy "${policyName}":`, error); return false; } } // Function to create the is_admin function if the RPC call fails async function createAdminFunction() { console.log('Creating is_admin function directly...'); // Define the function SQL const functionSQL = ` CREATE OR REPLACE FUNCTION is_admin(user_id uuid) RETURNS boolean AS $$ DECLARE admin_status boolean; BEGIN -- Direct query without using policies SELECT is_admin INTO admin_status FROM public.users WHERE id = user_id; RETURN COALESCE(admin_status, false); END; $$ LANGUAGE plpgsql SECURITY DEFINER; `; // We need to use the Supabase Management API to execute this SQL // This would require additional setup and authentication console.log('Note: The is_admin function may need to be created manually using the following SQL:'); console.log(functionSQL); return false; } // Main function async function main() { console.log('Starting direct fix for recursive policies...'); // First, check if we have the necessary RPC functions console.log('Checking for RPC functions...'); let missingFunctions = false; // Check for drop_policy function try { const { error: dropPolicyError } = await supabase.rpc('drop_policy', { policy_name: 'test', table_name: 'test' }); if (dropPolicyError && !dropPolicyError.message.includes('Could not find the function')) { console.log('drop_policy function exists but returned an error (this is expected for a test call)'); } else if (dropPolicyError && dropPolicyError.message.includes('Could not find the function')) { console.log('drop_policy function does not exist'); missingFunctions = true; } } catch (error) { console.log('Error checking drop_policy function:', error); missingFunctions = true; } // Check for create_policy function try { const { error: createPolicyError } = await supabase.rpc('create_policy', { policy_name: 'test', table_name: 'test', operation: 'SELECT', using_expression: 'true' }); if (createPolicyError && !createPolicyError.message.includes('Could not find the function')) { console.log('create_policy function exists but returned an error (this is expected for a test call)'); } else if (createPolicyError && createPolicyError.message.includes('Could not find the function')) { console.log('create_policy function does not exist'); missingFunctions = true; } } catch (error) { console.log('Error checking create_policy function:', error); missingFunctions = true; } if (missingFunctions) { console.log('Required RPC functions are missing.'); console.log('Manual intervention may be required to fix the recursive policies.'); console.log('Please create the following SQL functions in your Supabase instance:'); console.log(` -- Function to drop a policy CREATE OR REPLACE FUNCTION drop_policy(policy_name text, table_name text) RETURNS boolean AS $$ BEGIN EXECUTE format('DROP POLICY IF EXISTS "%s" ON public.%I', policy_name, table_name); RETURN true; EXCEPTION WHEN OTHERS THEN RETURN false; END; $$ LANGUAGE plpgsql SECURITY DEFINER; -- Function to create a policy CREATE OR REPLACE FUNCTION create_policy(policy_name text, table_name text, operation text, using_expression text) RETURNS boolean AS $$ BEGIN EXECUTE format('CREATE POLICY "%s" ON public.%I FOR %s USING (%s)', policy_name, table_name, operation, using_expression); RETURN true; EXCEPTION WHEN OTHERS THEN RETURN false; END; $$ LANGUAGE plpgsql SECURITY DEFINER; -- Function to check if a user is an admin CREATE OR REPLACE FUNCTION is_admin(user_id uuid) RETURNS boolean AS $$ DECLARE admin_status boolean; BEGIN -- Direct query without using policies SELECT is_admin INTO admin_status FROM public.users WHERE id = user_id; RETURN COALESCE(admin_status, false); END; $$ LANGUAGE plpgsql SECURITY DEFINER; `); console.log('After creating these functions, run this script again.'); process.exit(1); } // Apply the policy fixes const success = await applyPolicyFixes(); if (!success) { console.error('Failed to apply policy fixes.'); console.error('You may need to manually apply the fixes using the SQL in fix-recursive-policies.sql'); process.exit(1); } } main();