Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

Use SSO custom claims to initialize/update sales data

Gildas184f1f3ecddb
diff --git a/supabase/migrations/20260128165057_sso_handling.sql b/supabase/migrations/20260128165057_sso_handling.sql
new file mode 100644
index 00000000..d78612ee
--- /dev/null
+++ b/supabase/migrations/20260128165057_sso_handling.sql
@@ -0,0 +1,51 @@
+create extension if not exists "pgjwt" with schema "extensions";
+
+alter table "public"."sales" alter column "first_name" set default 'Pending'::text;
+
+alter table "public"."sales" alter column "last_name" set default 'Pending'::text;
+
+set check_function_bodies = off;
+
+CREATE OR REPLACE FUNCTION public.handle_new_user()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO ''
+AS $function$
+declare
+ sales_count int;
+begin
+ select count(id) into sales_count
+ from public.sales;
+
+ insert into public.sales (first_name, last_name, email, user_id, administrator)
+ values (
+ coalesce(new.raw_user_meta_data ->> 'first_name', new.raw_user_meta_data -> 'custom_claims' ->> 'first_name', 'Pending'),
+ coalesce(new.raw_user_meta_data ->> 'last_name', new.raw_user_meta_data -> 'custom_claims' ->> 'last_name', 'Pending'),
+ new.email,
+ new.id,
+ case when sales_count > 0 then FALSE else TRUE end
+ );
+ return new;
+end;
+$function$
+;
+
+CREATE OR REPLACE FUNCTION public.handle_update_user()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO ''
+AS $function$
+begin
+ update public.sales
+ set
+ first_name = coalesce(new.raw_user_meta_data ->> 'first_name', new.raw_user_meta_data -> 'custom_claims' ->> 'first_name', 'Pending'),
+ last_name = coalesce(new.raw_user_meta_data ->> 'last_name', new.raw_user_meta_data -> 'custom_claims' ->> 'last_name', 'Pending'),
+ email = new.email
+ where user_id = new.id;
+
+ return new;
+end;
+$function$
+;