-
Notifications
You must be signed in to change notification settings - Fork 8.9k
Expand file tree
/
Copy pathuser.rb
More file actions
2449 lines (2037 loc) · 71 KB
/
Copy pathuser.rb
File metadata and controls
2449 lines (2037 loc) · 71 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
# frozen_string_literal: true
class User < ActiveRecord::Base
include Searchable
include Roleable
include HasCustomFields
include SecondFactorManager
include HasDestroyedWebHook
include HasDeprecatedColumns
DEFAULT_FEATURED_BADGE_COUNT = 3
MAX_SIMILAR_USERS = 10
STAFF_REASON_SANITIZER = Rails::Html::SafeListSanitizer.new
STAFF_REASON_ALLOWED_TAGS = %w[a br].freeze
STAFF_REASON_ALLOWED_ATTRIBUTES = %w[href rel target].freeze
deprecate_column :flag_level, drop_from: "3.2"
# not deleted on user delete
has_many :posts
has_many :topics
has_many :uploads
has_many :category_users, dependent: :destroy
has_many :tag_users, dependent: :destroy
has_many :user_api_keys, dependent: :destroy
has_many :topic_allowed_users, dependent: :destroy
has_many :user_archived_messages, dependent: :destroy
has_many :email_change_requests, dependent: :destroy
has_many :email_tokens, dependent: :destroy
has_many :topic_links, dependent: :destroy
has_many :user_uploads, dependent: :destroy
has_many :upload_references, as: :target, dependent: :destroy
has_many :user_emails, dependent: :destroy, autosave: true
has_many :user_associated_accounts, dependent: :destroy
has_many :oauth2_user_infos, dependent: :destroy
has_many :user_second_factors, dependent: :destroy
has_many :user_badges, -> { for_enabled_badges }, dependent: :destroy
has_many :user_auth_tokens, dependent: :destroy
has_many :group_users, dependent: :destroy
has_many :user_warnings, dependent: :destroy
has_many :api_keys, dependent: :destroy
has_many :push_subscriptions, dependent: :destroy
has_many :acting_group_histories,
dependent: :destroy,
foreign_key: :acting_user_id,
class_name: "GroupHistory"
has_many :targeted_group_histories,
dependent: :destroy,
foreign_key: :target_user_id,
class_name: "GroupHistory"
has_many :reviewable_scores, dependent: :destroy
has_many :invites, foreign_key: :invited_by_id, dependent: :destroy
has_many :user_custom_fields, dependent: :destroy
has_many :user_associated_groups, dependent: :destroy
has_many :pending_posts,
-> { merge(Reviewable.pending) },
class_name: "ReviewableQueuedPost",
foreign_key: :target_created_by_id
has_one :user_option, dependent: :destroy
has_one :user_avatar, dependent: :destroy
has_one :primary_email,
-> { where(primary: true) },
class_name: "UserEmail",
dependent: :destroy,
autosave: true,
validate: false
has_one :user_stat, dependent: :destroy
has_one :user_profile, dependent: :destroy, inverse_of: :user
has_one :single_sign_on_record, dependent: :destroy
has_one :anonymous_user_master,
class_name: "AnonymousUser",
dependent: :destroy,
strict_loading: false
has_one :anonymous_user_shadow,
->(record) { where(active: true) },
foreign_key: :master_user_id,
class_name: "AnonymousUser",
dependent: :destroy
has_many :anonymous_user_shadows, foreign_key: :master_user_id, class_name: "AnonymousUser"
has_one :invited_user, dependent: :destroy
has_one :user_notification_schedule, dependent: :destroy
has_one :user_password, class_name: "UserPassword", dependent: :destroy, autosave: true
# delete all is faster but bypasses callbacks
has_many :bookmarks, dependent: :delete_all
has_many :notifications, dependent: :delete_all
has_many :topic_users, dependent: :delete_all
has_many :incoming_emails, dependent: :delete_all
has_many :user_visits, dependent: :delete_all
has_many :user_auth_token_logs, dependent: :delete_all
has_many :group_requests, dependent: :delete_all
has_many :muted_user_records, class_name: "MutedUser", dependent: :delete_all
has_many :ignored_user_records, class_name: "IgnoredUser", dependent: :delete_all
has_many :do_not_disturb_timings, dependent: :delete_all
has_many :reviewable_histories, foreign_key: :created_by_id, dependent: :delete_all
has_many :sidebar_sections, dependent: :destroy
has_many :user_histories, foreign_key: :target_user_id
has_one :user_status, dependent: :destroy
# dependent deleting handled via before_destroy (special cases)
has_many :user_actions
has_many :post_actions
has_many :post_timings
has_many :directory_items
has_many :email_logs
has_many :security_keys, -> { where(enabled: true) }, class_name: "UserSecurityKey"
has_many :all_security_keys, class_name: "UserSecurityKey"
has_many :badges, through: :user_badges
has_many :default_featured_user_badges,
-> do
max_featured_rank =
(
if SiteSetting.max_favorite_badges > 0
SiteSetting.max_favorite_badges + 1
else
DEFAULT_FEATURED_BADGE_COUNT
end
)
for_enabled_badges.grouped_with_count.where("featured_rank <= ?", max_featured_rank)
end,
class_name: "UserBadge"
has_many :topics_allowed, through: :topic_allowed_users, source: :topic
has_many :groups, through: :group_users
has_many :secure_categories, -> { distinct }, through: :groups, source: :categories
has_many :associated_groups, through: :user_associated_groups, dependent: :destroy
# deleted in user_second_factors relationship
has_many :totps,
-> { where(method: UserSecondFactor.methods[:totp], enabled: true) },
class_name: "UserSecondFactor"
has_one :master_user, through: :anonymous_user_master
has_one :shadow_user, through: :anonymous_user_shadow, source: :user
has_many :anonymous_shadow_users, through: :anonymous_user_shadows, source: :user
has_one :profile_background_upload, through: :user_profile
has_one :card_background_upload, through: :user_profile
belongs_to :approved_by, class_name: "User"
belongs_to :primary_group, class_name: "Group"
belongs_to :flair_group, class_name: "Group"
has_many :muted_users, through: :muted_user_records
has_many :ignored_users, through: :ignored_user_records
belongs_to :uploaded_avatar, class_name: "Upload"
has_many :sidebar_section_links, dependent: :delete_all
has_many :embeddable_hosts
delegate :last_sent_email_address, to: :email_logs
validates :username, presence: true
validate :username_validator, if: :will_save_change_to_username?
validate :password_validator
validate :name_validator, if: :will_save_change_to_name?
validates :name, user_full_name: true, if: :will_save_change_to_name?, length: { maximum: 255 }
validates :ip_address, allowed_ip_address: { on: :create }
validates :primary_email, presence: true, unless: :skip_email_validation
validates :validatable_user_fields_values,
watched_words: true,
unless: :should_skip_user_fields_validation?
validates_associated :primary_email,
message: ->(_, user_email) do
user_email[:value]&.errors&.[](:email)&.first.to_s
end
after_initialize :add_trust_level
before_validation :set_skip_validate_email
before_save :update_usernames
before_save :match_primary_group_changes
before_save :check_if_title_is_badged_granted
before_save :apply_watched_words, unless: :should_skip_user_fields_validation?
after_create :create_email_token
after_create :create_user_stat
after_create :create_user_option
after_create :create_user_profile
after_create :set_random_avatar
after_create :ensure_in_trust_level_group
after_create :set_default_categories_preferences
after_create :set_default_tags_preferences
after_create :set_default_sidebar_section_links
after_update :set_default_sidebar_section_links, if: Proc.new { saved_change_to_staged? }
after_update :trigger_user_updated_event,
if: Proc.new { human? && saved_change_to_uploaded_avatar_id? }
after_update :trigger_user_automatic_group_refresh, if: :saved_change_to_staged?
after_update :change_display_name, if: :saved_change_to_name?
after_save :expire_tokens_if_password_changed
after_save :clear_global_notice_if_needed
after_save :refresh_avatar
after_save :badge_grant
after_save :index_search
after_save :check_site_contact_username
after_save do
if saved_change_to_uploaded_avatar_id?
UploadReference.ensure_exist!(upload_ids: [uploaded_avatar_id], target: self)
end
end
after_commit :trigger_user_created_event, on: :create
after_commit :trigger_user_destroyed_event, on: :destroy
after_commit :deactivate_anonymous_shadow_users!, on: :update, if: :deactivated?
after_commit :suspend_anonymous_shadow_users!, on: :update, if: :newly_suspended?
before_destroy do
# These tables don't have primary keys, so destroying them with activerecord is tricky:
PostTiming.where(user_id: id).delete_all
TopicViewItem.where(user_id: id).delete_all
UserAction.where(
"user_id = :user_id OR target_user_id = :user_id OR acting_user_id = :user_id",
user_id: id,
).delete_all
# we need to bypass the default scope here, which appears not bypassed for :delete_all
# however :destroy it is bypassed
PostAction.with_deleted.where(user_id: id).delete_all
# This is a perf optimisation to ensure we hit the index
# without this we need to scan a much larger number of rows
DirectoryItem
.where(user_id: id)
.where("period_type in (?)", DirectoryItem.period_types.values)
.delete_all
# our relationship filters on enabled, this makes sure everything is deleted
UserSecurityKey.where(user_id: id).delete_all
Developer.where(user_id: id).delete_all
DraftSequence.where(user_id: id).delete_all
GivenDailyLike.where(user_id: id).delete_all
MutedUser.where(user_id: id).or(MutedUser.where(muted_user_id: id)).delete_all
IgnoredUser.where(user_id: id).or(IgnoredUser.where(ignored_user_id: id)).delete_all
UserAvatar.where(user_id: id).delete_all
end
# Skip validating email, for example from a particular auth provider plugin
attr_accessor :skip_email_validation
# Whether we need to be sending a system message after creation
attr_accessor :send_welcome_message
# This is just used to pass some information into the serializer
attr_accessor :notification_channel_position
# set to true to optimize creation and save for imports
attr_accessor :import_mode
# Cache for user custom fields. Currently it is used to display quick search results
attr_accessor :custom_data
# Information if user was authenticated with OAuth
attr_accessor :authenticated_with_oauth
# Attributes used when admin is impersonating a user
attr_accessor :is_impersonating
attr_accessor :impersonation_expires_at
scope :with_email,
->(email) { joins(:user_emails).where("lower(user_emails.email) IN (?)", email) }
scope :with_primary_email,
->(email) do
joins(:user_emails).where(
"lower(user_emails.email) IN (?) AND user_emails.primary",
email,
)
end
scope :human_users,
->(allowed_bot_user_ids: nil) do
if allowed_bot_user_ids.present?
where("users.id > 0 OR users.id IN (?)", allowed_bot_user_ids)
else
where("users.id > 0")
end
end
# excluding fake users like the system user or anonymous users
scope :real,
->(allowed_bot_user_ids: nil) do
human_users(allowed_bot_user_ids: allowed_bot_user_ids).where(
"NOT EXISTS(
SELECT 1
FROM anonymous_users a
WHERE a.user_id = users.id
)",
)
end
# TODO-PERF: There is no indexes on any of these
# and NotifyMailingListSubscribers does a select-all-and-loop
# may want to create an index on (active, silence, suspended_till)?
scope :silenced, -> { where("silenced_till IS NOT NULL AND silenced_till > ?", Time.zone.now) }
scope :not_silenced, -> { where("silenced_till IS NULL OR silenced_till <= ?", Time.zone.now) }
scope :suspended, -> { where("suspended_till IS NOT NULL AND suspended_till > ?", Time.zone.now) }
scope :not_suspended, -> { where("suspended_till IS NULL OR suspended_till <= ?", Time.zone.now) }
scope :activated, -> { where(active: true) }
scope :not_staged, -> { where(staged: false) }
scope :approved, -> { where(approved: true) }
scope :filter_by_username,
->(filter) do
if filter.is_a?(Array)
where("username_lower ~* ?", "(#{filter.join("|")})")
else
where("username_lower ILIKE ?", "%#{filter}%")
end
end
scope :filter_by_username_or_email,
->(filter) do
if filter.is_a?(String) && filter =~ /.+@.+/
# probably an email so try the bypass
if user_id = UserEmail.where("lower(email) = ?", filter.downcase).pick(:user_id)
return where("users.id = ?", user_id)
end
end
users = joins(:primary_email)
if filter.is_a?(Array)
users.where(
"username_lower ~* :filter OR lower(user_emails.email) SIMILAR TO :filter",
filter: "(#{filter.join("|")})",
)
else
users.where(
"username_lower ILIKE :filter OR lower(user_emails.email) ILIKE :filter",
filter: "%#{filter}%",
)
end
end
scope :watching_topic,
->(topic) do
joins(
DB.sql_fragment(
"LEFT JOIN category_users ON category_users.user_id = users.id AND category_users.category_id = :category_id",
category_id: topic.category_id,
),
)
.joins(
DB.sql_fragment(
"LEFT JOIN topic_users ON topic_users.user_id = users.id AND topic_users.topic_id = :topic_id",
topic_id: topic.id,
),
)
.joins(
"LEFT JOIN tag_users ON tag_users.user_id = users.id AND tag_users.tag_id IN (#{topic.tag_ids.join(",").presence || "NULL"})",
)
.where(
"category_users.notification_level > 0 OR topic_users.notification_level > 0 OR tag_users.notification_level > 0",
)
end
module NewTopicDuration
ALWAYS = -1
LAST_VISIT = -2
end
MAX_STAFF_DELETE_POST_COUNT = 5
def self.user_tips
@user_tips ||=
Enum.new(
first_notification: 1,
topic_timeline: 2,
post_menu: 3,
topic_notification_levels: 4,
suggested_topics: 5,
)
end
def should_skip_user_fields_validation?
custom_fields_clean? || SiteSetting.disable_watched_word_checking_in_user_fields
end
def all_sidebar_sections
sidebar_sections
.or(SidebarSection.public_sections)
.includes(:sidebar_urls)
.order("(section_type IS NOT NULL) DESC, (public IS TRUE) DESC")
end
def secured_sidebar_category_ids(user_guardian = nil)
user_guardian ||= guardian
SidebarSectionLink.where(user_id: id, linkable_type: "Category").pluck(:linkable_id) &
user_guardian.allowed_category_ids
end
def visible_sidebar_tags(user_guardian = nil)
user_guardian ||= guardian
DiscourseTagging.filter_visible(
Tag.where(
id: SidebarSectionLink.where(user_id: id, linkable_type: "Tag").select(:linkable_id),
),
user_guardian,
)
end
def self.max_password_length
UserPassword::MAX_PASSWORD_LENGTH
end
def self.username_length
SiteSetting.min_username_length.to_i..SiteSetting.max_username_length.to_i
end
def self.normalize_username(username)
username.to_s.unicode_normalize.downcase if username.present?
end
def self.username_available?(username, email = nil, allow_reserved_username: false)
lower = normalize_username(username)
return false if !allow_reserved_username && reserved_username?(lower)
return true if !username_exists?(lower)
# staged users can use the same username since they will take over the account
email.present? &&
User.joins(:user_emails).exists?(
staged: true,
username_lower: lower,
user_emails: {
primary: true,
email: email,
},
)
end
def self.reserved_username?(username)
username = normalize_username(username)
return true if SiteSetting.here_mention == username
SiteSetting.reserved_usernames_map.any? do |reserved|
username.match?(/\A#{Regexp.escape(reserved.unicode_normalize).gsub('\*', ".*")}\z/)
end
end
def self.editable_user_custom_fields(by_staff: false)
fields = []
fields.push(*DiscoursePluginRegistry.self_editable_user_custom_fields)
fields.push(*DiscoursePluginRegistry.staff_editable_user_custom_fields) if by_staff
fields.uniq
end
def self.allowed_user_custom_fields(guardian)
fields = []
fields.push(*DiscoursePluginRegistry.public_user_custom_fields)
if SiteSetting.public_user_custom_fields.present?
fields.push(*SiteSetting.public_user_custom_fields.split("|"))
end
if guardian.is_staff?
if SiteSetting.staff_user_custom_fields.present?
fields.push(*SiteSetting.staff_user_custom_fields.split("|"))
end
fields.push(*DiscoursePluginRegistry.staff_user_custom_fields)
end
fields.uniq
end
def self.human_user_id?(user_id)
user_id > 0
end
def human?
User.human_user_id?(id)
end
def bot?
!human?
end
def effective_locale
if SiteSetting.allow_user_locale && locale.present? && I18n.locale_available?(locale)
locale
else
SiteSetting.default_locale
end
end
def bookmarks_of_type(type)
bookmarks.where(bookmarkable_type: type)
end
EMAIL = /([^@]+)@([^\.]+)/
FROM_STAGED = "from_staged"
def self.new_from_params(params)
user = User.new
user.name = params[:name]
user.email = params[:email]
user.password = params[:password]
user.username = params[:username]
user
end
def unstage!
if staged
ActiveRecord::Base.transaction do
self.staged = false
custom_fields[FROM_STAGED] = true
notifications.destroy_all
save!
end
DiscourseEvent.trigger(:user_unstaged, self)
end
end
def self.suggest_name(string)
return "" if string.blank?
(string[/\A[^@]+/].presence || string[/[^@]+\z/]).tr(".", " ").titleize
end
def self.find_by_username_or_email(username_or_email)
if username_or_email.include?("@")
find_by_email(username_or_email)
else
find_by_username(username_or_email)
end
end
def self.find_by_email(email, primary: false)
if primary
with_primary_email(Email.downcase(email)).first
else
with_email(Email.downcase(email)).first
end
end
def self.find_by_username(username)
find_by(username_lower: normalize_username(username))
end
def in_any_groups?(group_ids)
# The :everyone short-circuit means any logged-in user matches a group_list
# containing group id 0. This conflates "all logged-in users" with "everyone
# including anon" and is gated behind the granular pseudogroups upcoming
# change.
everyone_shortcut =
!SiteSetting.granular_anonymous_and_logged_in_groups_permissions &&
group_ids.include?(Group::AUTO_GROUPS[:everyone])
logged_in_shortcut = group_ids.include?(Group::AUTO_GROUPS[:logged_in_users])
return true if everyone_shortcut || logged_in_shortcut
# Sometimes the system user doesn't have their auto groups
# from some strange edge case, this handles it.
if is_system_user? &&
(
(
Group.auto_groups_between(:admins, :trust_level_4) -
[Group::AUTO_GROUPS[:anonymous_users]]
) & group_ids
).any?
return true
end
(group_ids & belonging_to_group_ids).any?
end
def belonging_to_group_ids
@belonging_to_group_ids ||= group_users.pluck(:group_id)
end
def group_granted_trust_level
GroupUser.where(user_id: id).includes(:group).maximum("groups.grant_trust_level")
end
def visible_groups
groups.visible_groups(self)
end
def enqueue_welcome_message(message_type)
return unless SiteSetting.send_welcome_message?
Jobs.enqueue(:send_system_message, user_id: id, message_type: message_type)
end
def enqueue_member_welcome_message
return unless SiteSetting.send_tl1_welcome_message?
Jobs.enqueue(:send_system_message, user_id: id, message_type: "welcome_tl1_user")
end
def enqueue_tl2_promotion_message
return unless SiteSetting.send_tl2_promotion_message
Jobs.enqueue(:send_system_message, user_id: id, message_type: "tl2_promotion_message")
end
def enqueue_staff_welcome_message(role)
return unless staff?
return if is_singular_admin?
Jobs.enqueue(
:send_system_message,
user_id: id,
message_type: "welcome_staff",
message_options: {
role: role.to_s,
},
)
end
def change_username(new_username, actor = nil)
UsernameChanger.change(self, new_username, actor)
end
def created_topic_count
stat.topic_count
end
alias_method :topic_count, :created_topic_count
# tricky, we need our bus to be subscribed from the right spot
def sync_notification_channel_position
@unread_notifications_by_type = nil
self.notification_channel_position = MessageBus.last_id("/notification/#{id}")
end
def invited_by
# this is unfortunate, but when an invite is redeemed,
# any user created by the invite is created *after*
# the invite's redeemed_at
invite_redemption_delay = 5.seconds
used_invite =
Invite
.with_deleted
.joins(:invited_users)
.where(
"invited_users.user_id = ? AND invited_users.redeemed_at <= ?",
id,
created_at + invite_redemption_delay,
)
.first
used_invite.try(:invited_by)
end
def should_validate_email_address?
!skip_email_validation && !staged?
end
def self.email_hash(email)
Digest::MD5.hexdigest(email.strip.downcase)
end
def email_hash
User.email_hash(email)
end
def reload(options = nil)
@unread_notifications = nil
@all_unread_notifications_count = nil
@unread_total_notifications = nil
@unread_pms = nil
@unread_bookmarks = nil
@unread_high_prios = nil
@ignored_user_ids = nil
@muted_user_ids = nil
@belonging_to_group_ids = nil
super
end
def ignored_user_ids
@ignored_user_ids ||= ignored_users.pluck(:id)
end
def muted_user_ids
@muted_user_ids ||= muted_users.pluck(:id)
end
def unread_notifications_of_type(notification_type, since: nil)
# perf critical, much more efficient than AR
sql = <<~SQL
SELECT COUNT(*)
FROM notifications n
LEFT JOIN topics t ON t.id = n.topic_id
WHERE t.deleted_at IS NULL
AND n.notification_type = :notification_type
AND n.user_id = :user_id
AND NOT read
#{since ? "AND n.created_at > :since" : ""}
SQL
# to avoid coalesce we do to_i
DB.query_single(sql, user_id: id, notification_type: notification_type, since: since)[0].to_i
end
def unread_notifications_of_priority(high_priority:)
# perf critical, much more efficient than AR
sql = <<~SQL
SELECT COUNT(*)
FROM notifications n
LEFT JOIN topics t ON t.id = n.topic_id
WHERE t.deleted_at IS NULL
AND n.high_priority = :high_priority
AND n.user_id = :user_id
AND NOT read
SQL
# to avoid coalesce we do to_i
DB.query_single(sql, user_id: id, high_priority: high_priority)[0].to_i
end
MAX_UNREAD_BACKLOG = 400
def grouped_unread_notifications
results = DB.query(<<~SQL, user_id: id, limit: MAX_UNREAD_BACKLOG)
SELECT X.notification_type AS type, COUNT(*) FROM (
SELECT n.notification_type
FROM notifications n
LEFT JOIN topics t ON t.id = n.topic_id
WHERE t.deleted_at IS NULL
AND n.user_id = :user_id
AND NOT n.read
LIMIT :limit
) AS X
GROUP BY X.notification_type
SQL
results.map! { |row| [row.type, row.count] }
results.to_h
end
def unread_high_priority_notifications
@unread_high_prios ||= unread_notifications_of_priority(high_priority: true)
end
def new_personal_messages_notifications_count
args = {
user_id: id,
seen_notification_id: seen_notification_id,
private_message: Notification.types[:private_message],
}
DB.query_single(<<~SQL, args).first
SELECT COUNT(*)
FROM notifications
WHERE user_id = :user_id
AND id > :seen_notification_id
AND NOT read
AND notification_type = :private_message
SQL
end
# PERF: This safeguard is in place to avoid situations where
# a user with enormous amounts of unread data can issue extremely
# expensive queries
MAX_UNREAD_NOTIFICATIONS = 99
def self.max_unread_notifications
@max_unread_notifications ||= MAX_UNREAD_NOTIFICATIONS
end
def self.max_unread_notifications=(val)
@max_unread_notifications = val
end
def unread_notifications
@unread_notifications ||=
begin
# perf critical, much more efficient than AR
sql = <<~SQL
SELECT COUNT(*) FROM (
SELECT 1 FROM
notifications n
LEFT JOIN topics t ON t.id = n.topic_id
WHERE t.deleted_at IS NULL AND
n.high_priority = FALSE AND
n.user_id = :user_id AND
n.id > :seen_notification_id AND
NOT read
LIMIT :limit
) AS X
SQL
DB.query_single(
sql,
user_id: id,
seen_notification_id: seen_notification_id,
limit: User.max_unread_notifications,
)[
0
].to_i
end
end
def all_unread_notifications_count
@all_unread_notifications_count ||=
begin
sql = <<~SQL
SELECT COUNT(*) FROM (
SELECT 1 FROM
notifications n
LEFT JOIN topics t ON t.id = n.topic_id
WHERE t.deleted_at IS NULL AND
n.user_id = :user_id AND
n.id > :seen_notification_id AND
NOT read
LIMIT :limit
) AS X
SQL
DB.query_single(
sql,
user_id: id,
seen_notification_id: seen_notification_id,
limit: User.max_unread_notifications,
)[
0
].to_i
end
end
def total_unread_notifications
@unread_total_notifications ||= notifications.where("read = false").count
end
def reviewable_count
Reviewable.list_for(self, include_claimed_by_others: false).count
end
def bump_last_seen_notification!
query = notifications.visible
query = query.where("notifications.id > ?", seen_notification_id) if seen_notification_id
if max_notification_id = query.maximum(:id)
update!(seen_notification_id: max_notification_id)
true
else
false
end
end
def bump_last_seen_reviewable!
query = Reviewable.unseen_list_for(self, preload: false)
query = query.where("reviewables.id > ?", last_seen_reviewable_id) if last_seen_reviewable_id
max_reviewable_id = query.maximum(:id)
if max_reviewable_id
update!(last_seen_reviewable_id: max_reviewable_id)
publish_reviewable_counts
end
end
def publish_reviewable_counts(extra_data = nil)
data = {
reviewable_count: reviewable_count,
unseen_reviewable_count: Reviewable.unseen_reviewable_count(self),
}
data.merge!(extra_data) if extra_data.present?
MessageBus.publish("/reviewable_counts/#{id}", data, user_ids: [id])
end
def read_first_notification?
seen_notification_id != 0 || user_option.skip_new_user_tips
end
def publish_notifications_state
return if !allow_live_notifications?
# publish last notification json with the message so we can apply an update
notification = notifications.visible.order("notifications.created_at desc").first
json = NotificationSerializer.new(notification).as_json if notification
sql = <<~SQL
SELECT * FROM (
SELECT n.id, n.read FROM notifications n
LEFT JOIN topics t ON n.topic_id = t.id
WHERE
t.deleted_at IS NULL AND
n.high_priority AND
n.user_id = :user_id AND
NOT read
ORDER BY n.id DESC
LIMIT 20
) AS x
UNION ALL
SELECT * FROM (
SELECT n.id, n.read FROM notifications n
LEFT JOIN topics t ON n.topic_id = t.id
WHERE
t.deleted_at IS NULL AND
(n.high_priority = FALSE OR read) AND
n.user_id = :user_id
ORDER BY n.id DESC
LIMIT 20
) AS y
SQL
recent = DB.query(sql, user_id: id).map! { |r| [r.id, r.read] }
payload = {
unread_notifications: unread_notifications,
unread_high_priority_notifications: unread_high_priority_notifications,
read_first_notification: read_first_notification?,
last_notification: json,
recent: recent,
seen_notification_id: seen_notification_id,
}
payload[:all_unread_notifications_count] = all_unread_notifications_count
payload[:grouped_unread_notifications] = grouped_unread_notifications
payload[:new_personal_messages_notifications_count] = new_personal_messages_notifications_count
MessageBus.publish("/notification/#{id}", payload, user_ids: [id])
end
def publish_do_not_disturb(ends_at: nil)
MessageBus.publish("/do-not-disturb/#{id}", { ends_at: ends_at&.httpdate }, user_ids: [id])
end
def publish_user_status(status)
if status
payload = {
description: status.description,
emoji: status.emoji,
ends_at: status.ends_at&.iso8601,
}
else
payload = nil
end
if Guardian.new.can_see_user_status?(self)
MessageBus.publish(
"/user-status",
{ id => payload },
group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
)
elsif guardian.can_see_user_status?(self)
MessageBus.publish(
"/user-status",
{ id => payload },
user_ids: [id],
group_ids: [Group::AUTO_GROUPS[:staff]],
)
end
end
def password=(pw)
# special case for passwordless accounts
return if pw.blank?
if user_password
user_password.password = pw
else
build_user_password(password: pw)
end
@raw_password = pw # still required to maintain compatibility with usage of password-related User interface
end
def can_remove_password?
associated_accounts.present? || passkey_credential_ids.present?
end
def remove_password
raise Discourse::InvalidAccess if !can_remove_password?
user_password.destroy if user_password
end
def password
"" # so that validator doesn't complain that a password attribute doesn't exist
end
def password_hash
Discourse.deprecate(
"User#password_hash is deprecated, use UserPassword#password_hash instead.",
drop_from: "3.3",
raise_error: false,
)
user_password&.password_hash
end
def password_algorithm
Discourse.deprecate(
"User#password_algorithm is deprecated, use UserPassword#password_algorithm instead.",
drop_from: "3.3",
raise_error: false,
)
user_password&.password_algorithm
end
def salt