Repository navigation
Expand file tree
/
Copy pathfirestore.rules
More file actions
1485 lines (1344 loc) · 84.7 KB
/
Copy pathfirestore.rules
File metadata and controls
1485 lines (1344 loc) · 84.7 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
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
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function isOwner(userId) {
return request.auth != null && request.auth.uid == userId;
}
// Email sign-ups must confirm their address before joining or posting.
// Google and GitHub confirm the email themselves.
function isVerified() {
return request.auth != null && (
request.auth.token.email_verified == true ||
request.auth.token.firebase.sign_in_provider in ['google.com', 'github.com']
);
}
function changedKeys() {
return request.resource.data.diff(resource.data).affectedKeys();
}
// Moderators have the `moderator` custom claim on their Firebase Auth
// account (scripts/set-moderator.mjs). They review reported posts on
// /moderation.
function isModerator() {
return request.auth != null && request.auth.token.moderator == true;
}
// Admins have the `admin` claim too (scripts/set-moderator.mjs); they
// manage the moderation team and post site-wide announcements
function isAdmin() {
return request.auth != null && request.auth.token.admin == true;
}
// ---- Moderators acting on members' groups, meetups and other items ----
// Every such action is saved with a new moderationLog entry in the same
// write (src/app/moderation/useItemModeration.ts), so it's on the record.
// True when this write creates moderationLog/<logId>
function isLoggedByModerator(logId) {
let logPath = /databases/$(database)/documents/moderationLog/$(logId);
return isModerator() && !exists(logPath) && existsAfter(logPath);
}
// Deleting an item, like studyGroups/abc, is logged as
// moderationLog/delete-studyGroups-abc
function isModeratorDeleting(kind, id) {
return isLoggedByModerator('delete-' + kind + '-' + id);
}
// A task, check-in, update or entry goes with its item (any time after
// the item's deletion was logged), or on its own with its own entry, like
// moderationLog/delete-studyGroups-abc-checkIns-xyz
function isModeratorDeletingPart(kind, id, part, partId) {
return isModerator()
&& (existsAfter(/databases/$(database)/documents/moderationLog/$('delete-' + kind + '-' + id))
|| isLoggedByModerator('delete-' + kind + '-' + id + '-' + part + '-' + partId));
}
// A moderator edits only the item's wording (`keys`), naming a new
// moderationLog entry about this item in `moderationLogId`
function isModeratorEditing(kind, id, keys) {
let logId = request.resource.data.moderationLogId;
let logPath = /databases/$(database)/documents/moderationLog/$(logId);
return isModerator()
&& logId is string
&& changedKeys().hasOnly(keys.concat(['moderationLogId']))
&& !exists(logPath)
&& getAfter(logPath).data.action == 'edit-content'
&& getAfter(logPath).data.contentPath == kind + '/' + id;
}
function isModeratorEditingGroup(kind, id) {
return isModeratorEditing(kind, id, ['name', 'name_lowercase', 'topic', 'description'])
&& isValidGroup(request.resource.data);
}
// Study groups, group projects and book clubs share these rules.
// `kind` is the collection name, like 'studyGroups'.
function groupData(kind, groupId) {
return get(/databases/$(database)/documents/$(kind)/$(groupId)).data;
}
function isGroupMemberOf(kind, groupId) {
return request.auth != null && groupData(kind, groupId).memberIds.hasAny([request.auth.uid]);
}
function isGroupCreatorOf(kind, groupId) {
return request.auth != null && groupData(kind, groupId).creatorId == request.auth.uid;
}
function isValidGroup(data) {
return data.name is string && data.name.size() > 0 && data.name.size() <= 75
&& data.topic is string && data.topic.size() > 0 && data.topic.size() <= 50
&& data.description is string && data.description.size() <= 500
&& data.commitmentDays is list && data.commitmentDays.size() > 0 && data.commitmentDays.size() <= 7
&& (!('openToJoinAnytime' in data) || data.openToJoinAnytime is bool)
&& (!('startDate' in data) || data.startDate is timestamp);
}
// A start date being set must be ahead, and at most 90 days away
// (MAX_START_DAYS in src/lib/constants.ts)
function isAllowedStartDate(data) {
return !('startDate' in data)
|| (data.startDate > request.time && data.startDate < request.time + duration.value(90, 'd'));
}
// Only book clubs can stay open to join after their first week
function hasNoAnytimeJoin() {
return !('openToJoinAnytime' in request.resource.data);
}
function canCreateGroup() {
return isVerified()
&& request.resource.data.creatorId == request.auth.uid
&& request.resource.data.memberIds == [request.auth.uid]
// The real time, so the join window can't be stretched
&& request.resource.data.createdAt == request.time
&& isValidGroup(request.resource.data)
&& isAllowedStartDate(request.resource.data);
}
// Joining adds only yourself, while there's room, until the group starts
// (its start date, or two weeks after it was created; see joinDeadline in
// src/lib/groups.ts), or any time for a book club that stays open
function isJoiningGroup() {
return isVerified()
&& changedKeys().hasOnly(['memberIds'])
&& resource.data.memberIds.size() < 25
&& ((('startDate' in resource.data)
? request.time < resource.data.startDate
: request.time - resource.data.createdAt < duration.value(14, 'd'))
|| resource.data.get('openToJoinAnytime', false) == true)
&& isAddingSelfToList(request.resource.data.memberIds, resource.data.memberIds);
}
// Anyone but the creator can leave; the creator deletes the group instead
function isLeavingGroup() {
return changedKeys().hasOnly(['memberIds'])
&& resource.data.creatorId != request.auth.uid
&& isRemovingSelfFromList(request.resource.data.memberIds, resource.data.memberIds);
}
function isEditingGroup() {
return isVerified()
&& resource.data.creatorId == request.auth.uid
&& changedKeys().hasOnly(['name', 'name_lowercase', 'topic', 'description', 'commitment', 'commitmentDays', 'startTime', 'timezone', 'githubUrl', 'openToJoinAnytime', 'startDate'])
&& isValidGroup(request.resource.data)
// A new start date must be ahead; an unchanged one can be in the past
&& (!changedKeys().hasAny(['startDate']) || isAllowedStartDate(request.resource.data));
}
function isValidNewCheckIn() {
return isVerified()
&& request.resource.data.userId == request.auth.uid
&& request.resource.data.content is string
&& request.resource.data.content.size() > 0 && request.resource.data.content.size() <= 2000
&& request.resource.data.type in ['daily', 'weekly'];
}
// Only the author can edit a check-in, and it stays theirs
function isEditingOwnCheckIn() {
return request.auth != null
&& resource.data.userId == request.auth.uid
&& request.resource.data.userId == resource.data.userId
&& request.resource.data.content is string
&& request.resource.data.content.size() > 0 && request.resource.data.content.size() <= 2000;
}
function isMeetupCreator(meetupId) {
return request.auth != null && get(/databases/$(database)/documents/meetups/$(meetupId)).data.creatorId == request.auth.uid;
}
function isMeetupAttendee(meetupId) {
return request.auth != null && get(/databases/$(database)/documents/meetups/$(meetupId)).data.attendeeIds.hasAny([request.auth.uid]);
}
function isMentorshipMember(mentorshipId) {
return request.auth != null && get(/databases/$(database)/documents/mentorships/$(mentorshipId)).data.memberIds.hasAny([request.auth.uid]);
}
function isTutorshipMember(tutorshipId) {
return request.auth != null && get(/databases/$(database)/documents/tutorships/$(tutorshipId)).data.memberIds.hasAny([request.auth.uid]);
}
function isPairingMember(pairingId) {
return request.auth != null && get(/databases/$(database)/documents/pairings/$(pairingId)).data.memberIds.hasAny([request.auth.uid]);
}
// Members can list the mentorships, tutorships or pairings they're in,
// with where('memberIds', 'array-contains', <their uid>). Every result
// must include them, so a query without that filter is refused.
function isListingOwnConnections() {
return request.auth != null && resource.data.memberIds.hasAny([request.auth.uid]);
}
function isAddingSelfToList(listAfter, listBefore) {
return request.auth != null
&& listAfter.size() == listBefore.size() + 1
&& listAfter.hasAll(listBefore)
&& listAfter.hasAny([request.auth.uid])
&& !listBefore.hasAny([request.auth.uid]);
}
function isRemovingSelfFromList(listAfter, listBefore) {
return request.auth != null
&& listBefore.size() == listAfter.size() + 1
&& listBefore.hasAll(listAfter)
&& listBefore.hasAny([request.auth.uid])
&& !listAfter.hasAny([request.auth.uid]);
}
// Mentorships, tutorships and pairings are named after both members' IDs,
// sorted and joined with "_", like "abc_xyz"
function connectionIdWith(otherId) {
return request.auth.uid < otherId
? request.auth.uid + '_' + otherId
: otherId + '_' + request.auth.uid;
}
// Requests are only ever changed by the person they were sent to, and only
// to accept or decline them, once.
function isAnsweringRequest() {
return request.auth != null
&& request.auth.uid == resource.data.toUid
&& resource.data.status == 'pending'
&& changedKeys().hasOnly(['status'])
&& request.resource.data.status in ['accepted', 'declined'];
}
// True when `fromId` sent the caller this request and the save being
// checked is the one accepting it: it was pending before and is accepted
// after.
function isAcceptingRequest(requestsCollection, requestId, fromId) {
let before = get(/databases/$(database)/documents/$(requestsCollection)/$(requestId)).data;
let after = getAfter(/databases/$(database)/documents/$(requestsCollection)/$(requestId)).data;
return before.fromUid == fromId
&& before.toUid == request.auth.uid
&& before.status == 'pending'
&& after.status == 'accepted';
}
// A mentorship, tutorship or pairing is saved by the person accepting the
// request, in the same save that accepts it. It names the request, holds
// exactly the two people on it, and nothing the app doesn't write.
// `roleKeys` are the extra fields, like ['mentorId', 'menteeId'].
function isStartingConnection(connectionId, requestsCollection, roleKeys) {
let data = request.resource.data;
let fromId = get(/databases/$(database)/documents/$(requestsCollection)/$(data.requestId)).data.fromUid;
return isVerified()
&& data.keys().hasOnly(['id', 'memberIds', 'requestId', 'createdAt'].concat(roleKeys))
&& connectionId == connectionIdWith(fromId)
&& data.id == connectionId
&& data.memberIds.size() == 2
&& data.memberIds.hasAll([request.auth.uid, fromId])
&& data.createdAt == request.time
&& isAcceptingRequest(requestsCollection, data.requestId, fromId);
}
// Mentorship and tutorship requests say which role the sender wants
// filled: "seeking_mentor" means the person accepting becomes the mentor.
function hasRolesFromRequest(requestsCollection, offerer, seeker) {
let data = request.resource.data;
let sent = get(/databases/$(database)/documents/$(requestsCollection)/$(data.requestId)).data;
return (sent.type == 'seeking_' + offerer
&& data[offerer + 'Id'] == request.auth.uid
&& data[seeker + 'Id'] == sent.fromUid)
|| (sent.type == 'seeking_' + seeker
&& data[offerer + 'Id'] == sent.fromUid
&& data[seeker + 'Id'] == request.auth.uid);
}
function isStartingRoleConnection(connectionId, requestsCollection, offerer, seeker) {
return isStartingConnection(connectionId, requestsCollection, [offerer + 'Id', seeker + 'Id'])
&& hasRolesFromRequest(requestsCollection, offerer, seeker);
}
// Profiles are public, so they must never hold an email address.
// Firebase Auth already keeps each member's email privately.
// `createdAt` is when the account was made, set once at signup and never
// changed.
match /users/{userId} {
allow read: if true;
allow create: if isOwner(userId) && !('email' in request.resource.data)
&& (!('createdAt' in request.resource.data) || request.resource.data.createdAt == request.time)
&& (!('username' in request.resource.data || 'username_lowercase' in request.resource.data)
|| hasClaimedUsername(request.resource.data));
allow delete: if isOwner(userId);
allow update: if !('email' in request.resource.data) && (
(isOwner(userId) && !changedKeys().hasAny(['createdAt'])
&& request.resource.data.get('privateAccount', false) is bool
&& (!setsUsername(request.resource.data, resource.data) || hasClaimedUsername(request.resource.data))) ||
(
request.resource.data.diff(resource.data).affectedKeys().size() == 1 &&
request.resource.data.diff(resource.data).affectedKeys().hasOnly(['followers']) &&
// A private account's followers are added by the account itself,
// when it accepts a follow request (match /followRequests)
((isVerified() && !hasBlocked(userId, request.auth.uid) && !hasPrivateAccount(userId)
&& isAddingSelfToList(request.resource.data.followers, resource.data.get('followers', []))) ||
isRemovingSelfFromList(request.resource.data.followers, resource.data.get('followers', [])))
)
);
}
// True when `userId` has blocked `otherId` (users/{userId}/private/feedPrefs)
function hasBlocked(userId, otherId) {
let prefsPath = /databases/$(database)/documents/users/$(userId)/private/feedPrefs;
return exists(prefsPath) && get(prefsPath).data.get('blockedIds', []).hasAny([otherId]);
}
// Names nobody can sign up with, so no one can pose as the site's staff.
// Keep in step with RESERVED_USERNAMES in src/lib/usernames.ts.
function isReservedUsername(name) {
return name in [
'root', 'admin', 'administrator', 'abuse', 'webmaster', 'spam', 'help', 'support',
'administratorrequest', 'invalid', 'valid', 'error', 'motd', 'authenticateduser',
'moderator', 'staff', 'official', 'security', 'system', 'w3develops'
];
}
// A username document is named after the lowercase username: 3 to 24
// letters and numbers, as the signup form checks
function isClaimableUsername(name) {
return name.matches('^[a-z0-9]{3,24}$') && !isReservedUsername(name);
}
// A profile's username must be one the member has claimed (in the same
// write, at signup), so the rules above can't be skipped by writing the
// profile directly
function hasClaimedUsername(data) {
return data.username is string
&& data.username_lowercase == data.username.lower()
&& getAfter(/databases/$(database)/documents/usernames/$(data.username_lowercase)).data.uid == request.auth.uid;
}
function setsUsername(data, before) {
return data.diff(before).affectedKeys().hasAny(['username', 'username_lowercase']);
}
match /usernames/{username} {
allow get: if true;
allow list: if false;
allow create: if request.auth != null
&& request.auth.uid == request.resource.data.uid
&& request.resource.data.keys().hasOnly(['uid'])
&& isClaimableUsername(username);
allow update: if false;
// Lets members free up their username when they delete their account
allow delete: if request.auth != null && resource.data.uid == request.auth.uid;
}
// Site-wide announcements, shown in the banner at the top of every page
// and on /news. Admins (the `admin` claim) post them from the Announce tab
// on /moderation, can end them early, and can delete them.
match /announcements/{announcementId} {
allow read: if true;
allow create: if isAdmin()
&& isValidAnnouncement(request.resource.data)
&& request.resource.data.createdBy == request.auth.uid
&& request.resource.data.createdAt == request.time;
allow update: if isAdmin()
&& isValidAnnouncement(request.resource.data)
&& request.resource.data.diff(resource.data).affectedKeys().hasOnly(['isActive', 'endTime']);
allow delete: if isAdmin();
}
function isValidAnnouncement(data) {
return data.keys().hasOnly(['title', 'message', 'type', 'link', 'startTime', 'endTime', 'isActive', 'createdAt', 'createdBy'])
&& data.keys().hasAll(['title', 'message', 'type', 'startTime', 'endTime', 'isActive', 'createdAt', 'createdBy'])
&& data.title is string && data.title.size() >= 1 && data.title.size() <= 80
&& data.message is string && data.message.size() >= 1 && data.message.size() <= 300
&& data.type in ['info', 'warning', 'success', 'alert']
&& (!('link' in data) || (data.link is string && data.link.size() <= 300
&& data.link.matches('https://[^\\s]+|/([^/\\s][^\\s]*)?')))
&& data.startTime is timestamp && data.endTime is timestamp && data.endTime > data.startTime
&& data.isActive is bool && data.createdAt is timestamp && data.createdBy is string;
}
// w3Develops' own posts (community insights and news roundups), written
// only by the scheduler in functions/src/posts.ts through the Admin SDK
match /posts/{postId} {
allow read: if true;
allow write: if false;
}
// ---- Member articles on /news (src/lib/articles.ts) ----
// Members apply to write; moderators approve them as writers; writers
// draft and submit articles; moderators publish or send them back.
function isWriter(userId) {
return exists(/databases/$(database)/documents/writers/$(userId));
}
function isValidWriterApplication(data) {
return data.about is string && data.about.size() > 0 && data.about.size() <= 1000
&& !hasBlockedWord(data.about)
&& data.links is list && data.links.size() >= 1 && data.links.size() <= 3
&& data.links.join(' ').matches('https://[^\\s]{1,300}( https://[^\\s]{1,300}){0,2}')
&& data.topics is list && data.topics.size() <= 5;
}
match /writerApplications/{userId} {
allow read: if isOwner(userId) || isModerator();
allow create: if isOwner(userId) && isVerified()
&& request.resource.data.keys().hasOnly(['about', 'links', 'topics', 'status', 'createdAt'])
&& request.resource.data.status == 'pending'
&& request.resource.data.createdAt == request.time
&& isValidWriterApplication(request.resource.data);
// Applying again after a "not yet", or a moderator's decision
allow update: if (isOwner(userId) && resource.data.status == 'rejected'
&& changedKeys().hasOnly(['about', 'links', 'topics', 'status', 'createdAt', 'reviewedBy', 'reviewedAt', 'note'])
&& request.resource.data.keys().hasOnly(['about', 'links', 'topics', 'status', 'createdAt'])
&& request.resource.data.status == 'pending'
&& request.resource.data.createdAt == request.time
&& isValidWriterApplication(request.resource.data))
|| (isModerator() && resource.data.status == 'pending'
&& changedKeys().hasOnly(['status', 'reviewedBy', 'reviewedAt', 'note'])
&& request.resource.data.status in ['approved', 'rejected']
&& request.resource.data.reviewedBy == request.auth.uid
&& request.resource.data.reviewedAt == request.time
&& request.resource.data.note is string && request.resource.data.note.size() <= 500
&& (request.resource.data.status == 'rejected' || existsAfter(/databases/$(database)/documents/writers/$(userId))));
allow delete: if isOwner(userId);
}
// Approved writers, public so their articles can say so
match /writers/{userId} {
allow read: if true;
allow create: if isModerator()
&& request.resource.data.keys().hasOnly(['approvedBy', 'approvedAt'])
&& request.resource.data.approvedBy == request.auth.uid
&& request.resource.data.approvedAt == request.time;
allow update: if false;
allow delete: if isModerator();
}
function isValidArticle(data) {
return data.title is string && data.title.size() >= 10 && data.title.size() <= 120
&& data.summary is string && data.summary.size() > 0 && data.summary.size() <= 300
&& data.body is string && data.body.size() > 0 && data.body.size() <= 20000
&& data.topic in ['programming', 'career', 'ai', 'security', 'open-source', 'community', 'other']
&& !hasBlockedWord(data.title) && !hasBlockedWord(data.summary) && !hasBlockedWord(data.body);
}
match /articles/{articleId} {
allow read: if resource.data.status == 'published'
|| isModerator()
|| (request.auth != null && resource.data.authorId == request.auth.uid);
allow create: if isVerified() && isWriter(request.auth.uid)
&& request.resource.data.keys().hasOnly(['authorId', 'authorName', 'authorPhoto', 'title', 'summary', 'body', 'topic', 'status', 'createdAt', 'updatedAt'])
&& request.resource.data.authorId == request.auth.uid
&& request.resource.data.authorName == get(/databases/$(database)/documents/users/$(request.auth.uid)).data.username
&& request.resource.data.authorPhoto == get(/databases/$(database)/documents/users/$(request.auth.uid)).data.get('profilePictureUrl', '')
&& request.resource.data.status in ['draft', 'submitted']
&& request.resource.data.createdAt == request.time
&& request.resource.data.updatedAt == request.time
&& isValidArticle(request.resource.data);
// Writers change their drafts, submit them, and fix ones sent back;
// moderators publish or send back submitted ones
allow update: if (request.auth != null && resource.data.authorId == request.auth.uid
&& isWriter(request.auth.uid)
&& resource.data.status in ['draft', 'submitted', 'rejected']
&& changedKeys().hasOnly(['title', 'summary', 'body', 'topic', 'status', 'updatedAt'])
&& request.resource.data.status in ['draft', 'submitted']
&& request.resource.data.updatedAt == request.time
&& isValidArticle(request.resource.data))
|| (isModerator()
&& changedKeys().hasOnly(['status', 'editorNote', 'publishedAt', 'reviewedBy'])
&& request.resource.data.reviewedBy == request.auth.uid
&& request.resource.data.get('editorNote', '') is string && request.resource.data.get('editorNote', '').size() <= 500
&& ((resource.data.status == 'submitted' && request.resource.data.status == 'published' && request.resource.data.publishedAt == request.time)
|| (resource.data.status in ['submitted', 'published'] && request.resource.data.status == 'rejected')));
allow delete: if (request.auth != null && resource.data.authorId == request.auth.uid && resource.data.status != 'published')
|| isModerator();
}
match /mentorshipRequests/{requestId} {
allow read: if request.auth.uid == resource.data.fromUid || request.auth.uid == resource.data.toUid;
allow create: if isVerified() && request.auth.uid == request.resource.data.fromUid
&& request.resource.data.status == 'pending'
&& request.resource.data.fromUid != request.resource.data.toUid;
allow update: if isAnsweringRequest();
}
match /mentorships/{mentorshipId} {
allow get: if isMentorshipMember(mentorshipId);
allow list: if isListingOwnConnections();
// Saved again if the two reconnect later
allow create, update: if isStartingRoleConnection(mentorshipId, 'mentorshipRequests', 'mentor', 'mentee');
allow delete: if false;
match /tasks/{taskId} {
allow read: if isMentorshipMember(mentorshipId);
allow create: if isVerified() && isMentorshipMember(mentorshipId)
&& request.resource.data.creatorId == request.auth.uid
&& request.resource.data.isCompleted == false;
allow update: if isMentorshipMember(mentorshipId);
allow delete: if isMentorshipMember(mentorshipId) && resource.data.creatorId == request.auth.uid;
}
match /checkIns/{checkInId} {
allow read: if isMentorshipMember(mentorshipId);
allow create: if isMentorshipMember(mentorshipId) && isValidNewCheckIn();
allow update: if isEditingOwnCheckIn();
allow delete: if false;
}
match /notes/{noteId} {
allow read: if isMentorshipMember(mentorshipId);
allow write: if isVerified() && isMentorshipMember(mentorshipId);
}
}
match /tutorRequests/{requestId} {
allow read: if request.auth.uid == resource.data.fromUid || request.auth.uid == resource.data.toUid;
allow create: if isVerified() && request.auth.uid == request.resource.data.fromUid
&& request.resource.data.status == 'pending'
&& request.resource.data.fromUid != request.resource.data.toUid;
allow update: if isAnsweringRequest();
}
match /tutorships/{tutorshipId} {
allow get: if isTutorshipMember(tutorshipId);
allow list: if isListingOwnConnections();
// Saved again if the two reconnect later
allow create, update: if isStartingRoleConnection(tutorshipId, 'tutorRequests', 'tutor', 'student');
allow delete: if false;
match /tasks/{taskId} {
allow read: if isTutorshipMember(tutorshipId);
allow create: if isVerified() && isTutorshipMember(tutorshipId)
&& request.resource.data.creatorId == request.auth.uid
&& request.resource.data.isCompleted == false;
allow update: if isTutorshipMember(tutorshipId);
allow delete: if isTutorshipMember(tutorshipId) && resource.data.creatorId == request.auth.uid;
}
match /checkIns/{checkInId} {
allow read: if isTutorshipMember(tutorshipId);
allow create: if isTutorshipMember(tutorshipId) && isValidNewCheckIn();
allow update: if isEditingOwnCheckIn();
allow delete: if false;
}
match /notes/{noteId} {
allow read: if isTutorshipMember(tutorshipId);
allow write: if isVerified() && isTutorshipMember(tutorshipId);
}
}
match /pairRequests/{requestId} {
allow read: if request.auth.uid == resource.data.fromUid || request.auth.uid == resource.data.toUid;
allow create: if isVerified() && request.auth.uid == request.resource.data.fromUid
&& request.resource.data.status == 'pending'
&& request.resource.data.fromUid != request.resource.data.toUid;
allow update: if isAnsweringRequest();
}
match /pairings/{pairingId} {
allow get: if isPairingMember(pairingId);
allow list: if isListingOwnConnections();
// Saved again if the two reconnect later
allow create, update: if isStartingConnection(pairingId, 'pairRequests', []);
allow delete: if false;
match /tasks/{taskId} {
allow read: if isPairingMember(pairingId);
allow create: if isVerified() && isPairingMember(pairingId)
&& request.resource.data.creatorId == request.auth.uid
&& request.resource.data.isCompleted == false;
allow update: if isPairingMember(pairingId);
allow delete: if isPairingMember(pairingId) && resource.data.creatorId == request.auth.uid;
}
match /checkIns/{checkInId} {
allow read: if isPairingMember(pairingId);
allow create: if isPairingMember(pairingId) && isValidNewCheckIn();
allow update: if isEditingOwnCheckIn();
allow delete: if false;
}
match /notes/{noteId} {
allow read: if isPairingMember(pairingId);
allow write: if isVerified() && isPairingMember(pairingId);
}
}
match /competitions/{competitionId} {
allow read: if true;
allow create: if isVerified() && request.resource.data.creatorId == request.auth.uid;
allow update: if (request.auth != null && resource.data.creatorId == request.auth.uid)
|| isModeratorEditing('competitions', competitionId, ['name', 'name_lowercase', 'description', 'rules', 'prize']);
allow delete: if (request.auth != null && resource.data.creatorId == request.auth.uid)
|| isModeratorDeleting('competitions', competitionId);
match /entries/{entryId} {
allow read: if true;
allow create: if isVerified()
&& request.resource.data.userId == request.auth.uid
&& get(/databases/$(database)/documents/competitions/$(competitionId)).data.endDate > request.time
&& request.resource.data.username is string
&& request.resource.data.projectUrl is string
&& request.resource.data.voterIds == [];
// The entrant can edit their entry while the competition is open, but
// not its votes or owner
allow update: if (request.auth != null && resource.data.userId == request.auth.uid
&& get(/databases/$(database)/documents/competitions/$(competitionId)).data.endDate > request.time
&& !request.resource.data.diff(resource.data).affectedKeys().hasAny(['voterIds', 'userId'])) ||
// Other members can vote for an entry, or take their vote back
(isVerified() && resource.data.userId != request.auth.uid
&& request.resource.data.diff(resource.data).affectedKeys().hasOnly(['voterIds'])
&& (isAddingSelfToList(request.resource.data.voterIds, resource.data.get('voterIds', []))
|| isRemovingSelfFromList(request.resource.data.voterIds, resource.data.get('voterIds', []))));
allow delete: if (request.auth != null && resource.data.userId == request.auth.uid)
|| isModeratorDeletingPart('competitions', competitionId, 'entries', entryId);
}
}
match /jobs/{jobId} {
allow read: if true;
allow create: if isVerified() && request.resource.data.postedById == request.auth.uid;
allow update: if (request.auth != null && resource.data.postedById == request.auth.uid)
|| isModeratorEditing('jobs', jobId, ['title', 'title_lowercase', 'companyName', 'location', 'description', 'applyUrl']);
allow delete: if (request.auth != null && resource.data.postedById == request.auth.uid)
|| isModeratorDeleting('jobs', jobId);
}
// The free services directory on /marketplace (src/lib/services.ts).
// Each member has up to 5 listings, named "<uid>_1" to "<uid>_5". People
// contact them through their profile or the optional https link; no
// email addresses are stored, and no payments are handled.
function isValidServiceListing(data) {
return data.title is string && data.title.size() > 0 && data.title.size() <= 80
&& data.description is string && data.description.size() > 0 && data.description.size() <= 1000
&& !hasBlockedWord(data.title) && !hasBlockedWord(data.description)
&& data.category in ['websites', 'mobile', 'design', 'marketing', 'writing', 'data', 'devops', 'tutoring', 'tasks', 'other']
&& data.skills is list && data.skills.size() <= 8
&& (data.skills.size() == 0 || data.skills.join(',').matches('[a-z0-9.+# -]{1,30}(,[a-z0-9.+# -]{1,30}){0,7}'))
&& data.priceNote is string && data.priceNote.size() <= 60
&& (!('contactUrl' in data) || (data.contactUrl is string && data.contactUrl.size() <= 300 && data.contactUrl.matches('https://[^\\s]+')));
}
match /serviceListings/{listingId} {
allow read: if true;
allow create: if isVerified()
&& listingId.matches(request.auth.uid + '_[1-5]')
&& request.resource.data.keys().hasOnly(['ownerId', 'ownerName', 'ownerPhoto', 'title', 'description', 'category', 'skills', 'priceNote', 'contactUrl', 'createdAt', 'updatedAt'])
&& request.resource.data.ownerId == request.auth.uid
&& request.resource.data.ownerName == get(/databases/$(database)/documents/users/$(request.auth.uid)).data.username
&& request.resource.data.ownerPhoto == get(/databases/$(database)/documents/users/$(request.auth.uid)).data.get('profilePictureUrl', '')
&& request.resource.data.createdAt == request.time
&& request.resource.data.updatedAt == request.time
&& isValidServiceListing(request.resource.data);
allow update: if (request.auth != null && resource.data.ownerId == request.auth.uid
&& changedKeys().hasOnly(['title', 'description', 'category', 'skills', 'priceNote', 'contactUrl', 'updatedAt'])
&& request.resource.data.updatedAt == request.time
&& isValidServiceListing(request.resource.data))
|| isModeratorEditing('serviceListings', listingId, ['title', 'description', 'priceNote']);
allow delete: if (request.auth != null && resource.data.ownerId == request.auth.uid)
|| isModeratorDeleting('serviceListings', listingId);
}
// ---- Organizations (/orgs): businesses, nonprofits, communities and
// teams. Named by their URL slug. The owner and admins run the page;
// members ask to join (joinRequests) and admins add them. See
// src/lib/organizations.ts.
function isValidOrganization(data) {
return data.name is string && data.name.size() >= 2 && data.name.size() <= 80
&& data.kind in ['business', 'nonprofit', 'community', 'team']
&& data.tagline is string && data.tagline.size() <= 120
&& data.about is string && data.about.size() <= 2000
&& data.location is string && data.location.size() <= 100
&& (data.website == '' || (data.website is string && data.website.size() <= 300 && data.website.matches('https://[^\\s]+')))
&& !hasBlockedWord(data.name) && !hasBlockedWord(data.tagline) && !hasBlockedWord(data.about)
&& data.memberIds is list && data.memberIds.size() <= 500
&& data.adminIds is list && data.adminIds.size() >= 1 && data.adminIds.size() <= 10
&& data.memberIds.hasAll(data.adminIds)
&& data.adminIds.hasAny([data.ownerId]);
}
function isOrgAdmin(orgId) {
return request.auth != null
&& get(/databases/$(database)/documents/organizations/$(orgId)).data.adminIds.hasAny([request.auth.uid]);
}
match /organizations/{orgId} {
allow read: if true;
allow create: if isVerified()
&& orgId.matches('[a-z0-9]([a-z0-9-]{1,38})[a-z0-9]') && !isReservedUsername(orgId.replace('-', ''))
&& request.resource.data.keys().hasOnly(['name', 'kind', 'tagline', 'about', 'website', 'location', 'ownerId', 'adminIds', 'memberIds', 'createdAt', 'updatedAt'])
&& request.resource.data.ownerId == request.auth.uid
&& request.resource.data.adminIds == [request.auth.uid]
&& request.resource.data.memberIds == [request.auth.uid]
&& request.resource.data.createdAt == request.time
&& request.resource.data.updatedAt == request.time
&& isValidOrganization(request.resource.data);
allow update: if (request.auth != null && resource.data.adminIds.hasAny([request.auth.uid])
&& changedKeys().hasOnly(['name', 'kind', 'tagline', 'about', 'website', 'location', 'adminIds', 'memberIds', 'updatedAt'])
&& request.resource.data.updatedAt == request.time
// Only the owner chooses admins
&& (!changedKeys().hasAny(['adminIds']) || resource.data.ownerId == request.auth.uid)
&& isValidOrganization(request.resource.data))
// A member who isn't an admin leaves
|| (changedKeys().hasOnly(['memberIds'])
&& !resource.data.adminIds.hasAny([request.auth.uid])
&& isRemovingSelfFromList(request.resource.data.memberIds, resource.data.memberIds))
|| isModeratorEditing('organizations', orgId, ['name', 'tagline', 'about']);
allow delete: if (request.auth != null && resource.data.ownerId == request.auth.uid)
|| isModeratorDeleting('organizations', orgId);
// Asking to join, named by the member's uid; admins accept by adding
// them to memberIds and deleting the request
match /joinRequests/{userId} {
allow read: if isOwner(userId) || isOrgAdmin(orgId);
allow create: if isOwner(userId) && isVerified()
&& request.resource.data.keys().hasOnly(['name', 'photo', 'note', 'createdAt'])
&& request.resource.data.name == get(/databases/$(database)/documents/users/$(userId)).data.username
&& request.resource.data.photo == get(/databases/$(database)/documents/users/$(userId)).data.get('profilePictureUrl', '')
&& request.resource.data.note is string && request.resource.data.note.size() <= 300
&& !hasBlockedWord(request.resource.data.note)
&& request.resource.data.createdAt == request.time
&& !get(/databases/$(database)/documents/organizations/$(orgId)).data.memberIds.hasAny([userId]);
allow update: if false;
allow delete: if isOwner(userId) || isOrgAdmin(orgId) || isModeratorDeletingPart('organizations', orgId, 'joinRequests', userId);
}
}
match /studyGroups/{groupId} {
allow read: if true;
allow create: if canCreateGroup() && hasNoAnytimeJoin();
allow update: if ((isJoiningGroup() || isLeavingGroup() || isEditingGroup()) && hasNoAnytimeJoin())
|| isModeratorEditingGroup('studyGroups', groupId);
allow delete: if (request.auth != null && resource.data.creatorId == request.auth.uid)
|| isModeratorDeleting('studyGroups', groupId);
match /tasks/{taskId} {
allow read: if true;
allow create: if isVerified() && isGroupMemberOf('studyGroups', groupId)
&& request.resource.data.creatorId == request.auth.uid
&& request.resource.data.isCompleted == false;
allow update: if isVerified() && isGroupMemberOf('studyGroups', groupId);
allow delete: if (isGroupMemberOf('studyGroups', groupId) && resource.data.creatorId == request.auth.uid)
|| isGroupCreatorOf('studyGroups', groupId)
|| isModeratorDeletingPart('studyGroups', groupId, 'tasks', taskId);
}
match /checkIns/{checkInId} {
allow read: if true;
allow create: if isGroupMemberOf('studyGroups', groupId) && isValidNewCheckIn();
allow update: if isEditingOwnCheckIn();
// Lets the creator clear check-ins when deleting the group
allow delete: if isGroupCreatorOf('studyGroups', groupId)
|| isModeratorDeletingPart('studyGroups', groupId, 'checkIns', checkInId);
}
}
match /bookClubs/{bookClubId} {
allow read: if true;
allow create: if canCreateGroup();
allow update: if isJoiningGroup() || isLeavingGroup() || isEditingGroup() || isModeratorEditingGroup('bookClubs', bookClubId);
allow delete: if (request.auth != null && resource.data.creatorId == request.auth.uid)
|| isModeratorDeleting('bookClubs', bookClubId);
match /tasks/{taskId} {
allow read: if true;
allow create: if isVerified() && isGroupMemberOf('bookClubs', bookClubId)
&& request.resource.data.creatorId == request.auth.uid
&& request.resource.data.isCompleted == false;
allow update: if isVerified() && isGroupMemberOf('bookClubs', bookClubId);
allow delete: if (isGroupMemberOf('bookClubs', bookClubId) && resource.data.creatorId == request.auth.uid)
|| isGroupCreatorOf('bookClubs', bookClubId)
|| isModeratorDeletingPart('bookClubs', bookClubId, 'tasks', taskId);
}
match /checkIns/{checkInId} {
allow read: if true;
allow create: if isGroupMemberOf('bookClubs', bookClubId) && isValidNewCheckIn();
allow update: if isEditingOwnCheckIn();
// Lets the creator clear check-ins when deleting the group
allow delete: if isGroupCreatorOf('bookClubs', bookClubId)
|| isModeratorDeletingPart('bookClubs', bookClubId, 'checkIns', checkInId);
}
}
match /groupProjects/{groupProjectId} {
allow read: if true;
allow create: if canCreateGroup() && hasNoAnytimeJoin();
allow update: if ((isJoiningGroup() || isLeavingGroup() || isEditingGroup()) && hasNoAnytimeJoin())
|| isModeratorEditingGroup('groupProjects', groupProjectId);
allow delete: if (request.auth != null && resource.data.creatorId == request.auth.uid)
|| isModeratorDeleting('groupProjects', groupProjectId);
match /tasks/{taskId} {
allow read: if true;
allow create: if isVerified() && isGroupMemberOf('groupProjects', groupProjectId)
&& request.resource.data.creatorId == request.auth.uid
&& request.resource.data.isCompleted == false;
allow update: if isVerified() && isGroupMemberOf('groupProjects', groupProjectId);
allow delete: if (isGroupMemberOf('groupProjects', groupProjectId) && resource.data.creatorId == request.auth.uid)
|| isGroupCreatorOf('groupProjects', groupProjectId)
|| isModeratorDeletingPart('groupProjects', groupProjectId, 'tasks', taskId);
}
match /checkIns/{checkInId} {
allow read: if true;
allow create: if isGroupMemberOf('groupProjects', groupProjectId) && isValidNewCheckIn();
allow update: if isEditingOwnCheckIn();
// Lets the creator clear check-ins when deleting the group
allow delete: if isGroupCreatorOf('groupProjects', groupProjectId)
|| isModeratorDeletingPart('groupProjects', groupProjectId, 'checkIns', checkInId);
}
}
match /meetups/{meetupId} {
allow read: if true;
allow create: if isVerified()
&& request.resource.data.creatorId == request.auth.uid
&& request.resource.data.attendeeIds == [request.auth.uid];
allow update: if isMeetupCreator(meetupId) ||
(isVerified() && request.resource.data.diff(resource.data).affectedKeys().hasOnly(['attendeeIds']) && isAddingSelfToList(request.resource.data.attendeeIds, resource.data.attendeeIds))
|| isModeratorEditing('meetups', meetupId, ['name', 'name_lowercase', 'topic', 'description', 'locationAddress', 'virtualLink']);
allow delete: if isMeetupCreator(meetupId) || isModeratorDeleting('meetups', meetupId);
match /updates/{updateId} {
allow read: if true;
allow create: if isMeetupCreator(meetupId) && request.resource.data.creatorId == request.auth.uid;
allow update: if false;
allow delete: if isModeratorDeletingPart('meetups', meetupId, 'updates', updateId);
}
match /tasks/{taskId} {
// Moderators can list them to delete them with the meetup
allow read: if isMeetupAttendee(meetupId) || isModerator();
allow create: if isVerified() && isMeetupAttendee(meetupId) && request.resource.data.creatorId == request.auth.uid && request.resource.data.isCompleted == false;
allow update: if isMeetupAttendee(meetupId);
allow delete: if (isMeetupAttendee(meetupId) && resource.data.creatorId == request.auth.uid) || isMeetupCreator(meetupId)
|| isModeratorDeletingPart('meetups', meetupId, 'tasks', taskId);
}
match /checkIns/{checkInId} {
allow read: if true;
allow create: if isMeetupAttendee(meetupId) && isValidNewCheckIn();
allow update: if isEditingOwnCheckIn();
allow delete: if isModeratorDeletingPart('meetups', meetupId, 'checkIns', checkInId);
}
}
match /soloProjects/{soloProjectId} {
allow read: if true;
allow create: if isVerified()
&& request.resource.data.userId == request.auth.uid
&& request.resource.data.name is string && request.resource.data.name.size() > 0 && request.resource.data.name.size() <= 100
&& request.resource.data.projectUrl is string && request.resource.data.projectUrl.size() > 0
&& request.resource.data.description is string && request.resource.data.description.size() <= 2000;
allow update: if (request.auth != null && resource.data.userId == request.auth.uid)
|| isModeratorEditing('soloProjects', soloProjectId, ['name', 'description', 'projectUrl']);
allow delete: if (request.auth != null && resource.data.userId == request.auth.uid)
|| isModeratorDeleting('soloProjects', soloProjectId);
// The project owner's to-do list (src/components/TaskList.tsx), public
// like the project
match /tasks/{taskId} {
allow read: if true;
allow create: if isVerified() && isSoloProjectOwner(soloProjectId)
&& request.resource.data.creatorId == request.auth.uid
&& request.resource.data.isCompleted == false;
allow update: if isSoloProjectOwner(soloProjectId);
allow delete: if isSoloProjectOwner(soloProjectId)
|| isModeratorDeletingPart('soloProjects', soloProjectId, 'tasks', taskId);
}
}
function isSoloProjectOwner(soloProjectId) {
return request.auth != null
&& get(/databases/$(database)/documents/soloProjects/$(soloProjectId)).data.userId == request.auth.uid;
}
match /users/{userId}/notifications/{notificationId} {
allow read, write: if isOwner(userId);
}
// A member's private settings, like which notifications they want
// (src/lib/notification-prefs.ts). Only the member can see them.
match /users/{userId}/private/{docId} {
allow read, delete: if isOwner(userId);
allow create, update: if isOwner(userId) && (
(docId == 'notificationPrefs'
&& request.resource.data.keys().hasOnly(['follows', 'groupMembers', 'groupActivity', 'requests', 'following', 'meetingReminders', 'replies', 'mentions', 'messages'])
&& (!('follows' in request.resource.data) || request.resource.data.follows is bool)
&& (!('groupMembers' in request.resource.data) || request.resource.data.groupMembers is bool)
&& (!('groupActivity' in request.resource.data) || request.resource.data.groupActivity is bool)
&& (!('requests' in request.resource.data) || request.resource.data.requests is bool)
&& (!('following' in request.resource.data) || request.resource.data.following is bool)
&& (!('meetingReminders' in request.resource.data) || request.resource.data.meetingReminders is bool)
&& (!('replies' in request.resource.data) || request.resource.data.replies is bool)
&& (!('mentions' in request.resource.data) || request.resource.data.mentions is bool)
&& (!('messages' in request.resource.data) || request.resource.data.messages is bool))
// The feed's followed topics, muted and blocked members (FeedPrefs in src/lib/types.ts)
|| (docId == 'feedPrefs'
&& request.resource.data.keys().hasOnly(['topics', 'mutedIds', 'blockedIds', 'privateAccount'])
&& request.resource.data.get('privateAccount', false) is bool
&& request.resource.data.get('topics', []) is list && request.resource.data.get('topics', []).size() <= 30
&& request.resource.data.get('mutedIds', []) is list && request.resource.data.get('mutedIds', []).size() <= 500
&& request.resource.data.get('blockedIds', []) is list && request.resource.data.get('blockedIds', []).size() <= 500)
);
}
// Each member's activity feed and notifications, written only by the
// server (functions/src). Members can read their own, mark entries
// read or unread, and delete them.
match /users/{userId}/feed/{entryId} {
allow read, delete: if isOwner(userId);
allow create: if false;
allow update: if isOwner(userId)
&& changedKeys().hasOnly(['read'])
&& request.resource.data.read is bool;
}
// ---- Direct messages (/messages), for members 18 and over ----
// A member's birth date, entered once on /messages and never changed,
// so they can't move it to get past the age limit. Only they can read it.
match /ages/{userId} {
allow read: if isOwner(userId);
allow create: if isOwner(userId)
&& request.resource.data.keys().hasOnly(['birthDate', 'confirmedAt'])
&& request.resource.data.birthDate is timestamp
&& request.resource.data.birthDate < request.time
&& request.resource.data.birthDate > timestamp.date(1900, 1, 1)
&& request.resource.data.confirmedAt == request.time;
allow update, delete: if false;
}
// 18 years, counting leap days, have passed since their birth date
function isAdult(userId) {
let agePath = /databases/$(database)/documents/ages/$(userId);
return exists(agePath) && get(agePath).data.birthDate + duration.value(6575, 'd') <= request.time;
}
// Two members can message when both are adults, verified (the sender),
// and neither has blocked the other
function canMessage(otherId) {
return isVerified() && isAdult(request.auth.uid) && isAdult(otherId)
&& !hasBlocked(otherId, request.auth.uid) && !hasBlocked(request.auth.uid, otherId);
}
// A conversation between two members is named "<uid>_<uid>", the two
// uids sorted, so there's one per pair
match /conversations/{conversationId} {
allow read: if request.auth != null && resource.data.memberIds.hasAny([request.auth.uid]);
allow create: if request.auth != null
&& request.resource.data.keys().hasOnly(['memberIds', 'createdAt', 'lastMessageAt', 'lastMessageText', 'lastSenderId', 'readAt'])
&& request.resource.data.memberIds.size() == 2
&& request.resource.data.memberIds.hasAny([request.auth.uid])
&& request.resource.data.memberIds[0] < request.resource.data.memberIds[1]
&& conversationId == request.resource.data.memberIds[0] + '_' + request.resource.data.memberIds[1]
&& canMessage(request.resource.data.memberIds[0] == request.auth.uid ? request.resource.data.memberIds[1] : request.resource.data.memberIds[0])
&& request.resource.data.createdAt == request.time;
// Members update the latest-message preview with each message, and
// when they last read it
allow update: if request.auth != null && resource.data.memberIds.hasAny([request.auth.uid])
&& changedKeys().hasOnly(['lastMessageAt', 'lastMessageText', 'lastSenderId', 'readAt'])
&& (!changedKeys().hasAny(['lastMessageAt', 'lastMessageText', 'lastSenderId'])
|| (request.resource.data.lastSenderId == request.auth.uid && request.resource.data.lastMessageAt == request.time
&& request.resource.data.lastMessageText is string && request.resource.data.lastMessageText.size() <= 140))
&& request.resource.data.get('readAt', {}).keys().hasOnly(resource.data.memberIds)
&& request.resource.data.get('readAt', {}).diff(resource.data.get('readAt', {})).affectedKeys().hasOnly([request.auth.uid]);
allow delete: if false;
match /messages/{messageId} {
allow read: if request.auth != null
&& get(/databases/$(database)/documents/conversations/$(conversationId)).data.memberIds.hasAny([request.auth.uid]);
allow create: if request.auth != null
&& request.resource.data.keys().hasOnly(['senderId', 'text', 'createdAt'])
&& request.resource.data.senderId == request.auth.uid
&& request.resource.data.text is string && request.resource.data.text.size() > 0 && request.resource.data.text.size() <= 2000
&& !hasBlockedWord(request.resource.data.text)
&& request.resource.data.createdAt == request.time
&& !isSuspended(request.auth.uid)
// getAfter: the first message is saved with its conversation
&& getAfter(/databases/$(database)/documents/conversations/$(conversationId)).data.memberIds.hasAny([request.auth.uid])
&& canMessage(conversationId.replace(request.auth.uid, '').replace('_', ''));
allow update: if false;
// Senders can take back their own messages
allow delete: if request.auth != null && resource.data.senderId == request.auth.uid;
}
}
// Private reports about members or their posts
// (src/components/ReportUserButton.tsx). Members can only file them;
// moderators read them on /moderation and close them once handled.
match /reports/{reportId} {
allow read: if isModerator();
allow update: if isModerator()
&& changedKeys().hasOnly(['status', 'closedBy', 'closedAt'])
&& resource.data.status == 'open'
&& request.resource.data.status == 'closed'
&& request.resource.data.closedBy == request.auth.uid