Branchwell

AI Resource Pro / website / scripts / direct-fix-recursive-policies.ts

1import { createClient } from '@supabase/supabase-js';
2import { readFileSync, existsSync } from 'fs';
3import * as path from 'path';
4import * as dotenv from 'dotenv';
5
6// Load environment variables from .env.local
7const envLocalPath = path.resolve(process.cwd(), '.env.local');
8if (existsSync(envLocalPath)) {
9 console.log(`Loading environment from: ${envLocalPath}`);
10 dotenv.config({ path: envLocalPath });
11} else {
12 console.log(`No .env.local file found at: ${envLocalPath}`);
13 dotenv.config(); // Try loading from default .env
14}
15
16// Get Supabase credentials from environment variables
17const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || '';
18const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY || '';
19
20if (!supabaseUrl || !supabaseServiceKey) {
21 console.error('Missing Supabase environment variables');
22 process.exit(1);
23}
24
25// Create a service role client
26const supabase = createClient(supabaseUrl, supabaseServiceKey, {
27 auth: {
28 persistSession: false,
29 },
30});
31
32// Function to directly apply fixes to resolve recursive policy issues
33async function applyPolicyFixes() {
34 console.log('Applying direct fixes for recursive policies...');
35
36 try {
37 // Step 1: Drop problematic policies
38 console.log('Step 1: Dropping problematic policies...');
39
40 // Drop policies on users table
41 await dropPolicy('Admins can view all users', 'users');
42 await dropPolicy('Admins can update users', 'users');
43
44 // Drop policies on other tables
45 await dropPolicy('Admins can manage blog posts', 'blog_posts');
46 await dropPolicy('Admins can manage categories', 'categories');
47 await dropPolicy('Admins can manage tools', 'tools');
48 await dropPolicy('Admins can manage reviews', 'reviews');
49 await dropPolicy('Admins can manage news', 'news');
50 await dropPolicy('Admins can manage learning resources', 'learning_resources');
51
52 // Step 2: Create the is_admin function
53 console.log('Step 2: Creating is_admin function...');
54 const { error: functionError } = await supabase.rpc('create_is_admin_function');
55
56 if (functionError) {
57 console.log('Creating is_admin function via RPC failed (may need to create manually):', functionError);
58
59 console.log('Attempting to create is_admin function via direct API call...');
60 // The function may already exist, so we'll continue regardless
61 }
62
63 // Step 3: Create new policies using the function
64 console.log('Step 3: Creating new policies...');
65
66 // Create policies for users table
67 await createPolicy('Admins can view all users', 'users', 'SELECT', 'is_admin(auth.uid())');
68 await createPolicy('Admins can update users', 'users', 'UPDATE', 'is_admin(auth.uid())');
69
70 // Create policies for other tables
71 await createPolicy('Admins can manage blog posts', 'blog_posts', 'ALL', 'is_admin(auth.uid())');
72 await createPolicy('Admins can manage categories', 'categories', 'ALL', 'is_admin(auth.uid())');
73 await createPolicy('Admins can manage tools', 'tools', 'ALL', 'is_admin(auth.uid())');
74 await createPolicy('Admins can manage reviews', 'reviews', 'ALL', 'is_admin(auth.uid())');
75 await createPolicy('Admins can manage news', 'news', 'ALL', 'is_admin(auth.uid())');
76 await createPolicy('Admins can manage learning resources', 'learning_resources', 'ALL', 'is_admin(auth.uid())');
77
78 console.log('Successfully applied all policy fixes');
79 console.log('Please restart your application for the changes to take effect.');
80 return true;
81 } catch (error) {
82 console.error('Error applying policy fixes:', error);
83 return false;
84 }
85}
86
87// Helper function to drop a policy
88async function dropPolicy(policyName: string, tableName: string) {
89 try {
90 console.log(`Dropping policy "${policyName}" on table "${tableName}"...`);
91
92 const { data, error } = await supabase.rpc('drop_policy', {
93 policy_name: policyName,
94 table_name: tableName
95 });
96
97 if (error) {
98 console.log(`Error dropping policy "${policyName}" (it may not exist):`, error);
99 // Continue regardless, as the policy may not exist
100 return false;
101 }
102
103 console.log(`Successfully dropped policy "${policyName}" on "${tableName}"`);
104 return true;
105 } catch (error) {
106 console.log(`Error dropping policy "${policyName}" (continuing anyway):`, error);
107 return false;
108 }
109}
110
111// Helper function to create a policy
112async function createPolicy(policyName: string, tableName: string, operation: string, using: string) {
113 try {
114 console.log(`Creating policy "${policyName}" on table "${tableName}"...`);
115
116 const { data, error } = await supabase.rpc('create_policy', {
117 policy_name: policyName,
118 table_name: tableName,
119 operation: operation,
120 using_expression: using
121 });
122
123 if (error) {
124 console.log(`Error creating policy "${policyName}":`, error);
125
126 // We might need to create this directly via the Management API
127 // This would require additional authentication and setup
128 // For now, we'll continue and note that manual intervention may be needed
129 console.log(`Policy "${policyName}" on "${tableName}" may need to be created manually.`);
130 return false;
131 }
132
133 console.log(`Successfully created policy "${policyName}" on "${tableName}"`);
134 return true;
135 } catch (error) {
136 console.log(`Error creating policy "${policyName}":`, error);
137 return false;
138 }
139}
140
141// Function to create the is_admin function if the RPC call fails
142async function createAdminFunction() {
143 console.log('Creating is_admin function directly...');
144
145 // Define the function SQL
146 const functionSQL = `
147 CREATE OR REPLACE FUNCTION is_admin(user_id uuid)
148 RETURNS boolean AS $$
149 DECLARE
150 admin_status boolean;
151 BEGIN
152 -- Direct query without using policies
153 SELECT is_admin INTO admin_status FROM public.users WHERE id = user_id;
154 RETURN COALESCE(admin_status, false);
155 END;
156 $$ LANGUAGE plpgsql SECURITY DEFINER;
157 `;
158
159 // We need to use the Supabase Management API to execute this SQL
160 // This would require additional setup and authentication
161 console.log('Note: The is_admin function may need to be created manually using the following SQL:');
162 console.log(functionSQL);
163
164 return false;
165}
166
167// Main function
168async function main() {
169 console.log('Starting direct fix for recursive policies...');
170
171 // First, check if we have the necessary RPC functions
172 console.log('Checking for RPC functions...');
173
174 let missingFunctions = false;
175
176 // Check for drop_policy function
177 try {
178 const { error: dropPolicyError } = await supabase.rpc('drop_policy', {
179 policy_name: 'test',
180 table_name: 'test'
181 });
182
183 if (dropPolicyError && !dropPolicyError.message.includes('Could not find the function')) {
184 console.log('drop_policy function exists but returned an error (this is expected for a test call)');
185 } else if (dropPolicyError && dropPolicyError.message.includes('Could not find the function')) {
186 console.log('drop_policy function does not exist');
187 missingFunctions = true;
188 }
189 } catch (error) {
190 console.log('Error checking drop_policy function:', error);
191 missingFunctions = true;
192 }
193
194 // Check for create_policy function
195 try {
196 const { error: createPolicyError } = await supabase.rpc('create_policy', {
197 policy_name: 'test',
198 table_name: 'test',
199 operation: 'SELECT',
200 using_expression: 'true'
201 });
202
203 if (createPolicyError && !createPolicyError.message.includes('Could not find the function')) {
204 console.log('create_policy function exists but returned an error (this is expected for a test call)');
205 } else if (createPolicyError && createPolicyError.message.includes('Could not find the function')) {
206 console.log('create_policy function does not exist');
207 missingFunctions = true;
208 }
209 } catch (error) {
210 console.log('Error checking create_policy function:', error);
211 missingFunctions = true;
212 }
213
214 if (missingFunctions) {
215 console.log('Required RPC functions are missing.');
216 console.log('Manual intervention may be required to fix the recursive policies.');
217 console.log('Please create the following SQL functions in your Supabase instance:');
218
219 console.log(`
220 -- Function to drop a policy
221 CREATE OR REPLACE FUNCTION drop_policy(policy_name text, table_name text)
222 RETURNS boolean AS $$
223 BEGIN
224 EXECUTE format('DROP POLICY IF EXISTS "%s" ON public.%I', policy_name, table_name);
225 RETURN true;
226 EXCEPTION WHEN OTHERS THEN
227 RETURN false;
228 END;
229 $$ LANGUAGE plpgsql SECURITY DEFINER;
230
231 -- Function to create a policy
232 CREATE OR REPLACE FUNCTION create_policy(policy_name text, table_name text, operation text, using_expression text)
233 RETURNS boolean AS $$
234 BEGIN
235 EXECUTE format('CREATE POLICY "%s" ON public.%I FOR %s USING (%s)',
236 policy_name, table_name, operation, using_expression);
237 RETURN true;
238 EXCEPTION WHEN OTHERS THEN
239 RETURN false;
240 END;
241 $$ LANGUAGE plpgsql SECURITY DEFINER;
242
243 -- Function to check if a user is an admin
244 CREATE OR REPLACE FUNCTION is_admin(user_id uuid)
245 RETURNS boolean AS $$
246 DECLARE
247 admin_status boolean;
248 BEGIN
249 -- Direct query without using policies
250 SELECT is_admin INTO admin_status FROM public.users WHERE id = user_id;
251 RETURN COALESCE(admin_status, false);
252 END;
253 $$ LANGUAGE plpgsql SECURITY DEFINER;
254 `);
255
256 console.log('After creating these functions, run this script again.');
257 process.exit(1);
258 }
259
260 // Apply the policy fixes
261 const success = await applyPolicyFixes();
262
263 if (!success) {
264 console.error('Failed to apply policy fixes.');
265 console.error('You may need to manually apply the fixes using the SQL in fix-recursive-policies.sql');
266 process.exit(1);
267 }
268}
269
270main();