1+ -- Fix security vulnerability: Allow affiliates to access their own data
2+ -- This addresses the issue where affiliates couldn't see their own profile information
3+
4+ -- Add policy to allow affiliates to view their own data
5+ CREATE POLICY " Affiliates can view their own data"
6+ ON public .affiliates
7+ FOR SELECT
8+ USING (auth .uid () = user_id);
9+
10+ -- Add policy to allow affiliates to update their own data (except sensitive fields)
11+ CREATE POLICY " Affiliates can update their own profile"
12+ ON public .affiliates
13+ FOR UPDATE
14+ USING (auth .uid () = user_id)
15+ WITH CHECK (
16+ auth .uid () = user_id
17+ AND OLD .campaign_id = NEW .campaign_id -- Prevent changing campaign
18+ AND OLD .tracking_code = NEW .tracking_code -- Prevent changing tracking code
19+ AND OLD .commission_rate = NEW .commission_rate -- Prevent changing commission rate
20+ );
21+
22+ -- Add security function to validate affiliate data access
23+ CREATE OR REPLACE FUNCTION public .validate_affiliate_data_access(affiliate_id uuid, requesting_user_id uuid DEFAULT auth .uid ())
24+ RETURNS boolean
25+ LANGUAGE plpgsql
26+ SECURITY DEFINER
27+ SET search_path TO ' public'
28+ AS $function$
29+ DECLARE
30+ affiliate_user_id uuid;
31+ campaign_owner_id uuid;
32+ BEGIN
33+ -- Get affiliate user_id and campaign owner
34+ SELECT a .user_id , c .user_id INTO affiliate_user_id, campaign_owner_id
35+ FROM affiliates a
36+ JOIN campaigns c ON c .id = a .campaign_id
37+ WHERE a .id = affiliate_id;
38+
39+ -- Allow access if user is the affiliate or campaign owner
40+ RETURN (requesting_user_id = affiliate_user_id OR requesting_user_id = campaign_owner_id);
41+ END;
42+ $function$;
43+
44+ -- Log security event for affiliate data access
45+ CREATE OR REPLACE FUNCTION public .log_affiliate_data_access(affiliate_id uuid, access_type text )
46+ RETURNS void
47+ LANGUAGE plpgsql
48+ SECURITY DEFINER
49+ SET search_path TO ' public'
50+ AS $function$
51+ BEGIN
52+ PERFORM public .log_security_event (
53+ ' affiliate_data_access' ,
54+ auth .uid (),
55+ jsonb_build_object(
56+ ' affiliate_id' , affiliate_id,
57+ ' access_type' , access_type,
58+ ' timestamp' , now()
59+ )
60+ );
61+ END;
62+ $function$;
0 commit comments