-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema.sql
1930 lines (1453 loc) · 55.9 KB
/
schema.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
--
-- PostgreSQL database dump
--
-- Dumped from database version 13.0 (Debian 13.0-1.pgdg100+1)
-- Dumped by pg_dump version 13.0
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: app_hidden; Type: SCHEMA; Schema: -; Owner: -
--
CREATE SCHEMA app_hidden;
--
-- Name: app_private; Type: SCHEMA; Schema: -; Owner: -
--
CREATE SCHEMA app_private;
--
-- Name: app_public; Type: SCHEMA; Schema: -; Owner: -
--
CREATE SCHEMA app_public;
--
-- Name: graphile_worker; Type: SCHEMA; Schema: -; Owner: -
--
CREATE SCHEMA graphile_worker;
--
-- Name: citext; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS citext WITH SCHEMA public;
--
-- Name: EXTENSION citext; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION citext IS 'data type for case-insensitive character strings';
--
-- Name: pgcrypto; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public;
--
-- Name: EXTENSION pgcrypto; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION pgcrypto IS 'cryptographic functions';
--
-- Name: uuid-ossp; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;
--
-- Name: EXTENSION "uuid-ossp"; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION "uuid-ossp" IS 'generate universally unique identifiers (UUIDs)';
--
-- Name: biconditional_statement(boolean, boolean); Type: FUNCTION; Schema: app_hidden; Owner: -
--
CREATE FUNCTION app_hidden.biconditional_statement(a boolean, b boolean) RETURNS boolean
LANGUAGE sql IMMUTABLE STRICT
AS $$
select (a and b) or (not a and not b)
$$;
--
-- Name: implication(boolean, boolean); Type: FUNCTION; Schema: app_hidden; Owner: -
--
CREATE FUNCTION app_hidden.implication(a boolean, b boolean) RETURNS boolean
LANGUAGE sql IMMUTABLE STRICT
AS $$
select not a or b
$$;
--
-- Name: is_from_0_to_100(numeric); Type: FUNCTION; Schema: app_hidden; Owner: -
--
CREATE FUNCTION app_hidden.is_from_0_to_100(num numeric) RETURNS boolean
LANGUAGE sql IMMUTABLE STRICT
AS $$
select (num >= 0) AND (num <= 100);
$$;
SET default_tablespace = '';
SET default_table_access_method = heap;
--
-- Name: users; Type: TABLE; Schema: app_public; Owner: -
--
CREATE TABLE app_public.users (
id uuid DEFAULT public.uuid_generate_v4() NOT NULL,
user_secret_id uuid NOT NULL,
username public.citext NOT NULL,
name text,
avatar_url text,
is_admin boolean DEFAULT false NOT NULL,
created_at timestamp with time zone DEFAULT now() NOT NULL,
updated_at timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT users_avatar_url_check CHECK ((avatar_url ~ '^https?://[^/]+'::text)),
CONSTRAINT users_name_check CHECK ((name <> ''::text)),
CONSTRAINT users_username_check CHECK (((length((username)::text) >= 2) AND (length((username)::text) <= 24) AND (username OPERATOR(public.~) '^[a-zA-Z]([a-zA-Z0-9][_]?)+$'::public.citext)))
);
--
-- Name: TABLE users; Type: COMMENT; Schema: app_public; Owner: -
--
COMMENT ON TABLE app_public.users IS '@omit all
A user who can log in to the application.';
--
-- Name: COLUMN users.id; Type: COMMENT; Schema: app_public; Owner: -
--
COMMENT ON COLUMN app_public.users.id IS 'Unique identifier for the user.';
--
-- Name: COLUMN users.username; Type: COMMENT; Schema: app_public; Owner: -
--
COMMENT ON COLUMN app_public.users.username IS 'Public-facing username (or ''handle'') of the user.';
--
-- Name: COLUMN users.name; Type: COMMENT; Schema: app_public; Owner: -
--
COMMENT ON COLUMN app_public.users.name IS 'Public-facing name (or pseudonym) of the user.';
--
-- Name: COLUMN users.avatar_url; Type: COMMENT; Schema: app_public; Owner: -
--
COMMENT ON COLUMN app_public.users.avatar_url IS 'Optional avatar URL.';
--
-- Name: COLUMN users.is_admin; Type: COMMENT; Schema: app_public; Owner: -
--
COMMENT ON COLUMN app_public.users.is_admin IS 'If true, the user has elevated privileges.';
--
-- Name: link_or_register_user(integer, character varying, character varying, json, json); Type: FUNCTION; Schema: app_private; Owner: -
--
CREATE FUNCTION app_private.link_or_register_user(f_user_id integer, f_service character varying, f_identifier character varying, f_profile json, f_auth_details json) RETURNS app_public.users
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO '$user', 'public'
AS $$
declare
v_matched_user_id uuid;
v_matched_authentication_id int;
v_email citext;
v_name text;
v_avatar_url text;
v_user app_public.users;
v_user_email app_hidden.user_emails;
begin
-- See if a user account already matches these details
select id, user_id
into v_matched_authentication_id, v_matched_user_id
from app_public.user_authentications
where service = f_service
and identifier = f_identifier
limit 1;
if v_matched_user_id is not null and f_user_id is not null and v_matched_user_id <> f_user_id then
/* A different user already has this account linked. */
raise exception 'APP_EXCEPTION__LINK_OR_REGISTER_USER__DIFFERENT_ACCOUNT_ALREADY_LINKED' using errcode='TAKEN';
end if;
v_email = f_profile ->> 'email';
v_name := f_profile ->> 'name';
v_avatar_url := f_profile ->> 'avatar_url';
if v_matched_authentication_id is null then
if f_user_id is not null then
-- Link new account to logged in user account
insert into app_public.user_authentications (user_id, service, identifier, details) values
(f_user_id, f_service, f_identifier, f_profile) returning id, user_id into v_matched_authentication_id, v_matched_user_id;
insert into app_private.user_authentication_secrets (user_authentication_id, details) values
(v_matched_authentication_id, f_auth_details);
elsif v_email is not null then
-- See if the email is registered
select * into v_user_email from app_hidden.user_emails where email = v_email and is_verified is true;
if not (v_user_email is null) then
-- User exists!
insert into app_public.user_authentications (user_id, service, identifier, details) values
(v_user_email.user_id, f_service, f_identifier, f_profile) returning id, user_id into v_matched_authentication_id, v_matched_user_id;
insert into app_private.user_authentication_secrets (user_authentication_id, details) values
(v_matched_authentication_id, f_auth_details);
end if;
end if;
end if;
if v_matched_user_id is null and f_user_id is null and v_matched_authentication_id is null then
-- Create and return a new user account
return app_private.register_user(f_service, f_identifier, f_profile, f_auth_details, true);
else
if v_matched_authentication_id is not null then
update app_public.user_authentications
set details = f_profile
where id = v_matched_authentication_id;
update app_private.user_authentication_secrets
set details = f_auth_details
where user_authentication_id = v_matched_authentication_id;
update app_public.users
set
name = coalesce(users.name, v_name),
avatar_url = coalesce(users.avatar_url, v_avatar_url)
where id = v_matched_user_id
returning * into v_user;
return v_user;
else
-- v_matched_authentication_id is null
-- -> v_matched_user_id is null (they're paired)
-- -> f_user_id is not null (because the if clause above)
-- -> v_matched_authentication_id is not null (because of the separate if block above creating a user_authentications)
-- -> contradiction.
/* This should not occur */
raise exception 'APP_EXCEPTION__RESET_PASSWORD__SHOULD_NOT_OCCUR';
end if;
end if;
end;
$$;
--
-- Name: FUNCTION link_or_register_user(f_user_id integer, f_service character varying, f_identifier character varying, f_profile json, f_auth_details json); Type: COMMENT; Schema: app_private; Owner: -
--
COMMENT ON FUNCTION app_private.link_or_register_user(f_user_id integer, f_service character varying, f_identifier character varying, f_profile json, f_auth_details json) IS 'If you''re logged in, this will link an additional OAuth login to your account if necessary. If you''re logged out it may find if an account already exists (based on OAuth details or email address) and return that, or create a new user account if necessary.';
--
-- Name: really_create_user(text, text, boolean, text, text, text); Type: FUNCTION; Schema: app_private; Owner: -
--
CREATE FUNCTION app_private.really_create_user(username text, email text, email_is_verified boolean, name text, avatar_url text, password text DEFAULT NULL::text) RETURNS app_public.users
LANGUAGE plpgsql
SET search_path TO '$user', 'public'
AS $$
declare
v_user app_public.users;
v_user_secret_id uuid;
v_user_email_id uuid;
begin
-- Store the password
insert into app_private.user_secrets (password_hash) values
(
case
when password is null
then null
else crypt(password, gen_salt('bf'))
end
)
returning id into v_user_secret_id;
-- Insert the new user
insert into app_public.users (user_secret_id, username, name, avatar_url) values
(v_user_secret_id, username, name, avatar_url)
returning * into v_user;
-- Add the user's email
if email is not null then
insert into app_hidden.user_emails
(
user_id,
email,
is_verified,
verification_token,
verification_email_sent_at
)
values
(
v_user.id,
email,
email_is_verified,
case
when email_is_verified = true
then null
else encode(gen_random_bytes(4), 'hex')
end,
null
)
returning id into v_user_email_id;
if email_is_verified = false then
perform graphile_worker.add_job(
'JOB__SEND_VERIFICATION_EMAIL_FOR_USER_EMAIL',
json_build_object(
'id', v_user_email_id
)
);
end if;
end if;
return v_user;
end;
$$;
--
-- Name: FUNCTION really_create_user(username text, email text, email_is_verified boolean, name text, avatar_url text, password text); Type: COMMENT; Schema: app_private; Owner: -
--
COMMENT ON FUNCTION app_private.really_create_user(username text, email text, email_is_verified boolean, name text, avatar_url text, password text) IS 'Creates a user account. All arguments are optional, it trusts the calling method to perform sanitisation.';
--
-- Name: register_user(character varying, character varying, json, json, boolean); Type: FUNCTION; Schema: app_private; Owner: -
--
CREATE FUNCTION app_private.register_user(f_service character varying, f_identifier character varying, f_profile json, f_auth_details json, f_email_is_verified boolean DEFAULT false) RETURNS app_public.users
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO '$user', 'public'
AS $$
declare
v_user app_public.users;
v_email citext;
v_name text;
v_username text;
v_avatar_url text;
v_user_authentication_id int;
begin
-- Extract data from the user’s OAuth profile data.
v_email := f_profile ->> 'email';
v_name := f_profile ->> 'name';
v_username := f_profile ->> 'username';
v_avatar_url := f_profile ->> 'avatar_url';
-- Create the user account
v_user = app_private.really_create_user(
username => v_username,
email => v_email,
email_is_verified => f_email_is_verified,
name => v_name,
avatar_url => v_avatar_url
);
-- Insert the user’s private account data (e.g. OAuth tokens)
insert into app_public.user_authentications (user_id, service, identifier, details) values
(v_user.id, f_service, f_identifier, f_profile) returning id into v_user_authentication_id;
insert into app_private.user_authentication_secrets (user_authentication_id, details) values
(v_user_authentication_id, f_auth_details);
return v_user;
end;
$$;
--
-- Name: FUNCTION register_user(f_service character varying, f_identifier character varying, f_profile json, f_auth_details json, f_email_is_verified boolean); Type: COMMENT; Schema: app_private; Owner: -
--
COMMENT ON FUNCTION app_private.register_user(f_service character varying, f_identifier character varying, f_profile json, f_auth_details json, f_email_is_verified boolean) IS 'Used to register a user from information gleaned from OAuth. Primarily used by link_or_register_user';
--
-- Name: tg__set_updated_at(); Type: FUNCTION; Schema: app_private; Owner: -
--
CREATE FUNCTION app_private.tg__set_updated_at() RETURNS trigger
LANGUAGE plpgsql
AS $$
begin
new.updated_at := current_timestamp;
return new;
end;
$$;
--
-- Name: web_login(text, text); Type: FUNCTION; Schema: app_private; Owner: -
--
CREATE FUNCTION app_private.web_login(username text, password text) RETURNS app_public.users
LANGUAGE plpgsql STRICT SECURITY DEFINER
SET search_path TO '$user', 'public'
AS $$
declare
v_user app_public.users;
v_user_secret app_private.user_secrets;
v_login_attempt_window_duration interval = interval '6 hours';
begin
select * into v_user from app_public.user_by_username_or_verified_email(username);
if not (v_user is null) then
-- Load their secrets
select * into v_user_secret from app_private.user_secrets
where id = v_user.user_secret_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.password_attempts >= 20
) then
-- User account locked - too many login attempts
raise exception 'APP_EXCEPTION__LOGIN__ACCOUNT_LOCKED_TOO_MANY_ATTEMPTS' using errcode = 'LOCKD';
end if;
-- Not too many login attempts, let's check the password
if v_user_secret.password_hash = crypt(password, v_user_secret.password_hash) then
-- Excellent - they're loggged in! Let's reset the attempt tracking
update app_private.user_secrets
set password_attempts = 0, first_failed_password_attempt = null
where id = v_user.user_secret_id;
return v_user;
else
-- Wrong password, bump all the attempt tracking figures
update app_private.user_secrets
set
password_attempts = (
case
when first_failed_password_attempt is null
or first_failed_password_attempt < now() - v_login_attempt_window_duration
then 1
else 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 id = v_user.user_secret_id;
return null;
end if;
else
-- No user with that email/username was found
return null;
end if;
end;
$$;
--
-- Name: FUNCTION web_login(username text, password text); Type: COMMENT; Schema: app_private; Owner: -
--
COMMENT ON FUNCTION app_private.web_login(username text, password text) IS 'Returns a user that matches the username/password combo, or null on failure.';
--
-- Name: current_user(); Type: FUNCTION; Schema: app_public; Owner: -
--
CREATE FUNCTION app_public."current_user"() RETURNS app_public.users
LANGUAGE sql STABLE
SET search_path TO '$user', 'public'
AS $$
select users.*
from app_public.users
where id = app_public.current_user_id_or_null();
$$;
--
-- Name: FUNCTION "current_user"(); Type: COMMENT; Schema: app_public; Owner: -
--
COMMENT ON FUNCTION app_public."current_user"() IS 'The currently logged in user (or null if not logged in).';
--
-- Name: current_user_id_or_null(); Type: FUNCTION; Schema: app_public; Owner: -
--
CREATE FUNCTION app_public.current_user_id_or_null() RETURNS uuid
LANGUAGE sql STABLE
AS $$
select nullif(current_setting('jwt.claims.user_id', true), '')::uuid;
$$;
--
-- Name: FUNCTION current_user_id_or_null(); Type: COMMENT; Schema: app_public; Owner: -
--
COMMENT ON FUNCTION app_public.current_user_id_or_null() IS '@omit
Handy method to get the current user ID for use in RLS policies, etc; in GraphQL, use `query { currentUser { id } }` instead.';
--
-- Name: current_user_id_required(); Type: FUNCTION; Schema: app_public; Owner: -
--
CREATE FUNCTION app_public.current_user_id_required() RETURNS uuid
LANGUAGE sql STABLE
AS $$
select current_setting('jwt.claims.user_id', false)::uuid;
$$;
--
-- Name: FUNCTION current_user_id_required(); Type: COMMENT; Schema: app_public; Owner: -
--
COMMENT ON FUNCTION app_public.current_user_id_required() IS '@omit
Get current user id or raise error that returns 403 status code';
--
-- Name: forgot_password(text); Type: FUNCTION; Schema: app_public; Owner: -
--
CREATE FUNCTION app_public.forgot_password(email text) RETURNS boolean
LANGUAGE plpgsql STRICT SECURITY DEFINER
SET search_path TO '$user', 'public'
AS $$
declare
v_user_email app_hidden.user_emails;
v_reset_token text;
v_reset_min_duration_between_emails interval = interval '30 minutes';
v_reset_max_duration interval = interval '3 days';
begin
-- Find the matching user_email
select user_emails.* into v_user_email
from app_hidden.user_emails
where user_emails.email = forgot_password.email::citext
order by is_verified desc, id desc;
if not (v_user_email is null) then
-- 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 > now() - v_reset_min_duration_between_emails
) then
return true;
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_at < NOW() - v_reset_max_duration
then encode(gen_random_bytes(6), 'hex')
else reset_password_token
end
),
reset_password_token_generated_at = (
case
when reset_password_token is null or reset_password_token_generated_at < NOW() - v_reset_max_duration
then now()
else reset_password_token_generated_at
end
)
where user_id = v_user_email.user_id
returning reset_password_token into v_reset_token;
-- Trigger email send
perform graphile_worker.add_job(
'JOB__SEND_PASSWORD_RESET_EMAIL',
json_build_object(
'id', v_user_email.id
)
);
return true;
end if;
return false;
end;
$$;
--
-- Name: FUNCTION forgot_password(email text); Type: COMMENT; Schema: app_public; Owner: -
--
COMMENT ON FUNCTION app_public.forgot_password(email text) IS '@resultFieldName success
If you''ve forgotten your password, give us one of your email addresses and we'' send you a reset token. Note this only works if you have added an email address!';
--
-- Name: generate_url_safe_token(); Type: FUNCTION; Schema: app_public; Owner: -
--
CREATE FUNCTION app_public.generate_url_safe_token() RETURNS text
LANGUAGE sql STABLE
AS $$
select translate(
encode(gen_random_bytes(8), 'base64'),
'+/=',
''
)
$$;
--
-- Name: FUNCTION generate_url_safe_token(); Type: COMMENT; Schema: app_public; Owner: -
--
COMMENT ON FUNCTION app_public.generate_url_safe_token() IS '@omit';
--
-- Name: reset_password(uuid, text, text); Type: FUNCTION; Schema: app_public; Owner: -
--
CREATE FUNCTION app_public.reset_password(user_id uuid, token text, new_password text) RETURNS app_public.users
LANGUAGE plpgsql STRICT SECURITY DEFINER
SET search_path TO '$user', 'public'
AS $$
declare
v_user app_public.users;
v_user_email app_hidden.user_emails;
v_user_secret app_private.user_secrets;
v_reset_max_duration interval = interval '3 days';
v_max_reset_password_attempts int = 20;
begin
select users.* into v_user
from app_public.users
where id = user_id;
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 reset attempts?
if (
v_user_secret.first_failed_reset_password_attempt is not null
and
v_user_secret.first_failed_reset_password_attempt > NOW() - v_reset_max_duration
and
v_user_secret.reset_password_attempts >= v_max_reset_password_attempts
) then
-- Password reset locked - too many reset attempts
raise exception 'APP_EXCEPTION__RESET_PASSWORD__ACCOUNT_LOCKED_TOO_MANY_ATTEMPTS' using errcode = 'LOCKD';
end if;
-- Not too many reset attempts, let's check the token
if v_user_secret.reset_password_token = token then
-- Excellent - they're legit; let's reset the password as requested
update app_private.user_secrets
set
password_hash = crypt(new_password, gen_salt('bf')),
password_attempts = 0,
first_failed_password_attempt = null,
reset_password_token = null,
reset_password_token_generated_at = null,
reset_password_attempts = 0,
first_failed_reset_password_attempt = null
where user_secrets.user_id = v_user.id;
-- Notify that password has been reset
select * into v_user_email
from app_hidden.user_emails
where user_emails.user_id = reset_password.user_id
and is_verified = true
order by created_at
limit 1;
if v_user_email is not NULL then
perform graphile_worker.add_job(
'JOB__SEND_PASSWORD_CHANGED_EMAIL',
json_build_object(
'email', v_user_email.email
)
);
end if;
return v_user;
else
-- Wrong token, bump all the attempt tracking figures
update app_private.user_secrets
set
reset_password_attempts = (
case
when first_failed_reset_password_attempt is null
or first_failed_reset_password_attempt < now() - v_reset_max_duration
then 1
else reset_password_attempts + 1
end
),
first_failed_reset_password_attempt = (
case when first_failed_reset_password_attempt is null
or first_failed_reset_password_attempt < now() - v_reset_max_duration
then now()
else first_failed_reset_password_attempt
end
)
where user_secrets.user_id = v_user.id;
/* Invalid token */
raise exception 'APP_EXCEPTION__RESET_PASSWORD__INVALID_TOKEN' using errcode='INVLD';
end if;
else
-- No user with that id was found
/* Invalid user ID */
raise exception 'APP_EXCEPTION__RESET_PASSWORD__INVALID_USER_ID' using errcode='INVLD';
end if;
end;
$$;
--
-- Name: FUNCTION reset_password(user_id uuid, token text, new_password text); Type: COMMENT; Schema: app_public; Owner: -
--
COMMENT ON FUNCTION app_public.reset_password(user_id uuid, token text, new_password text) IS 'After triggering forgotPassword, you''ll be sent a reset token. Combine this with your user ID and a new password to reset your password.';
--
-- Name: user_by_username_or_verified_email(text); Type: FUNCTION; Schema: app_public; Owner: -
--
CREATE FUNCTION app_public.user_by_username_or_verified_email(username_or_email text) RETURNS app_public.users
LANGUAGE sql STABLE STRICT
SET search_path TO '$user', 'public'
AS $$
select users.*
from app_public.users
where
-- Match username against users username, or any verified email address
(
users.username = user_by_username_or_verified_email.username_or_email
or
exists(
select 1
from app_hidden.user_emails
where user_id = users.id
and is_verified is true
and email = user_by_username_or_verified_email.username_or_email::citext
)
);
$$;
--
-- Name: user_emails; Type: TABLE; Schema: app_hidden; Owner: -
--
CREATE TABLE app_hidden.user_emails (
id uuid DEFAULT public.uuid_generate_v4() NOT NULL,
user_id uuid NOT NULL,
email public.citext NOT NULL,
is_verified boolean DEFAULT false NOT NULL,
verification_token text,
verification_email_sent_at timestamp with time zone,
password_reset_email_sent_at timestamp with time zone,
created_at timestamp with time zone DEFAULT now() NOT NULL,
updated_at timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT user_emails_check CHECK (app_hidden.biconditional_statement((is_verified = true), (verification_token IS NULL))),
CONSTRAINT user_emails_check1 CHECK (app_hidden.implication((is_verified = true), (verification_email_sent_at IS NULL))),
CONSTRAINT user_emails_check2 CHECK (app_hidden.implication((is_verified = false), (password_reset_email_sent_at IS NULL))),
CONSTRAINT user_emails_email_check CHECK ((email OPERATOR(public.~) '[^@]+@[^@]+\.[^@]+'::public.citext))
);
--
-- Name: TABLE user_emails; Type: COMMENT; Schema: app_hidden; Owner: -
--
COMMENT ON TABLE app_hidden.user_emails IS '@omit all
Information about a user''s email address.';
--
-- Name: COLUMN user_emails.email; Type: COMMENT; Schema: app_hidden; Owner: -
--
COMMENT ON COLUMN app_hidden.user_emails.email IS 'The users email address, in `[email protected]` format.';
--
-- Name: COLUMN user_emails.is_verified; Type: COMMENT; Schema: app_hidden; Owner: -
--
COMMENT ON COLUMN app_hidden.user_emails.is_verified IS '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.';
--
-- Name: verify_user_email(text); Type: FUNCTION; Schema: app_public; Owner: -
--
CREATE FUNCTION app_public.verify_user_email(token text) RETURNS app_hidden.user_emails
LANGUAGE plpgsql STRICT SECURITY DEFINER
SET search_path TO '$user', 'public'
AS $$
declare
v_user_email app_hidden.user_emails;
v_max_duration interval = interval '7 days';
begin
UPDATE app_hidden.user_emails
SET is_verified = true
WHERE id = (
SELECT user_email_id
FROM app_private.user_email_secrets
WHERE user_email_secrets.verification_token = token
AND user_email_secrets.verification_email_sent_at > now() - v_max_duration
)
RETURNING * INTO v_user_email;
if v_user_email is NULL THEN
/* verification token is invalid or expired */
raise exception 'APP_EXCEPTION__VERIFY_USER_EMAIL__TOKEN_INVALID_OR_EXPIRED' using errcode='INVLD';
end if;
return v_user_email;
end;
$$;
--
-- Name: FUNCTION verify_user_email(token text); Type: COMMENT; Schema: app_public; Owner: -
--
COMMENT ON FUNCTION app_public.verify_user_email(token text) IS '@resultFieldName userEmail
After you add an email address, you will receive an email with a verification token. Give us the verification token to mark that email as verified!';
--
-- Name: jobs; Type: TABLE; Schema: graphile_worker; Owner: -
--
CREATE TABLE graphile_worker.jobs (
id bigint NOT NULL,
queue_name text DEFAULT (public.gen_random_uuid())::text,
task_identifier text NOT NULL,
payload json DEFAULT '{}'::json NOT NULL,
priority integer DEFAULT 0 NOT NULL,
run_at timestamp with time zone DEFAULT now() NOT NULL,
attempts integer DEFAULT 0 NOT NULL,
max_attempts integer DEFAULT 25 NOT NULL,
last_error text,
created_at timestamp with time zone DEFAULT now() NOT NULL,
updated_at timestamp with time zone DEFAULT now() NOT NULL,
key text,
locked_at timestamp with time zone,
locked_by text,
revision integer DEFAULT 0 NOT NULL,
flags jsonb,
CONSTRAINT jobs_key_check CHECK ((length(key) > 0))
);
--
-- Name: add_job(text, json, text, timestamp with time zone, integer, text, integer, text[]); Type: FUNCTION; Schema: graphile_worker; Owner: -
--
CREATE FUNCTION graphile_worker.add_job(identifier text, payload json DEFAULT NULL::json, queue_name text DEFAULT NULL::text, run_at timestamp with time zone DEFAULT NULL::timestamp with time zone, max_attempts integer DEFAULT NULL::integer, job_key text DEFAULT NULL::text, priority integer DEFAULT NULL::integer, flags text[] DEFAULT NULL::text[]) RETURNS graphile_worker.jobs
LANGUAGE plpgsql
AS $$
declare
v_job "graphile_worker".jobs;
begin
-- Apply rationality checks
if length(identifier) > 128 then
raise exception 'Task identifier is too long (max length: 128).' using errcode = 'GWBID';
end if;
if queue_name is not null and length(queue_name) > 128 then
raise exception 'Job queue name is too long (max length: 128).' using errcode = 'GWBQN';
end if;
if job_key is not null and length(job_key) > 512 then
raise exception 'Job key is too long (max length: 512).' using errcode = 'GWBJK';
end if;
if max_attempts < 1 then
raise exception 'Job maximum attempts must be at least 1' using errcode = 'GWBMA';
end if;
if job_key is not null then
-- Upsert job
insert into "graphile_worker".jobs (
task_identifier,
payload,
queue_name,
run_at,
max_attempts,
key,
priority,
flags
)
values(
identifier,
coalesce(payload, '{}'::json),
queue_name,
coalesce(run_at, now()),
coalesce(max_attempts, 25),
job_key,
coalesce(priority, 0),
(
select jsonb_object_agg(flag, true)
from unnest(flags) as item(flag)
)
)
on conflict (key) do update set
task_identifier=excluded.task_identifier,
payload=excluded.payload,
queue_name=excluded.queue_name,
max_attempts=excluded.max_attempts,
run_at=excluded.run_at,
priority=excluded.priority,
revision=jobs.revision + 1,
flags=excluded.flags,
-- always reset error/retry state
attempts=0,
last_error=null
where jobs.locked_at is null
returning *
into v_job;
-- If upsert succeeded (insert or update), return early
if not (v_job is null) then
return v_job;
end if;
-- Upsert failed -> there must be an existing job that is locked. Remove
-- existing key to allow a new one to be inserted, and prevent any
-- subsequent retries by bumping attempts to the max allowed.
update "graphile_worker".jobs
set
key = null,
attempts = jobs.max_attempts
where key = job_key;
end if;
-- insert the new job. Assume no conflicts due to the update above
insert into "graphile_worker".jobs(
task_identifier,
payload,
queue_name,
run_at,
max_attempts,
key,
priority,
flags
)
values(
identifier,
coalesce(payload, '{}'::json),
queue_name,
coalesce(run_at, now()),
coalesce(max_attempts, 25),
job_key,
coalesce(priority, 0),
(
select jsonb_object_agg(flag, true)
from unnest(flags) as item(flag)
)
)
returning *
into v_job;