Branchwell

AI Resource Pro / website / scripts / fix-recursive-policies.sql

1-- Script to fix recursive policies in Supabase
2-- Open Supabase Dashboard > SQL Editor and execute this script
3-- This will fix the "infinite recursion detected in policy for relation 'users'" error
4
5-- First, drop the problematic policies that cause recursion
6DROP POLICY IF EXISTS "Admins can view all users" ON public.users;
7DROP POLICY IF EXISTS "Admins can update users" ON public.users;
8
9-- Create new policies that avoid recursion by using a different approach
10-- Instead of querying the users table within its own policy, we'll use a direct check
11
12-- Create a function to check if a user is an admin
13CREATE OR REPLACE FUNCTION is_admin(user_id uuid)
14RETURNS boolean AS $$
15DECLARE
16 admin_status boolean;
17BEGIN
18 -- Direct query without using policies
19 SELECT is_admin INTO admin_status FROM public.users WHERE id = user_id;
20 RETURN COALESCE(admin_status, false);
21END;
22$$ LANGUAGE plpgsql SECURITY DEFINER;
23
24-- Create new policies using the function
25CREATE POLICY "Admins can view all users" ON public.users
26 FOR SELECT USING (
27 is_admin(auth.uid())
28 );
29
30CREATE POLICY "Admins can update users" ON public.users
31 FOR UPDATE USING (
32 is_admin(auth.uid())
33 );
34
35-- Fix other policies that might have the same issue
36DROP POLICY IF EXISTS "Admins can manage blog posts" ON public.blog_posts;
37DROP POLICY IF EXISTS "Admins can manage categories" ON public.categories;
38DROP POLICY IF EXISTS "Admins can manage tools" ON public.tools;
39DROP POLICY IF EXISTS "Admins can manage reviews" ON public.reviews;
40DROP POLICY IF EXISTS "Admins can manage news" ON public.news;
41DROP POLICY IF EXISTS "Admins can manage learning resources" ON public.learning_resources;
42
43-- Recreate them using the function
44CREATE POLICY "Admins can manage blog posts" ON public.blog_posts
45 FOR ALL USING (
46 is_admin(auth.uid())
47 );
48
49CREATE POLICY "Admins can manage categories" ON public.categories
50 FOR ALL USING (
51 is_admin(auth.uid())
52 );
53
54CREATE POLICY "Admins can manage tools" ON public.tools
55 FOR ALL USING (
56 is_admin(auth.uid())
57 );
58
59CREATE POLICY "Admins can manage reviews" ON public.reviews
60 FOR ALL USING (
61 is_admin(auth.uid())
62 );
63
64CREATE POLICY "Admins can manage news" ON public.news
65 FOR ALL USING (
66 is_admin(auth.uid())
67 );
68
69CREATE POLICY "Admins can manage learning resources" ON public.learning_resources
70 FOR ALL USING (
71 is_admin(auth.uid())
72 );