begin; create table if not exists public.academy_enrollments ( email text primary key check (email = lower(btrim(email)) and length(email) between 3 and 254), active boolean not null default true, expires_at timestamptz, created_at timestamptz not null default now(), updated_at timestamptz not null default now() ); alter table public.academy_enrollments enable row level security; revoke all on public.academy_enrollments from public, anon, authenticated; grant select, insert, update on public.academy_enrollments to authenticated; drop policy if exists academy_owner_enrollments_read on public.academy_enrollments; create policy academy_owner_enrollments_read on public.academy_enrollments for select to authenticated using ((select auth.uid()) = '7e0f0df7-cc38-4c4d-a7e0-1efcd448081b'::uuid); drop policy if exists academy_owner_enrollments_insert on public.academy_enrollments; create policy academy_owner_enrollments_insert on public.academy_enrollments for insert to authenticated with check ((select auth.uid()) = '7e0f0df7-cc38-4c4d-a7e0-1efcd448081b'::uuid); drop policy if exists academy_owner_enrollments_update on public.academy_enrollments; create policy academy_owner_enrollments_update on public.academy_enrollments for update to authenticated using ((select auth.uid()) = '7e0f0df7-cc38-4c4d-a7e0-1efcd448081b'::uuid) with check ((select auth.uid()) = '7e0f0df7-cc38-4c4d-a7e0-1efcd448081b'::uuid); create or replace function public.academy_has_access() returns boolean language sql stable security definer set search_path = '' as $$ select coalesce((select auth.uid()) = '7e0f0df7-cc38-4c4d-a7e0-1efcd448081b'::uuid, false) or exists ( select 1 from auth.users as u join public.academy_enrollments as e on e.email = lower(u.email) where u.id = (select auth.uid()) and u.email_confirmed_at is not null and e.active and (e.expires_at is null or e.expires_at > now()) ); $$; revoke all on function public.academy_has_access() from public, anon, authenticated; grant execute on function public.academy_has_access() to anon, authenticated; drop policy if exists academy_read on public.academy_content; drop policy if exists academy_public_site on public.academy_content; create policy academy_public_site on public.academy_content for select to anon, authenticated using (key = 'site'); drop policy if exists academy_members_read on public.academy_content; create policy academy_members_read on public.academy_content for select to authenticated using ((select public.academy_has_access())); drop policy if exists academy_read_boundary on public.academy_content; create policy academy_read_boundary on public.academy_content as restrictive for select to anon, authenticated using (key = 'site' or (select public.academy_has_access())); commit;