Branchwell

AI Resource Pro / website / supabase / migrations / 20261030000000_users_and_saved_tutorials.sql

1-- Fresh schema for the redesigned site: user profiles and saved tutorials.
2-- Tutorials themselves live as MDX files in the repo, keyed by slug.
3
4-- ── users ──────────────────────────────────────────────────
5CREATE TABLE IF NOT EXISTS public.users (
6 id uuid PRIMARY KEY REFERENCES auth.users (id) ON DELETE CASCADE,
7 email text,
8 full_name text,
9 avatar_url text,
10 is_admin boolean NOT NULL DEFAULT false,
11 marketing_consent boolean NOT NULL DEFAULT false,
12 marketing_consent_at timestamptz,
13 created_at timestamptz NOT NULL DEFAULT now(),
14 updated_at timestamptz NOT NULL DEFAULT now()
15);
16
17ALTER TABLE public.users ENABLE ROW LEVEL SECURITY;
18
19CREATE POLICY "users_select_own"
20 ON public.users FOR SELECT
21 USING ((select auth.uid()) = id);
22
23CREATE POLICY "users_insert_own"
24 ON public.users FOR INSERT
25 WITH CHECK ((select auth.uid()) = id AND is_admin = false);
26
27CREATE POLICY "users_update_own"
28 ON public.users FOR UPDATE
29 USING ((select auth.uid()) = id)
30 WITH CHECK ((select auth.uid()) = id);
31
32-- Signed-in users can edit their own row but never change is_admin
33CREATE OR REPLACE FUNCTION public.protect_is_admin()
34RETURNS trigger
35LANGUAGE plpgsql
36SET search_path = ''
37AS $$
38BEGIN
39 IF current_user IN ('anon', 'authenticated') THEN
40 NEW.is_admin := OLD.is_admin;
41 END IF;
42 RETURN NEW;
43END;
44$$;
45
46CREATE TRIGGER users_protect_is_admin
47 BEFORE UPDATE ON public.users
48 FOR EACH ROW EXECUTE FUNCTION public.protect_is_admin();
49
50-- Create a profile row whenever someone signs up (email, Google or Apple)
51CREATE OR REPLACE FUNCTION public.handle_new_user()
52RETURNS trigger
53LANGUAGE plpgsql
54SECURITY DEFINER
55SET search_path = ''
56AS $$
57BEGIN
58 INSERT INTO public.users (id, email, full_name, avatar_url)
59 VALUES (
60 NEW.id,
61 NEW.email,
62 COALESCE(NEW.raw_user_meta_data ->> 'full_name', NEW.raw_user_meta_data ->> 'name'),
63 NEW.raw_user_meta_data ->> 'avatar_url'
64 )
65 ON CONFLICT (id) DO NOTHING;
66 RETURN NEW;
67END;
68$$;
69
70CREATE TRIGGER on_auth_user_created
71 AFTER INSERT ON auth.users
72 FOR EACH ROW EXECUTE FUNCTION public.handle_new_user();
73
74-- ── saved_tutorials ────────────────────────────────────────
75CREATE TABLE IF NOT EXISTS public.saved_tutorials (
76 user_id uuid NOT NULL REFERENCES public.users (id) ON DELETE CASCADE,
77 tutorial_slug text NOT NULL,
78 completed_at timestamptz,
79 created_at timestamptz NOT NULL DEFAULT now(),
80 PRIMARY KEY (user_id, tutorial_slug)
81);
82
83ALTER TABLE public.saved_tutorials ENABLE ROW LEVEL SECURITY;
84
85CREATE POLICY "saved_tutorials_own"
86 ON public.saved_tutorials FOR ALL
87 USING ((select auth.uid()) = user_id)
88 WITH CHECK ((select auth.uid()) = user_id);