-
Notifications
You must be signed in to change notification settings - Fork 18
/
supabase_rbac--3.0.0.sql
324 lines (278 loc) · 10.2 KB
/
supabase_rbac--3.0.0.sql
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
create table
"groups" (
"id" uuid not null default gen_random_uuid (),
"metadata" jsonb not null default '{}'::jsonb,
"created_at" timestamp with time zone not null default now(),
"updated_at" timestamp with time zone not null default now()
);
create table
"group_users" (
"id" uuid not null default gen_random_uuid (),
"group_id" uuid not null,
"user_id" uuid not null,
"role" text not null default ''::text,
"metadata" jsonb not null default '{}'::jsonb,
"created_at" timestamp with time zone not null default now(),
"updated_at" timestamp with time zone not null default now()
);
create table
"group_invites" (
"id" uuid not null default gen_random_uuid (),
"group_id" uuid not null,
"roles" text[] not null default '{}'::text[] check (cardinality(roles) > 0),
"invited_by" uuid not null,
"created_at" timestamp with time zone not null default now(),
"user_id" uuid,
"accepted_at" timestamp with time zone
);
CREATE UNIQUE INDEX group_pkey ON "groups" USING btree (id);
CREATE UNIQUE INDEX group_users_group_id_idx ON group_users USING btree (group_id, user_id, role);
CREATE UNIQUE INDEX group_users_pkey ON group_users USING btree (id);
CREATE UNIQUE INDEX group_invites_pkey ON group_invites USING btree (id);
alter table "groups"
add constraint "group_pkey" PRIMARY KEY using index "group_pkey";
alter table "group_users"
add constraint "group_users_pkey" PRIMARY KEY using index "group_users_pkey";
alter table "group_users"
add constraint "group_users_group_id_fkey" FOREIGN KEY (group_id) REFERENCES "groups" (id) not valid;
alter table "group_users" validate constraint "group_users_group_id_fkey";
alter table "group_users"
add constraint "group_users_user_id_fkey" FOREIGN KEY (user_id) REFERENCES auth.users (id) not valid;
alter table "group_users" validate constraint "group_users_user_id_fkey";
alter table "group_invites"
add constraint "group_invites_pkey" PRIMARY KEY using index "group_invites_pkey";
alter table "group_invites"
add constraint "group_invites_invited_by_fkey" FOREIGN KEY ("invited_by") REFERENCES auth.users (id) not valid;
alter table "group_invites" validate constraint "group_invites_invited_by_fkey";
alter table "group_invites"
add constraint "group_invites_group_id_fkey" FOREIGN KEY ("group_id") REFERENCES groups (id) not valid;
alter table "group_invites" validate constraint "group_invites_group_id_fkey";
alter table "group_invites"
add constraint "group_invites_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES auth.users (id) not valid;
alter table "group_invites" validate constraint "group_invites_user_id_fkey";
alter table "group_invites" enable row level security;
create or replace view
@extschema@."user_roles"
WITH
(security_invoker) as
SELECT
gu.id,
COALESCE((g.metadata ->> 'name'::text), NULL::text) AS group_name,
gu.role,
COALESCE((gu.metadata ->> 'email'::text), NULL::text) AS email,
gu.group_id,
gu.user_id
FROM (
group_users gu
JOIN groups g ON ((g.id = gu.group_id))
);
CREATE
OR REPLACE FUNCTION @extschema@.delete_group_users () RETURNS trigger LANGUAGE plpgsql
set
search_path = @extschema@ as $function$
BEGIN
DELETE from group_users WHERE id = OLD.id;
RETURN NULL;
END;
$function$;
create
or REPLACE FUNCTION @extschema@.db_pre_request () returns void language plpgsql stable security definer
set
search_path = @extschema@ as $function$
declare
groups jsonb;
begin
-- get current groups from auth.users
select raw_app_meta_data->'groups' from auth.users into groups where id = auth.uid();
-- store it in the request object
perform set_config('request.groups'::text, groups::text, false /* applies to transaction if true, session if false */);
end;
$function$;
create
or replace function @extschema@.get_user_claims () returns jsonb language sql stable
set
search_path = @extschema@ as $function$
select coalesce(current_setting('request.groups', true)::jsonb, auth.jwt()->'app_metadata'->'groups')::jsonb
$function$;
create
or replace function @extschema@.user_has_group_role (group_id uuid, group_role text) returns boolean language plpgsql stable
set
search_path = @extschema@ as $function$
declare
auth_role text = auth.role();
retval bool;
begin
if auth_role = 'authenticated' then
if jwt_is_expired() then
raise exception 'invalid_jwt' using hint = 'jwt is expired or missing';
end if;
select coalesce(get_user_claims()->group_id::text ? group_role,
false
) into retval;
return retval;
elsif auth_role = 'anon' then
return false;
else -- not a user session, probably being called from a trigger or something
if session_user = 'postgres' then
return true;
else -- such as 'authenticator'
return false;
end if;
end if;
end;
$function$;
create
or replace function @extschema@.user_is_group_member (group_id uuid) returns boolean language plpgsql stable
set
search_path = @extschema@ as $function$
declare
auth_role text = auth.role();
retval bool;
begin
if auth_role = 'authenticated' then
if jwt_is_expired() then
raise exception 'invalid_jwt' using hint = 'jwt is expired or missing';
end if;
select coalesce(get_user_claims() ? group_id::text,
false
) into retval;
return retval;
elsif auth_role = 'anon' then
return false;
else -- not a user session, probably being called from a trigger or something
if session_user = 'postgres' then
return true;
else -- such as 'authenticator'
return false;
end if;
end if;
end;
$function$;
create
or replace function @extschema@.jwt_is_expired () returns boolean language plpgsql stable
set
search_path = @extschema@ as $function$
begin
return extract(epoch from now()) > coalesce(auth.jwt()->>'exp', '0')::numeric;
end;
$function$;
CREATE OR REPLACE FUNCTION @extschema@.update_group_users_email()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO @extschema@
AS $function$
BEGIN
-- Check if the email was changed or it is a new insertion
IF (TG_OP = 'INSERT') OR (TG_OP = 'UPDATE' AND NEW.email IS DISTINCT FROM OLD.email) THEN
-- Update the email in the metadata of group_users
UPDATE @extschema@.group_users
SET metadata = jsonb_set(metadata, '{email}', to_jsonb(NEW.email))
WHERE user_id = NEW.id;
END IF;
RETURN NEW;
END;
$function$;
CREATE OR REPLACE FUNCTION @extschema@.update_user_roles()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO @extschema@
AS $function$
DECLARE
_group_id TEXT = COALESCE(new.group_id, old.group_id)::TEXT;
_group_id_old TEXT = COALESCE(old.group_id, new.group_id)::TEXT;
_user_id UUID = COALESCE(new.user_id, old.user_id);
_user_id_old UUID = COALESCE(old.user_id, new.user_id);
_role TEXT = COALESCE(new.role, old.role);
_role_old TEXT = COALESCE(old.role, new.role);
_user_email TEXT;
_raw_app_meta_data JSONB;
BEGIN
-- Check if user_id or group_id is changed
IF _group_id IS DISTINCT FROM _group_id_old OR _user_id IS DISTINCT FROM _user_id_old THEN
RAISE EXCEPTION 'Changing user_id or group_id is not allowed';
END IF;
-- Fetch current email early to avoid multiple SELECT statements
SELECT email, raw_app_meta_data INTO _user_email, _raw_app_meta_data FROM auth.users WHERE id = _user_id;
_raw_app_meta_data = coalesce(_raw_app_meta_data, '{}'::jsonb);
-- Check if the record has been deleted or the role has been changed
IF (TG_OP = 'DELETE') OR (TG_OP = 'UPDATE' AND _role IS DISTINCT FROM _role_old) THEN
-- Remove role from raw_app_meta_data
_raw_app_meta_data = jsonb_set(
_raw_app_meta_data,
'{groups}',
jsonb_strip_nulls(
COALESCE(_raw_app_meta_data->'groups', '{}'::jsonb) ||
jsonb_build_object(
_group_id::text,
(
SELECT jsonb_agg(val)
FROM jsonb_array_elements_text(COALESCE(_raw_app_meta_data->'groups'->(_group_id::text), '[]'::jsonb)) AS vals(val)
WHERE val <> _role_old
)
)
)
);
END IF;
-- Check if the record has been inserted or the role has been changed
IF (TG_OP = 'INSERT') OR (TG_OP = 'UPDATE' AND _role IS DISTINCT FROM _role_old) THEN
-- Add role to raw_app_meta_data
_raw_app_meta_data = jsonb_set(
_raw_app_meta_data,
'{groups}',
COALESCE(_raw_app_meta_data->'groups', '{}'::jsonb) ||
jsonb_build_object(
_group_id::text,
(
SELECT jsonb_agg(DISTINCT val)
FROM (
SELECT val
FROM jsonb_array_elements_text(COALESCE(_raw_app_meta_data->'groups'->(_group_id::text), '[]'::jsonb)) AS vals(val)
UNION
SELECT _role
) AS combined_roles(val)
)
)
);
END IF;
-- Update raw_app_meta_data in auth.users
UPDATE auth.users
SET raw_app_meta_data = _raw_app_meta_data
WHERE id = _user_id;
-- Update email in metadata of the NEW record
NEW.metadata = jsonb_set(NEW.metadata, '{email}', to_jsonb(_user_email));
-- Return null (the trigger function requires a return value)
RETURN NEW;
END;
$function$;
-- Enable the db_pre_request hook for the authenticator role
ALTER ROLE authenticator
SET
pgrst.db_pre_request TO 'db_pre_request';
NOTIFY pgrst,
'reload config';
create trigger handle_updated_at before
update
on
@extschema@.groups for each row execute function moddatetime('updated_at');
create trigger handle_updated_at before
update
on
@extschema@.group_users for each row execute function moddatetime('updated_at');
CREATE TRIGGER on_change_update_user_metadata
BEFORE INSERT
OR DELETE
OR
UPDATE ON group_users FOR EACH ROW
EXECUTE FUNCTION update_user_roles ();
CREATE TRIGGER update_group_users_email
AFTER INSERT OR UPDATE
ON auth.users
FOR EACH ROW
EXECUTE FUNCTION update_group_users_email();
CREATE TRIGGER on_delete_user INSTEAD OF DELETE ON user_roles FOR EACH ROW
EXECUTE FUNCTION delete_group_users ();
alter table "group_users" enable row level security;
alter table "groups" enable row level security;
alter table "group_invites" enable row level security;