-- Fix: SQL per creare le tabelle e policies (gestisce policy giĆ  esistenti) -- 1. Crea tabella profili (se non esiste) CREATE TABLE IF NOT EXISTS public.profiles ( id uuid PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE, email text NOT NULL, full_name text, avatar_url text, role text DEFAULT 'user' CHECK (role IN ('admin', 'user')), created_at timestamp with time zone DEFAULT timezone('utc'::text, now()), updated_at timestamp with time zone DEFAULT timezone('utc'::text, now()) ); -- 2. Abilita RLS ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY; -- 3. Elimina policies esistenti (per evitare conflitti) DROP POLICY IF EXISTS "Public profiles are viewable by everyone" ON public.profiles; DROP POLICY IF EXISTS "Users can insert their own profile" ON public.profiles; DROP POLICY IF EXISTS "Users can update own profile" ON public.profiles; -- 4. Ricrea policies CREATE POLICY "Public profiles are viewable by everyone" ON public.profiles FOR SELECT USING (true); CREATE POLICY "Users can insert their own profile" ON public.profiles FOR INSERT WITH CHECK (auth.uid() = id); CREATE POLICY "Users can update own profile" ON public.profiles FOR UPDATE USING (auth.uid() = id); -- 5. Funzione per auto-creare profilo CREATE OR REPLACE FUNCTION public.handle_new_user() RETURNS trigger AS $$ BEGIN INSERT INTO public.profiles (id, email, full_name, role) VALUES ( NEW.id, NEW.email, NEW.raw_user_meta_data->>'full_name', COALESCE(NEW.raw_user_meta_data->>'role', 'user') ); RETURN NEW; END; $$ LANGUAGE plpgsql SECURITY DEFINER; -- 6. Trigger DROP TRIGGER IF EXISTS on_auth_user_created ON auth.users; CREATE TRIGGER on_auth_user_created AFTER INSERT ON auth.users FOR EACH ROW EXECUTE FUNCTION public.handle_new_user(); -- 7. Verifica: mostra struttura tabella SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'profiles' AND table_schema = 'public';