-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsupabase_schema.sql
More file actions
78 lines (68 loc) · 2.49 KB
/
Copy pathsupabase_schema.sql
File metadata and controls
78 lines (68 loc) · 2.49 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
-- Enable UUID extension
create extension if not exists "pgcrypto";
-- ROLES
create table if not exists public.roles (
user_id uuid primary key references auth.users(id) on delete cascade,
role text not null check (role in ('admin', 'user')) default 'user',
created_at timestamptz default now()
);
alter table public.roles enable row level security;
-- PROFILES
create table if not exists public.profiles (
id uuid primary key references auth.users(id) on delete cascade,
prn_number text unique,
email text,
full_name text,
avatar_url text,
website text,
bio text,
updated_at timestamptz
);
alter table public.profiles enable row level security;
-- POLICIES
-- Profiles
create policy "Public profiles are viewable by everyone" on profiles for select using (true);
create policy "Users can insert their own profile" on profiles for insert with check (auth.uid() = id);
create policy "Users can update own profile" on profiles for update using (auth.uid() = id);
create policy "Admins can update any profile" on profiles for update using (
exists (select 1 from roles where user_id = auth.uid() and role = 'admin')
);
create policy "Admins can delete any profile" on profiles for delete using (
exists (select 1 from roles where user_id = auth.uid() and role = 'admin')
);
-- Roles
create policy "Roles viewable by everyone" on roles for select using (true);
create policy "Admins can insert roles" on roles for insert with check (
exists (select 1 from roles where user_id = auth.uid() and role = 'admin')
);
create policy "Admins can update roles" on roles for update using (
exists (select 1 from roles where user_id = auth.uid() and role = 'admin')
);
create policy "Admins can delete roles" on roles for delete using (
exists (select 1 from roles where user_id = auth.uid() and role = 'admin')
);
-- HANDLERS
create or replace function public.handle_new_user()
returns trigger as $$
begin
insert into public.roles (user_id, role)
values (new.id, 'user');
insert into public.profiles (id, full_name, avatar_url, prn_number, email)
values (
new.id,
new.raw_user_meta_data->>'full_name',
new.raw_user_meta_data->>'avatar_url',
new.raw_user_meta_data->>'prn_number',
new.email
);
return new;
exception
when others then
return new;
end;
$$ language plpgsql security definer;
-- Trigger
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();