-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsupabase_setup.sql
More file actions
287 lines (242 loc) · 10.3 KB
/
Copy pathsupabase_setup.sql
File metadata and controls
287 lines (242 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
-- ====================================================================
-- MapMyTree - Supabase Database Setup Script
-- Run this in your Supabase project's SQL Editor (https://supabase.com)
-- ====================================================================
-- 1. Create profiles table if it does not exist at all
CREATE TABLE IF NOT EXISTS public.profiles (
id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
email VARCHAR(255) NOT NULL
);
-- Ensure all required columns exist on the profiles table (for pre-existing tables)
ALTER TABLE public.profiles ADD COLUMN IF NOT EXISTS email VARCHAR(255);
ALTER TABLE public.profiles ADD COLUMN IF NOT EXISTS role VARCHAR(50) DEFAULT 'normal_user';
ALTER TABLE public.profiles ADD COLUMN IF NOT EXISTS full_name VARCHAR(255);
ALTER TABLE public.profiles ADD COLUMN IF NOT EXISTS phone_number VARCHAR(50);
ALTER TABLE public.profiles ADD COLUMN IF NOT EXISTS avatar_url TEXT;
ALTER TABLE public.profiles ADD COLUMN IF NOT EXISTS is_verified BOOLEAN DEFAULT TRUE;
ALTER TABLE public.profiles ADD COLUMN IF NOT EXISTS is_active BOOLEAN DEFAULT TRUE;
ALTER TABLE public.profiles ADD COLUMN IF NOT EXISTS created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW();
-- Drop pre-existing constraints that restrict roles so ngo_admin can be assigned
ALTER TABLE public.profiles DROP CONSTRAINT IF EXISTS profiles_role_check;
ALTER TABLE public.profiles DROP CONSTRAINT IF EXISTS role_check;
-- 2. Configure Row Level Security (RLS) policies
ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "Allow public read" ON public.profiles;
DROP POLICY IF EXISTS "Allow individual insert" ON public.profiles;
DROP POLICY IF EXISTS "Allow individual update" ON public.profiles;
CREATE POLICY "Allow public read" ON public.profiles
FOR SELECT USING (true);
CREATE POLICY "Allow individual insert" ON public.profiles
FOR INSERT WITH CHECK (auth.uid() = id);
CREATE POLICY "Allow individual update" ON public.profiles
FOR UPDATE USING (auth.uid() = id);
-- 3. Create database trigger function to auto-create profile row on signup
CREATE TABLE IF NOT EXISTS public.pre_approved_emails (
email VARCHAR(255) PRIMARY KEY,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Enable RLS on pre_approved_emails
ALTER TABLE public.pre_approved_emails ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Allow admin to select pre_approved_emails" ON public.pre_approved_emails
FOR SELECT USING (
EXISTS (
SELECT 1 FROM public.profiles
WHERE id = auth.uid() AND role = 'ngo_admin'
)
);
CREATE POLICY "Allow admin to insert pre_approved_emails" ON public.pre_approved_emails
FOR INSERT WITH CHECK (
EXISTS (
SELECT 1 FROM public.profiles
WHERE id = auth.uid() AND role = 'ngo_admin'
)
);
CREATE POLICY "Allow admin to delete pre_approved_emails" ON public.pre_approved_emails
FOR DELETE USING (
EXISTS (
SELECT 1 FROM public.profiles
WHERE id = auth.uid() AND role = 'ngo_admin'
)
);
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS TRIGGER AS $$
DECLARE
default_role VARCHAR(50);
is_pre_approved BOOLEAN;
BEGIN
-- Auto-assign role to admin@gmail.com
IF NEW.email = 'admin@gmail.com' THEN
default_role := 'ngo_admin';
ELSE
-- Fallback to the role passed from Flutter signup metadata
default_role := COALESCE(NEW.raw_user_meta_data->>'role', 'normal_user');
END IF;
-- Check if email is pre-approved for NGO volunteer
IF default_role = 'ngo_volunteer' THEN
SELECT EXISTS (
SELECT 1 FROM public.pre_approved_emails
WHERE LOWER(email) = LOWER(NEW.email)
) INTO is_pre_approved;
ELSE
is_pre_approved := false;
END IF;
INSERT INTO public.profiles (id, email, role, full_name, phone_number, is_verified, is_active)
VALUES (
NEW.id,
NEW.email,
default_role,
COALESCE(NEW.raw_user_meta_data->>'name', NEW.raw_user_meta_data->>'full_name'),
COALESCE(NEW.raw_user_meta_data->>'phone', NEW.raw_user_meta_data->>'contact_phone'),
CASE
WHEN default_role = 'ngo_volunteer' THEN is_pre_approved
ELSE true
END,
true
)
ON CONFLICT (id) DO UPDATE
SET
email = EXCLUDED.email,
role = CASE WHEN EXCLUDED.email = 'admin@gmail.com' THEN 'ngo_admin' ELSE EXCLUDED.role END;
-- Clean up pre-approved email if it was used
IF is_pre_approved THEN
DELETE FROM public.pre_approved_emails WHERE LOWER(email) = LOWER(NEW.email);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- 4. Re-bind the trigger to execute on auth.users inserts
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 PROCEDURE public.handle_new_user();
-- 5. Force update/insert for existing users (including admin@gmail.com) if already registered
INSERT INTO public.profiles (id, email, role, full_name, is_verified)
SELECT id, email, 'ngo_admin', 'NGO Admin', true
FROM auth.users
WHERE email = 'admin@gmail.com'
ON CONFLICT (id) DO UPDATE
SET role = 'ngo_admin', is_verified = true;
-- 6. Define secure client RPC function to delete own user account cleanly
-- Bypasses the need for database level foreign keys by cleaning up records first
CREATE OR REPLACE FUNCTION public.delete_current_user()
RETURNS VOID AS $$
DECLARE
current_user_id UUID;
BEGIN
current_user_id := auth.uid();
-- Delete user's sponsorship requests
DELETE FROM public.sponsorship_requests WHERE user_id = current_user_id;
-- Nullify user's planted trees (handles text/uuid comparison safely)
UPDATE public.trees SET planted_by = NULL WHERE planted_by = current_user_id::text;
-- Delete user profile
DELETE FROM public.profiles WHERE id = current_user_id;
-- Delete user login
DELETE FROM auth.users WHERE id = current_user_id;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- 7. Add RLS policy for ngo_admin to update profiles (approval/activation)
CREATE POLICY "Allow admins to update all profiles" ON public.profiles
FOR UPDATE USING (
EXISTS (
SELECT 1 FROM public.profiles
WHERE id = auth.uid() AND role = 'ngo_admin'
)
);
-- 8. Storage bucket setup
INSERT INTO storage.buckets (id, name, public)
VALUES ('tree-photos', 'tree-photos', true)
ON CONFLICT (id) DO NOTHING;
CREATE POLICY "Allow public read access to tree-photos" ON storage.objects
FOR SELECT USING (bucket_id = 'tree-photos');
CREATE POLICY "Allow authenticated inserts to tree-photos" ON storage.objects
FOR INSERT WITH CHECK (
bucket_id = 'tree-photos' AND auth.role() = 'authenticated'
);
CREATE POLICY "Allow authenticated updates to tree-photos" ON storage.objects
FOR UPDATE USING (
bucket_id = 'tree-photos' AND auth.role() = 'authenticated'
);
CREATE POLICY "Allow authenticated deletes to tree-photos" ON storage.objects
FOR DELETE USING (
bucket_id = 'tree-photos' AND auth.role() = 'authenticated'
);
-- 9. Add secure RPC function to update volunteer profiles (bypassing direct profile update RLS checks)
CREATE OR REPLACE FUNCTION public.admin_update_volunteer(volunteer_id UUID, verify BOOLEAN, active BOOLEAN)
RETURNS VOID AS $$
BEGIN
-- Verify that the caller is indeed an ngo_admin
IF EXISTS (
SELECT 1 FROM public.profiles
WHERE id = auth.uid() AND role = 'ngo_admin'
) THEN
UPDATE public.profiles
SET is_verified = verify, is_active = active
WHERE id = volunteer_id;
ELSE
RAISE EXCEPTION 'Access Denied: Only NGO Admins can manage volunteer accounts.';
END IF;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- ====================================================================
-- 10. RLS Policies for 'requests' table
-- Without these, NGO users cannot update request status (silently blocked)
-- ====================================================================
-- Enable RLS on requests table
ALTER TABLE public.requests ENABLE ROW LEVEL SECURITY;
-- Allow authenticated users to INSERT their own requests
DROP POLICY IF EXISTS "Allow users to insert own requests" ON public.requests;
CREATE POLICY "Allow users to insert own requests" ON public.requests
FOR INSERT WITH CHECK (auth.uid() = user_id);
-- Allow users to read their own requests
DROP POLICY IF EXISTS "Allow users to read own requests" ON public.requests;
CREATE POLICY "Allow users to read own requests" ON public.requests
FOR SELECT USING (auth.uid() = user_id);
-- Allow NGO admins and volunteers to read ALL requests
DROP POLICY IF EXISTS "Allow NGO to read all requests" ON public.requests;
CREATE POLICY "Allow NGO to read all requests" ON public.requests
FOR SELECT USING (
EXISTS (
SELECT 1 FROM public.profiles
WHERE id = auth.uid() AND role IN ('ngo_admin', 'ngo_volunteer')
)
);
-- Allow NGO admins and volunteers to UPDATE any request (e.g., mark completed)
DROP POLICY IF EXISTS "Allow NGO to update requests" ON public.requests;
CREATE POLICY "Allow NGO to update requests" ON public.requests
FOR UPDATE USING (
EXISTS (
SELECT 1 FROM public.profiles
WHERE id = auth.uid() AND role IN ('ngo_admin', 'ngo_volunteer')
)
);
-- Allow users to update their OWN request (e.g., upload payment)
DROP POLICY IF EXISTS "Allow users to update own requests" ON public.requests;
CREATE POLICY "Allow users to update own requests" ON public.requests
FOR UPDATE USING (auth.uid() = user_id);
-- ====================================================================
-- 11. RLS Policies for 'trees' table
-- ====================================================================
-- Enable RLS on trees table
ALTER TABLE public.trees ENABLE ROW LEVEL SECURITY;
-- Allow public read of all trees (for QR scan page etc)
DROP POLICY IF EXISTS "Allow public read of trees" ON public.trees;
CREATE POLICY "Allow public read of trees" ON public.trees
FOR SELECT USING (true);
-- Allow NGO volunteers/admins to INSERT trees
DROP POLICY IF EXISTS "Allow NGO to insert trees" ON public.trees;
CREATE POLICY "Allow NGO to insert trees" ON public.trees
FOR INSERT WITH CHECK (
EXISTS (
SELECT 1 FROM public.profiles
WHERE id = auth.uid() AND role IN ('ngo_admin', 'ngo_volunteer')
)
);
-- Allow NGO volunteers/admins to UPDATE trees
DROP POLICY IF EXISTS "Allow NGO to update trees" ON public.trees;
CREATE POLICY "Allow NGO to update trees" ON public.trees
FOR UPDATE USING (
EXISTS (
SELECT 1 FROM public.profiles
WHERE id = auth.uid() AND role IN ('ngo_admin', 'ngo_volunteer')
)
);