-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFIX_PROFILES.sql
More file actions
49 lines (43 loc) · 1.55 KB
/
FIX_PROFILES.sql
File metadata and controls
49 lines (43 loc) · 1.55 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
-- 1. Add phone column if it doesn't exist
ALTER TABLE public.profiles
ADD COLUMN IF NOT EXISTS phone text;
-- 2. Create a function to handle new user signup automatically
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS trigger AS $$
BEGIN
INSERT INTO public.profiles (id, full_name, avatar_url, phone)
VALUES (
new.id,
new.raw_user_meta_data->>'full_name',
new.raw_user_meta_data->>'avatar_url',
new.phone
);
RETURN new;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- 3. Create the trigger (fires after every auth.users insert)
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();
-- 4. Backfill existing users who might be missing a profile
INSERT INTO public.profiles (id, phone, full_name)
SELECT
id,
phone,
raw_user_meta_data->>'full_name'
FROM auth.users
WHERE id NOT IN (SELECT id FROM public.profiles)
ON CONFLICT (id) DO NOTHING;
-- 5. Enable RLS (just in case)
ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;
-- 6. Policy to let users update their own profile
DROP POLICY IF EXISTS "Users can update own profile" ON public.profiles;
CREATE POLICY "Users can update own profile"
ON public.profiles FOR UPDATE
USING (auth.uid() = id);
-- 7. Policy to let everyone read profiles (needed for neighbors to see names)
DROP POLICY IF EXISTS "Profiles are viewable by everyone" ON public.profiles;
CREATE POLICY "Profiles are viewable by everyone"
ON public.profiles FOR SELECT
USING (true);