-
-
Notifications
You must be signed in to change notification settings - Fork 218
/
000001.sql
2070 lines (1858 loc) · 85.3 KB
/
000001.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--! Previous: -
--! Hash: sha1:eaf2866060caa0bba319236017c15a40d37a7815
--! split: 0001-reset.sql
/*
* Graphile Migrate will run our `current/...` migrations in one batch. Since
* this is our first migration it's defining the entire database, so we first
* drop anything that may have previously been created
* (app_public/app_hidden/app_private) so that we can start from scratch.
*/
drop schema if exists app_public cascade;
drop schema if exists app_hidden cascade;
drop schema if exists app_private cascade;
--! split: 0010-public-permissions.sql
/*
* The `public` *schema* contains things like PostgreSQL extensions. We
* deliberately do not install application logic into the public schema
* (instead storing it to app_public/app_hidden/app_private as appropriate),
* but none the less we don't want untrusted roles to be able to install or
* modify things into the public schema.
*
* The `public` *role* is automatically inherited by all other roles; we only
* want specific roles to be able to access our database so we must revoke
* access to the `public` role.
*/
revoke all on schema public from public;
alter default privileges revoke all on sequences from public;
alter default privileges revoke all on functions from public;
-- Of course we want our database owner to be able to do anything inside the
-- database, so we grant access to the `public` schema:
grant all on schema public to :DATABASE_OWNER;
--! split: 0020-schemas.sql
/*
* Read about our app_public/app_hidden/app_private schemas here:
* https://www.graphile.org/postgraphile/namespaces/#advice
*
* Note this pattern is not required to use PostGraphile, it's merely the
* preference of the author of this package.
*/
create schema app_public;
create schema app_hidden;
create schema app_private;
-- The 'visitor' role (used by PostGraphile to represent an end user) may
-- access the public, app_public and app_hidden schemas (but _NOT_ the
-- app_private schema).
grant usage on schema public, app_public, app_hidden to :DATABASE_VISITOR;
-- We want the `visitor` role to be able to insert rows (`serial` data type
-- creates sequences, so we need to grant access to that).
alter default privileges in schema public, app_public, app_hidden
grant usage, select on sequences to :DATABASE_VISITOR;
-- And the `visitor` role should be able to call functions too.
alter default privileges in schema public, app_public, app_hidden
grant execute on functions to :DATABASE_VISITOR;
--! split: 0030-common-triggers.sql
/*
* These triggers are commonly used across many tables.
*/
-- Used for queueing jobs easily; relies on the fact that every table we have
-- has a primary key 'id' column; this won't work if you rename your primary
-- key columns.
create function app_private.tg__add_job() returns trigger as $$
begin
perform graphile_worker.add_job(tg_argv[0], json_build_object('id', NEW.id));
return NEW;
end;
$$ language plpgsql volatile security definer set search_path to pg_catalog, public, pg_temp;
comment on function app_private.tg__add_job() is
E'Useful shortcut to create a job on insert/update. Pass the task name as the first trigger argument, and optionally the queue name as the second argument. The record id will automatically be available on the JSON payload.';
-- This trigger is used to queue a job to inform a user that a significant
-- security change has been made to their account (e.g. adding a new email
-- address, linking a new social login).
create function app_private.tg__add_audit_job() returns trigger as $$
declare
v_user_id uuid;
v_type text = TG_ARGV[0];
v_user_id_attribute text = TG_ARGV[1];
v_extra_attribute1 text = TG_ARGV[2];
v_extra_attribute2 text = TG_ARGV[3];
v_extra_attribute3 text = TG_ARGV[4];
v_extra1 text;
v_extra2 text;
v_extra3 text;
begin
if v_user_id_attribute is null then
raise exception 'Invalid tg__add_audit_job call';
end if;
execute 'select ($1.' || quote_ident(v_user_id_attribute) || ')::uuid'
using (case when TG_OP = 'INSERT' then NEW else OLD end)
into v_user_id;
if v_extra_attribute1 is not null then
execute 'select ($1.' || quote_ident(v_extra_attribute1) || ')::text'
using (case when TG_OP = 'DELETE' then OLD else NEW end)
into v_extra1;
end if;
if v_extra_attribute2 is not null then
execute 'select ($1.' || quote_ident(v_extra_attribute2) || ')::text'
using (case when TG_OP = 'DELETE' then OLD else NEW end)
into v_extra2;
end if;
if v_extra_attribute3 is not null then
execute 'select ($1.' || quote_ident(v_extra_attribute3) || ')::text'
using (case when TG_OP = 'DELETE' then OLD else NEW end)
into v_extra3;
end if;
if v_user_id is not null then
perform graphile_worker.add_job(
'user__audit',
json_build_object(
'type', v_type,
'user_id', v_user_id,
'extra1', v_extra1,
'extra2', v_extra2,
'extra3', v_extra3,
'current_user_id', app_public.current_user_id(),
'schema', TG_TABLE_SCHEMA,
'table', TG_TABLE_NAME
));
end if;
return NEW;
end;
$$ language plpgsql volatile security definer set search_path to pg_catalog, public, pg_temp;
comment on function app_private.tg__add_audit_job() is
E'For notifying a user that an auditable action has taken place. Call with audit event name, user ID attribute name, and optionally another value to be included (e.g. the PK of the table, or some other relevant information). e.g. `tg__add_audit_job(''added_email'', ''user_id'', ''email'')`';
/*
* This trigger is used on tables with created_at and updated_at to ensure that
* these timestamps are kept valid (namely: `created_at` cannot be changed, and
* `updated_at` must be monotonically increasing).
*/
create function app_private.tg__timestamps() returns trigger as $$
begin
NEW.created_at = (case when TG_OP = 'INSERT' then NOW() else OLD.created_at end);
NEW.updated_at = (case when TG_OP = 'UPDATE' and OLD.updated_at >= NOW() then OLD.updated_at + interval '1 millisecond' else NOW() end);
return NEW;
end;
$$ language plpgsql volatile set search_path to pg_catalog, public, pg_temp;
comment on function app_private.tg__timestamps() is
E'This trigger should be called on all tables with created_at, updated_at - it ensures that they cannot be manipulated and that updated_at will always be larger than the previous updated_at.';
/*
* This trigger is useful for adding realtime features to our GraphQL schema
* with minimal effort in the database. It's a very generic trigger function;
* you're intended to pass three arguments when you call it:
*
* 1. The "event" name to include, this is an arbitrary string.
* 2. The "topic" template that we'll be publishing the event to. A `$1` in
* this may be added as a placeholder which will be replaced by the
* "subject" value.
* 3. The "subject" column, we'll read the value of this column from the NEW
* (for insert/update) or OLD (for delete) record and include it in the
* event payload.
*
* A PostgreSQL `NOTIFY` will be issued to the topic (or "channel") generated
* from arguments 2 and 3, the body of the notification will be a stringified
* JSON object containing `event`, `sub` (the subject specified by argument 3)
* and `id` (the record id).
*
* Example:
*
* create trigger _500_gql_update
* after update on app_public.users
* for each row
* execute procedure app_public.tg__graphql_subscription(
* 'userChanged', -- the "event" string, useful for the client to know what happened
* 'graphql:user:$1', -- the "topic" the event will be published to, as a template
* 'id' -- If specified, `$1` above will be replaced with NEW.id or OLD.id from the trigger.
* );
*/
create function app_public.tg__graphql_subscription() returns trigger as $$
declare
v_process_new bool = (TG_OP = 'INSERT' OR TG_OP = 'UPDATE');
v_process_old bool = (TG_OP = 'UPDATE' OR TG_OP = 'DELETE');
v_event text = TG_ARGV[0];
v_topic_template text = TG_ARGV[1];
v_attribute text = TG_ARGV[2];
v_record record;
v_sub text;
v_topic text;
v_i int = 0;
v_last_topic text;
begin
for v_i in 0..1 loop
if (v_i = 0) and v_process_new is true then
v_record = new;
elsif (v_i = 1) and v_process_old is true then
v_record = old;
else
continue;
end if;
if v_attribute is not null then
execute 'select $1.' || quote_ident(v_attribute)
using v_record
into v_sub;
end if;
if v_sub is not null then
v_topic = replace(v_topic_template, '$1', v_sub);
else
v_topic = v_topic_template;
end if;
if v_topic is distinct from v_last_topic then
-- This if statement prevents us from triggering the same notification twice
v_last_topic = v_topic;
perform pg_notify(v_topic, json_build_object(
'event', v_event,
'subject', v_sub,
'id', v_record.id
)::text);
end if;
end loop;
return v_record;
end;
$$ language plpgsql volatile;
comment on function app_public.tg__graphql_subscription() is
E'This function enables the creation of simple focussed GraphQL subscriptions using database triggers. Read more here: https://www.graphile.org/postgraphile/subscriptions/#custom-subscriptions';
--! split: 0040-pg-sessions-table.sql
/*
* This table is used (only) by `connect-pg-simple` (see `installSession.ts`)
* to track cookie session information at the webserver (`express`) level if
* you don't have a redis server. If you're using redis everywhere (including
* development) then you don't need this table.
*
* Do not confuse this with the `app_private.sessions` table.
*/
create table app_private.connect_pg_simple_sessions (
sid varchar not null,
sess json not null,
expire timestamp not null
);
alter table app_private.connect_pg_simple_sessions
enable row level security;
alter table app_private.connect_pg_simple_sessions
add constraint session_pkey primary key (sid) not deferrable initially immediate;
--! split: 1000-sessions.sql
/*
* The sessions table is used to track who is logged in, if there are any
* restrictions on that session, when it was last active (so we know if it's
* still valid), etc.
*
* In Starter we only have an extremely limited implementation of this, but you
* could add things like "last_auth_at" to it so that you could track when they
* last officially authenticated; that way if you have particularly dangerous
* actions you could require them to log back in to allow them to perform those
* actions. (GitHub does this when you attempt to change the settings on a
* repository, for example.)
*
* The primary key is a cryptographically secure random uuid; the value of this
* primary key should be secret, and only shared with the user themself. We
* currently wrap this session in a webserver-level session (either using
* redis, or using `connect-pg-simple` which uses the
* `connect_pg_simple_sessions` table which we defined previously) so that we
* don't even send the raw session id to the end user, but you might want to
* consider exposing it for things such as mobile apps or command line
* utilities that may not want to implement cookies to maintain a cookie
* session.
*/
create table app_private.sessions (
uuid uuid not null default gen_random_uuid() primary key,
user_id uuid not null,
-- You could add access restriction columns here if you want, e.g. for OAuth scopes.
created_at timestamptz not null default now(),
last_active timestamptz not null default now()
);
alter table app_private.sessions enable row level security;
-- To allow us to efficiently see what sessions are open for a particular user.
create index on app_private.sessions (user_id);
--! split: 1010-session-functions.sql
/*
* This function is responsible for reading the `jwt.claims.session_id`
* transaction setting (set from the `pgSettings` function within
* `installPostGraphile.ts`). Defining this inside a function means we can
* modify it in future to allow additional ways of defining the session.
*/
-- Note we have this in `app_public` but it doesn't show up in the GraphQL
-- schema because we've used `postgraphile.tags.jsonc` to omit it. We could
-- have put it in app_hidden to get the same effect more easily, but it's often
-- useful to un-omit it to ease debugging auth issues.
create function app_public.current_session_id() returns uuid as $$
select nullif(pg_catalog.current_setting('jwt.claims.session_id', true), '')::uuid;
$$ language sql stable;
comment on function app_public.current_session_id() is
E'Handy method to get the current session ID.';
/*
* We can figure out who the current user is by looking up their session in the
* sessions table using the `current_session_id()` function.
*
* A less secure but more performant version of this function might contain only:
*
* select nullif(pg_catalog.current_setting('jwt.claims.user_id', true), '')::uuid;
*
* The increased security of this implementation is because even if someone gets
* the ability to run SQL within this transaction they cannot impersonate
* another user without knowing their session_id (which should be closely
* guarded).
*
* The below implementation is more secure than simply indicating the user_id
* directly: even if an SQL injection vulnerability were to allow a user to set
* their `jwt.claims.session_id` to another value, it would take them many
* millenia to be able to correctly guess someone else's session id (since it's
* a cryptographically secure random value that is kept secret). This makes
* impersonating another user virtually impossible.
*/
create function app_public.current_user_id() returns uuid as $$
select user_id from app_private.sessions where uuid = app_public.current_session_id();
$$ language sql stable security definer set search_path to pg_catalog, public, pg_temp;
comment on function app_public.current_user_id() is
E'Handy method to get the current user ID for use in RLS policies, etc; in GraphQL, use `currentUser{id}` instead.';
--! split: 1020-users.sql
/*
* The users table stores (unsurprisingly) the users of our application. You'll
* notice that it does NOT contain private information such as the user's
* password or their email address; that's because the users table is seen as
* public - anyone who can "see" the user can see this information.
*
* The author sees `is_admin` and `is_verified` as public information; if you
* disagree then you should relocate these attributes to another table, such as
* `user_secrets`.
*/
create table app_public.users (
id uuid primary key default gen_random_uuid(),
username citext not null unique check(length(username) >= 2 and length(username) <= 24 and username ~ '^[a-zA-Z]([_]?[a-zA-Z0-9])+$'),
name text,
avatar_url text check(avatar_url ~ '^https?://[^/]+'),
is_admin boolean not null default false,
is_verified boolean not null default false,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
alter table app_public.users enable row level security;
-- We couldn't implement this relationship on the sessions table until the users table existed!
alter table app_private.sessions
add constraint sessions_user_id_fkey
foreign key ("user_id") references app_public.users on delete cascade;
-- Users are publicly visible, like on GitHub, Twitter, Facebook, Trello, etc.
create policy select_all on app_public.users for select using (true);
-- You can only update yourself.
create policy update_self on app_public.users for update using (id = app_public.current_user_id());
grant select on app_public.users to :DATABASE_VISITOR;
-- NOTE: `insert` is not granted, because we'll handle that separately
grant update(username, name, avatar_url) on app_public.users to :DATABASE_VISITOR;
-- NOTE: `delete` is not granted, because we require confirmation via request_account_deletion/confirm_account_deletion
comment on table app_public.users is
E'A user who can log in to the application.';
comment on column app_public.users.id is
E'Unique identifier for the user.';
comment on column app_public.users.username is
E'Public-facing username (or ''handle'') of the user.';
comment on column app_public.users.name is
E'Public-facing name (or pseudonym) of the user.';
comment on column app_public.users.avatar_url is
E'Optional avatar URL.';
comment on column app_public.users.is_admin is
E'If true, the user has elevated privileges.';
create trigger _100_timestamps
before insert or update on app_public.users
for each row
execute procedure app_private.tg__timestamps();
/**********/
-- Returns the current user; this is a "custom query" function; see:
-- https://www.graphile.org/postgraphile/custom-queries/
-- So this will be queryable via GraphQL as `{ currentUser { ... } }`
create function app_public.current_user() returns app_public.users as $$
select users.* from app_public.users where id = app_public.current_user_id();
$$ language sql stable;
comment on function app_public.current_user() is
E'The currently logged in user (or null if not logged in).';
/**********/
-- The users table contains all the public information, but we need somewhere
-- to store private information. In fact, this data is so private that we don't
-- want the user themselves to be able to see it - things like the bcrypted
-- password hash, timestamps of recent login attempts (to allow us to
-- auto-protect user accounts that are under attack), etc.
create table app_private.user_secrets (
user_id uuid not null primary key references app_public.users on delete cascade,
password_hash text,
last_login_at timestamptz not null default now(),
failed_password_attempts int not null default 0,
first_failed_password_attempt timestamptz,
reset_password_token text,
reset_password_token_generated timestamptz,
failed_reset_password_attempts int not null default 0,
first_failed_reset_password_attempt timestamptz,
delete_account_token text,
delete_account_token_generated timestamptz
);
alter table app_private.user_secrets enable row level security;
comment on table app_private.user_secrets is
E'The contents of this table should never be visible to the user. Contains data mostly related to authentication.';
/*
* When we insert into `users` we _always_ want there to be a matching
* `user_secrets` entry, so we have a trigger to enforce this:
*/
create function app_private.tg_user_secrets__insert_with_user() returns trigger as $$
begin
insert into app_private.user_secrets(user_id) values(NEW.id);
return NEW;
end;
$$ language plpgsql volatile set search_path to pg_catalog, public, pg_temp;
create trigger _500_insert_secrets
after insert on app_public.users
for each row
execute procedure app_private.tg_user_secrets__insert_with_user();
comment on function app_private.tg_user_secrets__insert_with_user() is
E'Ensures that every user record has an associated user_secret record.';
/*
* Because you can register with username/password or using OAuth (social
* login), we need a way to tell the user whether or not they have a
* password. This is to help the UI display the right interface: change
* password or set password.
*/
create function app_public.users_has_password(u app_public.users) returns boolean as $$
select (password_hash is not null) from app_private.user_secrets where user_secrets.user_id = u.id and u.id = app_public.current_user_id();
$$ language sql stable security definer set search_path to pg_catalog, public, pg_temp;
/*
* When the user validates their email address we want the UI to be notified
* immediately, so we'll issue a notification to the `graphql:user:*` topic
* which GraphQL users can subscribe to via the `currentUserUpdated`
* subscription field.
*/
create trigger _500_gql_update
after update on app_public.users
for each row
execute procedure app_public.tg__graphql_subscription(
'userChanged', -- the "event" string, useful for the client to know what happened
'graphql:user:$1', -- the "topic" the event will be published to, as a template
'id' -- If specified, `$1` above will be replaced with NEW.id or OLD.id from the trigger.
);
--! split: 1030-user_emails.sql
/*
* A user may have more than one email address; this is useful when letting the
* user change their email so that they can verify the new one before deleting
* the old one, but is also generally useful as they might want to use
* different emails to log in versus where to send notifications. Therefore we
* track user emails in a separate table.
*/
create table app_public.user_emails (
id uuid primary key default gen_random_uuid(),
user_id uuid not null default app_public.current_user_id() references app_public.users on delete cascade,
email citext not null check (email ~ '[^@]+@[^@]+\.[^@]+'),
is_verified boolean not null default false,
is_primary boolean not null default false,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
-- Each user can only have an email once.
constraint user_emails_user_id_email_key unique(user_id, email),
-- An unverified email cannot be set as the primary email.
constraint user_emails_must_be_verified_to_be_primary check(is_primary is false or is_verified is true)
);
alter table app_public.user_emails enable row level security;
-- Once an email is verified, it may only be used by one user. (We can't
-- enforce this before an email is verified otherwise it could be used to
-- prevent a legitimate user from signing up.)
create unique index uniq_user_emails_verified_email on app_public.user_emails(email) where (is_verified is true);
-- Only one primary email per user.
create unique index uniq_user_emails_primary_email on app_public.user_emails (user_id) where (is_primary is true);
-- Allow efficient retrieval of all the emails owned by a particular user.
create index idx_user_emails_user on app_public.user_emails (user_id);
-- For the user settings page sorting
create index idx_user_emails_primary on app_public.user_emails (is_primary, user_id);
-- Keep created_at and updated_at up to date.
create trigger _100_timestamps
before insert or update on app_public.user_emails
for each row
execute procedure app_private.tg__timestamps();
-- When an email address is added to a user, notify them (in case their account was compromised).
create trigger _500_audit_added
after insert on app_public.user_emails
for each row
execute procedure app_private.tg__add_audit_job(
'added_email',
'user_id',
'id',
'email'
);
-- When an email address is removed from a user, notify them (in case their account was compromised).
create trigger _500_audit_removed
after delete on app_public.user_emails
for each row
execute procedure app_private.tg__add_audit_job(
'removed_email',
'user_id',
'id',
'email'
);
-- You can't verify an email address that someone else has already verified. (Email is taken.)
create function app_public.tg_user_emails__forbid_if_verified() returns trigger as $$
begin
if exists(select 1 from app_public.user_emails where email = NEW.email and is_verified is true) then
raise exception 'An account using that email address has already been created.' using errcode='EMTKN';
end if;
return NEW;
end;
$$ language plpgsql volatile security definer set search_path to pg_catalog, public, pg_temp;
create trigger _200_forbid_existing_email before insert on app_public.user_emails for each row execute procedure app_public.tg_user_emails__forbid_if_verified();
-- If the email wasn't already verified (e.g. via a social login provider) then
-- queue up the verification email to be sent.
create trigger _900_send_verification_email
after insert on app_public.user_emails
for each row
when (NEW.is_verified is false)
execute procedure app_private.tg__add_job('user_emails__send_verification');
comment on table app_public.user_emails is
E'Information about a user''s email address.';
comment on column app_public.user_emails.email is
E'The users email address, in `a@b.c` format.';
comment on column app_public.user_emails.is_verified is
E'True if the user has is_verified their email address (by clicking the link in the email we sent them, or logging in with a social login provider), false otherwise.';
-- Users may only manage their own emails.
create policy select_own on app_public.user_emails for select using (user_id = app_public.current_user_id());
create policy insert_own on app_public.user_emails for insert with check (user_id = app_public.current_user_id());
-- NOTE: we don't allow emails to be updated, instead add a new email and delete the old one.
create policy delete_own on app_public.user_emails for delete using (user_id = app_public.current_user_id());
grant select on app_public.user_emails to :DATABASE_VISITOR;
grant insert (email) on app_public.user_emails to :DATABASE_VISITOR;
-- No update
grant delete on app_public.user_emails to :DATABASE_VISITOR;
-- Prevent deleting the user's last email, otherwise they can't access password reset/etc.
create function app_public.tg_user_emails__prevent_delete_last_email() returns trigger as $$
begin
if exists (
with remaining as (
select user_emails.user_id
from app_public.user_emails
inner join deleted
on user_emails.user_id = deleted.user_id
-- Don't delete last verified email
where (user_emails.is_verified is true or not exists (
select 1
from deleted d2
where d2.user_id = user_emails.user_id
and d2.is_verified is true
))
order by user_emails.id asc
/*
* Lock this table to prevent race conditions; see:
* https://www.cybertec-postgresql.com/en/triggers-to-enforce-constraints/
*/
for update of user_emails
)
select 1
from app_public.users
where id in (
select user_id from deleted
except
select user_id from remaining
)
)
then
raise exception 'You must have at least one (verified) email address' using errcode = 'CDLEA';
end if;
return null;
end;
$$
language plpgsql
-- Security definer is required for 'FOR UPDATE OF' since we don't grant UPDATE privileges.
security definer
set search_path = pg_catalog, public, pg_temp;
-- Note this check runs AFTER the email was deleted. If the user was deleted
-- then their emails will also be deleted (thanks to the foreign key on delete
-- cascade) and this is desirable; we only want to prevent the deletion if
-- the user still exists so we check after the statement completes.
create trigger _500_prevent_delete_last
after delete on app_public.user_emails
referencing old table as deleted
for each statement
execute procedure app_public.tg_user_emails__prevent_delete_last_email();
/**********/
/*
* Just like with users and user_secrets, there are secrets for emails that we
* don't want the user to be able to see - for example the verification token.
* Like with user_secrets we automatically create a record in this table
* whenever a record is added to user_emails.
*/
create table app_private.user_email_secrets (
user_email_id uuid primary key references app_public.user_emails on delete cascade,
verification_token text,
verification_email_sent_at timestamptz,
password_reset_email_sent_at timestamptz
);
alter table app_private.user_email_secrets enable row level security;
comment on table app_private.user_email_secrets is
E'The contents of this table should never be visible to the user. Contains data mostly related to email verification and avoiding spamming users.';
comment on column app_private.user_email_secrets.password_reset_email_sent_at is
E'We store the time the last password reset was sent to this email to prevent the email getting flooded.';
create function app_private.tg_user_email_secrets__insert_with_user_email() returns trigger as $$
declare
v_verification_token text;
begin
if NEW.is_verified is false then
v_verification_token = encode(gen_random_bytes(7), 'hex');
end if;
insert into app_private.user_email_secrets(user_email_id, verification_token) values(NEW.id, v_verification_token);
return NEW;
end;
$$ language plpgsql volatile security definer set search_path to pg_catalog, public, pg_temp;
create trigger _500_insert_secrets
after insert on app_public.user_emails
for each row
execute procedure app_private.tg_user_email_secrets__insert_with_user_email();
comment on function app_private.tg_user_email_secrets__insert_with_user_email() is
E'Ensures that every user_email record has an associated user_email_secret record.';
/**********/
/*
* When the user receives the email verification message it will contain the
* token; this function is responsible for checking the token and marking the
* email as verified if it matches. Note it is a `SECURITY DEFINER` function,
* which means it runs with the security of the user that defined the function
* (which is the database owner) - i.e. it can do anything the database owner
* can do. This means we have to be very careful what we put in the function,
* and make sure that it checks that the user is allowed to do what they're
* trying to do - in this case, we do that check by ensuring the token matches.
*/
create function app_public.verify_email(user_email_id uuid, token text) returns boolean as $$
begin
update app_public.user_emails
set
is_verified = true,
is_primary = is_primary or not exists(
select 1 from app_public.user_emails other_email where other_email.user_id = user_emails.user_id and other_email.is_primary is true
)
where id = user_email_id
and exists(
select 1 from app_private.user_email_secrets where user_email_secrets.user_email_id = user_emails.id and verification_token = token
);
return found;
end;
$$ language plpgsql strict volatile security definer set search_path to pg_catalog, public, pg_temp;
comment on function app_public.verify_email(user_email_id uuid, token text) is
E'Once you have received a verification token for your email, you may call this mutation with that token to make your email verified.';
/*
* When the users first email address is verified we will mark their account as
* verified, which can unlock additional features that were gated behind an
* `isVerified` check.
*/
create function app_public.tg_user_emails__verify_account_on_verified() returns trigger as $$
begin
update app_public.users set is_verified = true where id = new.user_id and is_verified is false;
return new;
end;
$$ language plpgsql strict volatile security definer set search_path to pg_catalog, public, pg_temp;
create trigger _500_verify_account_on_verified
after insert or update of is_verified
on app_public.user_emails
for each row
when (new.is_verified is true)
execute procedure app_public.tg_user_emails__verify_account_on_verified();
--! split: 1040-user_authentications.sql
/*
* In addition to logging in with username/email and password, users may use
* other authentication methods, such as "social login" (OAuth) with GitHub,
* Twitter, Facebook, etc. We store details of these logins to the
* user_authentications and user_authentication_secrets tables.
*
* The user is allowed to delete entries in this table (which will unlink them
* from that service), but adding records to the table requires elevated
* privileges (it's managed by the `installPassportStrategy.ts` middleware,
* which calls out to the `app_private.link_or_register_user` database
* function).
*/
create table app_public.user_authentications (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references app_public.users on delete cascade,
service text not null,
identifier text not null,
details jsonb not null default '{}'::jsonb,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
constraint uniq_user_authentications unique(service, identifier)
);
alter table app_public.user_authentications enable row level security;
-- Make it efficient to find all the authentications for a particular user.
create index on app_public.user_authentications(user_id);
-- Keep created_at and updated_at up to date.
create trigger _100_timestamps
before insert or update on app_public.user_authentications
for each row
execute procedure app_private.tg__timestamps();
comment on table app_public.user_authentications is
E'Contains information about the login providers this user has used, so that they may disconnect them should they wish.';
comment on column app_public.user_authentications.service is
E'The login service used, e.g. `twitter` or `github`.';
comment on column app_public.user_authentications.identifier is
E'A unique identifier for the user within the login service.';
comment on column app_public.user_authentications.details is
E'Additional profile details extracted from this login method';
-- Users may view and delete their social logins.
create policy select_own on app_public.user_authentications for select using (user_id = app_public.current_user_id());
create policy delete_own on app_public.user_authentications for delete using (user_id = app_public.current_user_id());
-- TODO: on delete, check this isn't the last one, or that they have a verified
-- email address or password. For now we're not worrying about that since all
-- the OAuth providers we use verify the email address.
-- Notify the user if a social login is removed.
create trigger _500_audit_removed
after delete on app_public.user_authentications
for each row
execute procedure app_private.tg__add_audit_job(
'unlinked_account',
'user_id',
'service',
'identifier'
);
-- NOTE: we don't need to notify when a linked account is added here because
-- that's handled in the link_or_register_user function.
grant select on app_public.user_authentications to :DATABASE_VISITOR;
grant delete on app_public.user_authentications to :DATABASE_VISITOR;
/**********/
-- This table contains secret information for each user_authentication; could
-- be things like access tokens, refresh tokens, profile information. Whatever
-- the passport strategy deems necessary.
create table app_private.user_authentication_secrets (
user_authentication_id uuid not null primary key references app_public.user_authentications on delete cascade,
details jsonb not null default '{}'::jsonb
);
alter table app_private.user_authentication_secrets enable row level security;
-- NOTE: user_authentication_secrets doesn't need an auto-inserter as we handle
-- that everywhere that can create a user_authentication row.
--! split: 1100-login.sql
/*
* This function handles logging in a user with their username (or email
* address) and password.
*
* Note that it is not in app_public; this function is intended to be called
* with elevated privileges (namely from `PassportLoginPlugin.ts`). The reason
* for this is because we want to be able to track failed login attempts (to
* help protect user accounts). If this were callable by a user, they could
* roll back the transaction when a login fails and no failed attempts would be
* logged, effectively giving them infinite retries. We want to disallow this,
* so we only let code call into `login` that we trust to not roll back the
* transaction afterwards.
*/
create function app_private.login(username citext, password text) returns app_private.sessions as $$
declare
v_user app_public.users;
v_user_secret app_private.user_secrets;
v_login_attempt_window_duration interval = interval '5 minutes';
v_session app_private.sessions;
begin
if username like '%@%' then
-- It's an email
select users.* into v_user
from app_public.users
inner join app_public.user_emails
on (user_emails.user_id = users.id)
where user_emails.email = login.username
order by
user_emails.is_verified desc, -- Prefer verified email
user_emails.created_at asc -- Failing that, prefer the first registered (unverified users _should_ verify before logging in)
limit 1;
else
-- It's a username
select users.* into v_user
from app_public.users
where users.username = login.username;
end if;
if not (v_user is null) then
-- Load their secrets
select * into v_user_secret from app_private.user_secrets
where user_secrets.user_id = v_user.id;
-- Have there been too many login attempts?
if (
v_user_secret.first_failed_password_attempt is not null
and
v_user_secret.first_failed_password_attempt > NOW() - v_login_attempt_window_duration
and
v_user_secret.failed_password_attempts >= 3
) then
raise exception 'User account locked - too many login attempts. Try again after 5 minutes.' using errcode = 'LOCKD';
end if;
-- Not too many login attempts, let's check the password.
-- NOTE: `password_hash` could be null, this is fine since `NULL = NULL` is null, and null is falsy.
if v_user_secret.password_hash = crypt(password, v_user_secret.password_hash) then
-- Excellent - they're logged in! Let's reset the attempt tracking
update app_private.user_secrets
set failed_password_attempts = 0, first_failed_password_attempt = null, last_login_at = now()
where user_id = v_user.id;
-- Create a session for the user
insert into app_private.sessions (user_id) values (v_user.id) returning * into v_session;
-- And finally return the session
return v_session;
else
-- Wrong password, bump all the attempt tracking figures
update app_private.user_secrets
set
failed_password_attempts = (case when first_failed_password_attempt is null or first_failed_password_attempt < now() - v_login_attempt_window_duration then 1 else failed_password_attempts + 1 end),
first_failed_password_attempt = (case when first_failed_password_attempt is null or first_failed_password_attempt < now() - v_login_attempt_window_duration then now() else first_failed_password_attempt end)
where user_id = v_user.id;
return null; -- Must not throw otherwise transaction will be aborted and attempts won't be recorded
end if;
else
-- No user with that email/username was found
return null;
end if;
end;
$$ language plpgsql strict volatile;
comment on function app_private.login(username citext, password text) is
E'Returns a user that matches the username/password combo, or null on failure.';
--! split: 1110-logout.sql
/*
* Logging out deletes the session, and clears the session_id in the
* transaction. This is a `SECURITY DEFINER` function, so we check that the
* user is allowed to do it by matching the current_session_id().
*/
create function app_public.logout() returns void as $$
begin
-- Delete the session
delete from app_private.sessions where uuid = app_public.current_session_id();
-- Clear the identifier from the transaction
perform set_config('jwt.claims.session_id', '', true);
end;
$$ language plpgsql security definer volatile set search_path to pg_catalog, public, pg_temp;
--! split: 1120-forgot_password.sql
/*
* When a user forgets their password we want to let them set a new one; but we
* need to be very careful with this. We don't want to reveal whether or not an
* account exists by the email address, so we email the entered email address
* whether or not it's registered. If it's not registered, we track these
* attempts in `unregistered_email_password_resets` to ensure that we don't
* allow spamming the address; otherwise we store it to `user_email_secrets`.
*
* `app_public.forgot_password` is responsible for checking these things and
* queueing a reset password token to be emailed to the user. For what happens
* after the user receives this email, see instead `app_private.reset_password`.
*
* NOTE: unlike app_private.login and app_private.reset_password, rolling back
* the results of this function will not cause any security issues so we do not
* need to call it indirectly as we do for those other functions. (Rolling back
* will undo the tracking of when we sent the email but it will also prevent
* the email being sent, so it's harmless.)
*/
create table app_private.unregistered_email_password_resets (
email citext constraint unregistered_email_pkey primary key,
attempts int not null default 1,
latest_attempt timestamptz not null
);
comment on table app_private.unregistered_email_password_resets is
E'If someone tries to recover the password for an email that is not registered in our system, this table enables us to rate-limit outgoing emails to avoid spamming.';
comment on column app_private.unregistered_email_password_resets.attempts is
E'We store the number of attempts to help us detect accounts being attacked.';
comment on column app_private.unregistered_email_password_resets.latest_attempt is
E'We store the time the last password reset was sent to this email to prevent the email getting flooded.';
/**********/
create function app_public.forgot_password(email citext) returns void as $$
declare
v_user_email app_public.user_emails;
v_token text;
v_token_min_duration_between_emails interval = interval '3 minutes';
v_token_max_duration interval = interval '3 days';
v_now timestamptz = clock_timestamp(); -- Function can be called multiple during transaction
v_latest_attempt timestamptz;
begin
-- Find the matching user_email:
select user_emails.* into v_user_email
from app_public.user_emails
where user_emails.email = forgot_password.email
order by is_verified desc, id desc;
-- If there is no match:
if v_user_email is null then
-- This email doesn't exist in the system; trigger an email stating as much.
-- We do not allow this email to be triggered more than once every 15
-- minutes, so we need to track it:
insert into app_private.unregistered_email_password_resets (email, latest_attempt)
values (forgot_password.email, v_now)
on conflict on constraint unregistered_email_pkey
do update
set latest_attempt = v_now, attempts = unregistered_email_password_resets.attempts + 1
where unregistered_email_password_resets.latest_attempt < v_now - interval '15 minutes'
returning latest_attempt into v_latest_attempt;
if v_latest_attempt = v_now then
perform graphile_worker.add_job(
'user__forgot_password_unregistered_email',
json_build_object('email', forgot_password.email::text)
);
end if;
-- TODO: we should clear out the unregistered_email_password_resets table periodically.
return;
end if;
-- There was a match.
-- See if we've triggered a reset recently:
if exists(
select 1
from app_private.user_email_secrets
where user_email_id = v_user_email.id
and password_reset_email_sent_at is not null
and password_reset_email_sent_at > v_now - v_token_min_duration_between_emails
) then
-- If so, take no action.
return;
end if;
-- Fetch or generate reset token:
update app_private.user_secrets
set
reset_password_token = (
case
when reset_password_token is null or reset_password_token_generated < v_now - v_token_max_duration
then encode(gen_random_bytes(7), 'hex')
else reset_password_token
end
),
reset_password_token_generated = (
case
when reset_password_token is null or reset_password_token_generated < v_now - v_token_max_duration
then v_now
else reset_password_token_generated
end
)
where user_id = v_user_email.user_id
returning reset_password_token into v_token;
-- Don't allow spamming an email:
update app_private.user_email_secrets
set password_reset_email_sent_at = v_now