Class: UsersController
Constant Summary
collapse
- MAX_RECENT_SEARCHES =
5
- SEARCH_USERS_LIMIT =
50
- AVATAR_TYPES_WITH_UPLOAD =
%w[uploaded custom gravatar]
- BOOKMARKS_LIMIT =
20
20
ApplicationController::CHALLENGE_KEY, ApplicationController::HONEYPOT_KEY, ApplicationController::LEGACY_NO_THEMES, ApplicationController::LEGACY_NO_UNOFFICIAL_PLUGINS, ApplicationController::NO_PLUGINS, ApplicationController::NO_THEMES, ApplicationController::NO_UNOFFICIAL_PLUGINS, ApplicationController::SAFE_MODE
CanonicalURL::ControllerExtensions::ALLOWED_CANONICAL_PARAMS
Instance Attribute Summary
#theme_id
Instance Method Summary
collapse
#application_layout, #can_cache_content?, #clear_notifications, #conditionally_allow_site_embedding, #current_homepage, #discourse_expires_in, #dont_cache_page, #ember_cli_required?, #fetch_user_from_params, #guardian, #handle_permalink, #handle_theme, #handle_unverified_request, #has_escaped_fragment?, #immutable_for, #login_method, #no_cookies, #perform_refresh_session, #post_ids_including_replies, #preload_json, #rate_limit_second_factor!, #redirect_with_client_support, #render_json_dump, #render_serialized, requires_plugin, #rescue_discourse_actions, #resolve_safe_mode, #secure_session, #serialize_data, #set_current_user_for_logs, #set_layout, #set_mobile_view, #set_mp_snapshot_fields, #show_browser_update?, #store_preloaded, #use_crawler_layout?, #with_resolved_locale
Methods included from VaryHeader
#ensure_vary_header
resolve_theme_id
#add_readonly_header, #allowed_in_staff_writes_only_mode?, #block_if_readonly_mode, #check_readonly_mode, #get_or_check_readonly_mode, #get_or_check_staff_writes_only_mode, included, #staff_writes_only_mode?
Methods included from Hijack
#hijack
Methods included from GlobalPath
#cdn_path, #cdn_relative_path, #full_cdn_url, #path, #upload_cdn_path
Methods included from JsonError
#create_errors_json
#canonical_url, #default_canonical, included
#clear_current_user, #current_user, has_auth_cookie?, #is_api?, #is_user_api?, #log_off_user, #log_on_user, lookup_from_env, #refresh_session
Instance Method Details
#account_created ⇒ Object
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
|
# File 'app/controllers/users_controller.rb', line 1073
def account_created
if current_user.present?
if SiteSetting.enable_discourse_connect_provider && payload = cookies.delete(:sso_payload)
return redirect_to(session_sso_provider_url + "?" + payload)
elsif destination_url = cookies.delete(:destination_url)
return redirect_to(destination_url, allow_other_host: true)
else
return redirect_to(path("/"))
end
end
@custom_body_class = "static-account-created"
@message = session["user_created_message"] || I18n.t("activation.missing_session")
@account_created = { message: @message, show_controls: false }
if session_user_id = session[SessionController::ACTIVATE_USER_KEY]
if user = User.where(id: session_user_id.to_i).first
@account_created[:username] = user.username
@account_created[:email] = user.email
@account_created[:show_controls] = !user.from_staged?
end
end
store_preloaded("accountCreated", MultiJson.dump(@account_created))
expires_now
respond_to do |format|
format.html { render "default/empty" }
format.json { render json: success_json }
end
end
|
#activate_account ⇒ Object
1105
1106
1107
1108
1109
1110
1111
1112
|
# File 'app/controllers/users_controller.rb', line 1105
def activate_account
expires_now
respond_to do |format|
format.html { render "default/empty" }
format.json { render json: success_json }
end
end
|
#admin_login ⇒ Object
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
|
# File 'app/controllers/users_controller.rb', line 992
def admin_login
return redirect_to(path("/")) if current_user
if request.put? && params[:email].present?
RateLimiter.new(nil, "admin-login-hr-#{request.remote_ip}", 6, 1.hour).performed!
RateLimiter.new(nil, "admin-login-min-#{request.remote_ip}", 3, 1.minute).performed!
if user = User.with_email(params[:email]).admins.human_users.first
email_token =
user.email_tokens.create!(email: user.email, scope: EmailToken.scopes[:email_login])
token_string = email_token.token
token_string += "?safe_mode=no_plugins,no_themes" if params["use_safe_mode"]
Jobs.enqueue(
:critical_user_email,
type: "admin_login",
user_id: user.id,
email_token: token_string,
)
@message = I18n.t("admin_login.success")
else
@message = I18n.t("admin_login.errors.unknown_email_address")
end
end
render layout: "no_ember"
rescue RateLimiter::LimitExceeded
@message = I18n.t("rate_limiter.slow_down")
render layout: "no_ember"
end
|
#badge_title ⇒ Object
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
|
# File 'app/controllers/users_controller.rb', line 433
def badge_title
params.require(:user_badge_id)
user = fetch_user_from_params
guardian.ensure_can_edit!(user)
user_badge = UserBadge.find_by(id: params[:user_badge_id])
previous_title = user.title
if user_badge && user_badge.user == user && user_badge.badge.allow_title?
user.title = user_badge.badge.display_name
user.save!
log_params = {
details: "title matching badge id #{user_badge.badge.id}",
previous_value: previous_title,
new_value: user.title,
}
if current_user.staff? && current_user != user
StaffActionLogger.new(current_user).log_title_change(user, log_params)
else
UserHistory.create!(
log_params.merge(target_user_id: user.id, action: UserHistory.actions[:change_title]),
)
end
else
user.title = ""
user.save!
log_params = { previous_value: previous_title }
if current_user.staff? && current_user != user
StaffActionLogger.new(current_user).log_title_revoke(
user,
log_params.merge(
revoke_reason: "user title was same as revoked badge name or custom badge name",
),
)
else
UserHistory.create!(
log_params.merge(target_user_id: user.id, action: UserHistory.actions[:revoke_title]),
)
end
end
render body: nil
end
|
#badges ⇒ Object
196
197
198
199
|
# File 'app/controllers/users_controller.rb', line 196
def badges
raise Discourse::NotFound unless SiteSetting.enable_badges?
show
end
|
#bookmarks ⇒ Object
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
|
# File 'app/controllers/users_controller.rb', line 1859
def bookmarks
user = fetch_user_from_params
guardian.ensure_can_edit!(user)
user_guardian = Guardian.new(user)
respond_to do |format|
format.json do
bookmark_list =
UserBookmarkList.new(
user: user,
guardian: guardian,
search_term: params[:q],
page: params[:page],
per_page: fetch_limit_from_params(default: nil, max: BOOKMARKS_LIMIT),
)
bookmark_list.load
if bookmark_list.bookmarks.empty?
render json: { bookmarks: [] }
else
page = params[:page].to_i + 1
bookmark_list.more_bookmarks_url =
"#{Discourse.base_path}/u/#{params[:username]}/bookmarks.json?page=#{page}"
render_serialized(bookmark_list, UserBookmarkListSerializer)
end
end
format.ics do
@bookmark_reminders =
Bookmark
.with_reminders
.where(user_id: user.id)
.order(:reminder_at)
.map do |bookmark|
bookmark.registered_bookmarkable.serializer.new(
bookmark,
scope: user_guardian,
root: false,
)
end
end
end
end
|
#cards ⇒ Object
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
|
# File 'app/controllers/users_controller.rb', line 166
def cards
guardian.ensure_public_can_see_profiles!
user_ids = params.require(:user_ids).split(",").map(&:to_i)
raise Discourse::InvalidParameters.new(:user_ids) if user_ids.length > 50
users =
User.where(id: user_ids).includes(
:user_option,
:user_stat,
:default_featured_user_badges,
:user_profile,
:card_background_upload,
:primary_group,
:flair_group,
:primary_email,
:user_status,
)
users = users.filter { |u| guardian.can_see_profile?(u) }
preload_fields =
User.allowed_user_custom_fields(guardian) +
UserField.all.pluck(:id).map { |fid| "#{User::USER_FIELD_PREFIX}#{fid}" }
User.preload_custom_fields(users, preload_fields)
User.preload_recent_time_read(users)
render json: users, each_serializer: UserCardSerializer
end
|
#changing_case_of_own_username(target_user, username) ⇒ Object
599
600
601
|
# File 'app/controllers/users_controller.rb', line 599
def changing_case_of_own_username(target_user, username)
target_user && username.downcase == (target_user.username.downcase)
end
|
#check_confirmed_session ⇒ Object
#check_email ⇒ Object
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
|
# File 'app/controllers/users_controller.rb', line 622
def check_email
begin
RateLimiter.new(nil, "check-email-#{request.remote_ip}", 10, 1.minute).performed!
rescue RateLimiter::LimitExceeded
return render json: success_json
end
email = Email.downcase((params[:email] || "").strip)
return render json: success_json if email.blank? || SiteSetting.hide_email_address_taken?
if !EmailAddressValidator.valid_value?(email)
error = User.new.errors.full_message(:email, I18n.t(:"user.email.invalid"))
return render json: failed_json.merge(errors: [error])
end
if !EmailValidator.allowed?(email)
error = User.new.errors.full_message(:email, I18n.t(:"user.email.not_allowed"))
return render json: failed_json.merge(errors: [error])
end
if ScreenedEmail.should_block?(email)
error = User.new.errors.full_message(:email, I18n.t(:"user.email.blocked"))
return render json: failed_json.merge(errors: [error])
end
if User.where(staged: false).find_by_email(email).present?
error = User.new.errors.full_message(:email, I18n.t(:"errors.messages.taken"))
return render json: failed_json.merge(errors: [error])
end
render json: success_json
end
|
#check_emails ⇒ Object
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
|
# File 'app/controllers/users_controller.rb', line 294
def check_emails
user = fetch_user_from_params(include_inactive: true)
unless user == current_user
guardian.ensure_can_check_emails!(user)
StaffActionLogger.new(current_user).log_check_email(user, context: params[:context])
end
email, *secondary_emails = user.emails
unconfirmed_emails = user.unconfirmed_emails
render json: {
email: email,
secondary_emails: secondary_emails,
unconfirmed_emails: unconfirmed_emails,
associated_accounts: user.associated_accounts,
}
rescue Discourse::InvalidAccess
render json: failed_json, status: 403
end
|
#check_sso_email ⇒ Object
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
|
# File 'app/controllers/users_controller.rb', line 315
def check_sso_email
user = fetch_user_from_params(include_inactive: true)
unless user == current_user
guardian.ensure_can_check_sso_details!(user)
StaffActionLogger.new(current_user).log_check_email(user, context: params[:context])
end
email = user&.single_sign_on_record&.external_email
email = I18n.t("user.email.does_not_exist") if email.blank?
render json: { email: email }
rescue Discourse::InvalidAccess
render json: failed_json, status: 403
end
|
#check_sso_payload ⇒ Object
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
|
# File 'app/controllers/users_controller.rb', line 331
def check_sso_payload
user = fetch_user_from_params(include_inactive: true)
guardian.ensure_can_check_sso_details!(user)
unless user == current_user
StaffActionLogger.new(current_user).log_check_email(user, context: params[:context])
end
payload = user&.single_sign_on_record&.last_payload
payload = I18n.t("user.email.does_not_exist") if payload.blank?
render json: { payload: payload }
rescue Discourse::InvalidAccess
render json: failed_json, status: 403
end
|
#check_username ⇒ Object
Used for checking availability of a username and will return suggestions if the username is not available.
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
|
# File 'app/controllers/users_controller.rb', line 605
def check_username
if !params[:username].present?
params.require(:username) if !params[:email].present?
return render(json: success_json)
end
username = params[:username]&.unicode_normalize
target_user = user_from_params_or_current_user
return render_available_true if changing_case_of_own_username(target_user, username)
checker = UsernameCheckerService.new
email = params[:email] || target_user.try(:email)
render json: checker.check_username(username, email)
end
|
#clear_featured_topic ⇒ Object
1850
1851
1852
1853
1854
1855
|
# File 'app/controllers/users_controller.rb', line 1850
def clear_featured_topic
user = fetch_user_from_params
guardian.ensure_can_edit!(user)
user.user_profile.update(featured_topic_id: nil)
render json: success_json
end
|
#confirm_admin ⇒ Object
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
|
# File 'app/controllers/users_controller.rb', line 1516
def confirm_admin
@confirmation = AdminConfirmation.find_by_code(params[:token])
raise Discourse::NotFound unless @confirmation
unless @confirmation.performed_by.id == (current_user&.id || @confirmation.performed_by.id)
raise Discourse::InvalidAccess.new
end
if request.post?
@confirmation.email_confirmed!
@confirmed = true
end
respond_to do |format|
format.json { render json: success_json }
format.html { render layout: "no_ember" }
end
end
|
#confirm_email_token ⇒ Object
972
973
974
975
976
|
# File 'app/controllers/users_controller.rb', line 972
def confirm_email_token
expires_now
EmailToken.confirm(params[:token], scope: EmailToken.scopes[:signup])
render json: success_json
end
|
#confirm_session ⇒ Object
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
|
# File 'app/controllers/users_controller.rb', line 1535
def confirm_session
if SiteSetting.enable_discourse_connect || !SiteSetting.enable_local_logins
raise Discourse::NotFound
end
if confirm_secure_session
render json: success_json
else
render json: failed_json.merge(error: I18n.t("login.incorrect_password_or_passkey"))
end
rescue ::DiscourseWebauthn::SecurityKeyError => err
render_json_error(err.message, status: 401)
end
|
#create ⇒ Object
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
|
# File 'app/controllers/users_controller.rb', line 660
def create
params.require(:email)
params.require(:username)
params.require(:invite_code) if SiteSetting.require_invite_code
params.permit(:user_fields)
params.permit(:external_ids)
if SiteSetting.enable_discourse_connect && !is_api?
return fail_with("login.new_registrations_disabled_discourse_connect")
end
return fail_with("login.new_registrations_disabled") unless SiteSetting.allow_new_registrations
if params[:password] && params[:password].length > User.max_password_length
return fail_with("login.password_too_long")
end
return fail_with("login.email_too_long") if params[:email].length > 254 + 1 + 253
if SiteSetting.require_invite_code &&
SiteSetting.invite_code.strip.downcase != params[:invite_code].strip.downcase
return fail_with("login.wrong_invite_code")
end
if clashing_with_existing_route?(params[:username]) ||
User.reserved_username?(params[:username])
return fail_with("login.reserved_username")
end
params[:locale] ||= I18n.locale unless current_user
new_user_params = user_params.except(:timezone)
user = User.where(staged: true).with_email(new_user_params[:email].strip.downcase).first
if user
user.active = false
user.unstage!
end
user ||= User.new
user.attributes = new_user_params
if user.approved? || EmailValidator.can_auto_approve_user?(user.email)
ReviewableUser.set_approved_fields!(user, current_user)
end
user_fields = UserField.all
if user_fields.present?
field_params = params[:user_fields] || {}
fields = user.custom_fields
user_fields.each do |f|
field_val = field_params[f.id.to_s]
if field_val.blank?
return fail_with("login.missing_user_field") if f.required?
else
fields["#{User::USER_FIELD_PREFIX}#{f.id}"] = field_val[0...UserField.max_length]
end
end
user.custom_fields = fields
end
associations = []
if params[:external_ids].is_a?(ActionController::Parameters) && current_user&.admin? && is_api?
params[:external_ids].each do |provider_name, provider_uid|
authenticator = Discourse.enabled_authenticators.find { |a| a.name == provider_name }
raise Discourse::InvalidParameters.new(:external_ids) if !authenticator&.is_managed?
association =
UserAssociatedAccount.find_or_initialize_by(
provider_name: provider_name,
provider_uid: provider_uid,
)
associations << association
end
end
authentication = UserAuthenticator.new(user, session)
if !authentication.has_authenticator? && !SiteSetting.enable_local_logins &&
!(current_user&.admin? && is_api?)
return render body: nil, status: :forbidden
end
authentication.start
if authentication.email_valid? && !authentication.authenticated?
return fail_with("login.incorrect_username_email_or_password")
end
activation = UserActivator.new(user, request, session, cookies)
activation.start
user.password = SecureRandom.hex if user.password.blank? &&
(authentication.has_authenticator? || associations.present?)
if user.save
authentication.finish
activation.finish
associations.each { |a| a.update!(user: user) }
user.update_timezone_if_missing(params[:timezone])
secure_session[HONEYPOT_KEY] = nil
secure_session[CHALLENGE_KEY] = nil
session["user_created_message"] = activation.message
session[SessionController::ACTIVATE_USER_KEY] = user.id
user.activate if user.active?
render json: { success: true, active: user.active?, message: activation.message }.merge(
SiteSetting.hide_email_address_taken ? {} : { user_id: user.id },
)
elsif SiteSetting.hide_email_address_taken &&
user.errors[:primary_email]&.include?(I18n.t("errors.messages.taken"))
session["user_created_message"] = activation.success_message
existing_user = User.find_by_email(user.primary_email&.email)
if !existing_user && SiteSetting.normalize_emails
existing_user =
UserEmail.find_by_normalized_email(user.primary_email&.normalized_email)&.user
end
if existing_user
Jobs.enqueue(:critical_user_email, type: "account_exists", user_id: existing_user.id)
end
render json: { success: true, active: false, message: activation.success_message }
else
errors = user.errors.to_hash
errors[:email] = errors.delete(:primary_email) if errors[:primary_email]
render json: {
success: false,
message: I18n.t("login.errors", errors: user.errors.full_messages.join("\n")),
errors: errors,
values: {
name: user.name,
username: user.username,
email: user.primary_email&.email,
},
is_developer: UsernameCheckerService.is_developer?(user.email),
}
end
rescue ActiveRecord::StatementInvalid
render json: { success: false, message: I18n.t("login.something_already_taken") }
end
|
#create_second_factor_backup ⇒ Object
1580
1581
1582
1583
1584
|
# File 'app/controllers/users_controller.rb', line 1580
def create_second_factor_backup
backup_codes = current_user.generate_backup_codes
render json: success_json.merge(backup_codes: backup_codes)
end
|
#create_second_factor_security_key ⇒ Object
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
|
# File 'app/controllers/users_controller.rb', line 1600
def create_second_factor_security_key
if current_user.all_security_keys.count >= UserSecurityKey::MAX_KEYS_PER_USER
render_json_error(I18n.t("login.too_many_security_keys"), status: 422)
return
end
challenge_session = DiscourseWebauthn.stage_challenge(current_user, secure_session)
render json:
success_json.merge(
challenge: challenge_session.challenge,
rp_id: DiscourseWebauthn.rp_id,
rp_name: DiscourseWebauthn.rp_name,
supported_algorithms: ::DiscourseWebauthn::SUPPORTED_ALGORITHMS,
user_secure_id: current_user.create_or_fetch_secure_identifier,
existing_active_credential_ids:
current_user.second_factor_security_key_credential_ids,
)
end
|
#create_second_factor_totp ⇒ Object
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
|
# File 'app/controllers/users_controller.rb', line 1586
def create_second_factor_totp
require "rotp" if !defined?(ROTP)
totp_data = ROTP::Base32.random
secure_session["staged-totp-#{current_user.id}"] = totp_data
qrcode_png =
RQRCode::QRCode.new(current_user.totp_provisioning_uri(totp_data)).as_png(
border_modules: 1,
size: 240,
)
render json:
success_json.merge(key: totp_data.scan(/.{4}/).join(" "), qr: qrcode_png.to_data_url)
end
|
#delete_passkey ⇒ Object
1670
1671
1672
1673
1674
1675
1676
|
# File 'app/controllers/users_controller.rb', line 1670
def delete_passkey
raise Discourse::NotFound unless SiteSetting.enable_passkeys
current_user.security_keys.find_by(id: params[:id].to_i)&.destroy!
render json: success_json
end
|
#destroy ⇒ Object
1404
1405
1406
1407
1408
1409
1410
1411
|
# File 'app/controllers/users_controller.rb', line 1404
def destroy
@user = fetch_user_from_params
guardian.ensure_can_delete_user!(@user)
UserDestroyer.new(current_user).destroy(@user, delete_posts: true, context: params[:context])
render json: success_json
end
|
#destroy_email ⇒ Object
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
|
# File 'app/controllers/users_controller.rb', line 380
def destroy_email
return render json: failed_json, status: 410 if !SiteSetting.enable_secondary_emails
params.require(:email)
user = fetch_user_from_params
guardian.ensure_can_edit!(user)
ActiveRecord::Base.transaction do
if change_requests = user.email_change_requests.where(new_email: params[:email]).presence
change_requests.destroy_all
elsif user.user_emails.where(email: params[:email], primary: false).destroy_all.present?
DiscourseEvent.trigger(:user_updated, user)
else
return render json: failed_json, status: 428
end
if current_user.staff? && current_user != user
StaffActionLogger.new(current_user).log_destroy_email(user)
else
UserHistory.create(action: UserHistory.actions[:destroy_email], acting_user_id: user.id)
end
end
render json: success_json
end
|
#destroy_user_image ⇒ Object
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
|
# File 'app/controllers/users_controller.rb', line 1388
def destroy_user_image
user = fetch_user_from_params
guardian.ensure_can_edit!(user)
case params.require(:type)
when "profile_background"
user.user_profile.clear_profile_background
when "card_background"
user.user_profile.clear_card_background
else
raise Discourse::InvalidParameters.new(:type)
end
render json: success_json
end
|
#disable_second_factor ⇒ Object
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
|
# File 'app/controllers/users_controller.rb', line 1729
def disable_second_factor
current_user.user_second_factors.destroy_all
current_user.second_factor_security_keys.destroy_all
Jobs.enqueue(
:critical_user_email,
type: "account_second_factor_disabled",
user_id: current_user.id,
)
render json: success_json
end
|
#email_login ⇒ Object
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
|
# File 'app/controllers/users_controller.rb', line 1022
def email_login
raise Discourse::NotFound if !SiteSetting.enable_local_logins_via_email
return redirect_to path("/") if current_user
expires_now
params.require(:login)
RateLimiter.new(nil, "email-login-hour-#{request.remote_ip}", 6, 1.hour).performed!
RateLimiter.new(nil, "email-login-min-#{request.remote_ip}", 3, 1.minute).performed!
user = User.human_users.find_by_username_or_email(params[:login])
user_presence = user.present? && !user.staged
if user
RateLimiter.new(nil, "email-login-hour-#{user.id}", 6, 1.hour).performed!
RateLimiter.new(nil, "email-login-min-#{user.id}", 3, 1.minute).performed!
if user_presence
DiscourseEvent.trigger(:before_email_login, user)
email_token =
user.email_tokens.create!(email: user.email, scope: EmailToken.scopes[:email_login])
Jobs.enqueue(
:critical_user_email,
type: "email_login",
user_id: user.id,
email_token: email_token.token,
)
end
end
json = success_json
json[:hide_taken] = SiteSetting.hide_email_address_taken
json[:user_found] = user_presence unless SiteSetting.hide_email_address_taken
render json: json
rescue RateLimiter::LimitExceeded
render_json_error(I18n.t("rate_limiter.slow_down"))
end
|
#enable_second_factor_totp ⇒ Object
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
|
# File 'app/controllers/users_controller.rb', line 1701
def enable_second_factor_totp
if params[:second_factor_token].blank?
return render json: failed_json.merge(error: I18n.t("login.missing_second_factor_code"))
end
if params[:name].blank?
return render json: failed_json.merge(error: I18n.t("login.missing_second_factor_name"))
end
auth_token = params[:second_factor_token]
totp_data = secure_session["staged-totp-#{current_user.id}"]
totp_object = current_user.get_totp_object(totp_data)
rate_limit_second_factor!(current_user)
authenticated =
!auth_token.blank? &&
totp_object.verify(
auth_token,
drift_ahead: SecondFactorManager::TOTP_ALLOWED_DRIFT_SECONDS,
drift_behind: SecondFactorManager::TOTP_ALLOWED_DRIFT_SECONDS,
)
unless authenticated
return render json: failed_json.merge(error: I18n.t("login.invalid_second_factor_code"))
end
current_user.create_totp(data: totp_data, name: params[:name], enabled: true)
render json: success_json
end
|
#feature_topic ⇒ Object
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
|
# File 'app/controllers/users_controller.rb', line 1833
def feature_topic
user = fetch_user_from_params
topic = Topic.find(params[:topic_id].to_i)
if !guardian.can_feature_topic?(user, topic)
return(
render_json_error(
I18n.t("activerecord.errors.models.user_profile.attributes.featured_topic_id.invalid"),
403,
)
)
end
user.user_profile.update(featured_topic_id: topic.id)
render json: success_json
end
|
#index ⇒ Object
114
115
|
# File 'app/controllers/users_controller.rb', line 114
def index
end
|
#invited ⇒ Object
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
|
# File 'app/controllers/users_controller.rb', line 531
def invited
if guardian.can_invite_to_forum?
filter = params[:filter] || "redeemed"
inviter =
fetch_user_from_params(
include_inactive: current_user.staff? || SiteSetting.show_inactive_accounts,
)
invites =
if filter == "pending" && guardian.can_see_invite_details?(inviter)
Invite.includes(:topics, :groups).pending(inviter)
elsif filter == "expired"
Invite.expired(inviter)
elsif filter == "redeemed"
Invite.redeemed_users(inviter)
else
Invite.none
end
invites = invites.offset(params[:offset].to_i || 0).limit(SiteSetting.invites_per_page)
show_emails = guardian.can_see_invite_emails?(inviter)
if params[:search].present? && invites.present?
filter_sql = "(LOWER(users.username) LIKE :filter)"
filter_sql =
"(LOWER(invites.email) LIKE :filter) or (LOWER(users.username) LIKE :filter)" if show_emails
invites = invites.where(filter_sql, filter: "%#{params[:search].downcase}%")
end
pending_count = Invite.pending(inviter).reorder(nil).count.to_i
expired_count = Invite.expired(inviter).reorder(nil).count.to_i
redeemed_count = Invite.redeemed_users(inviter).reorder(nil).count.to_i
render json:
MultiJson.dump(
InvitedSerializer.new(
OpenStruct.new(
invite_list: invites.to_a,
show_emails: show_emails,
inviter: inviter,
type: filter,
counts: {
pending: pending_count,
expired: expired_count,
redeemed: redeemed_count,
total: pending_count + expired_count,
},
),
scope: guardian,
root: false,
),
)
elsif current_user&.staff?
message =
if SiteSetting.enable_discourse_connect
I18n.t("invite.disabled_errors.discourse_connect_enabled")
end
render_invite_error(message)
else
render_json_error(I18n.t("invite.disabled_errors.invalid_access"))
end
end
|
#list_second_factors ⇒ Object
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
|
# File 'app/controllers/users_controller.rb', line 1553
def list_second_factors
if SiteSetting.enable_discourse_connect || !SiteSetting.enable_local_logins
raise Discourse::NotFound
end
if secure_session_confirmed?
totp_second_factors =
current_user
.totps
.select(:id, :name, :last_used, :created_at, :method)
.where(enabled: true)
.order(:created_at)
.as_json(only: %i[id name method last_used])
security_keys =
current_user
.security_keys
.where(factor_type: UserSecurityKey.factor_types[:second_factor])
.order(:created_at)
.as_json(only: %i[id user_id credential_id public_key factor_type enabled name last_used])
render json: success_json.merge(totps: totp_second_factors, security_keys: security_keys)
else
render json: success_json.merge(unconfirmed_session: true)
end
end
|
#logon_after_password_reset ⇒ Object
978
979
980
981
982
983
984
985
986
987
988
989
990
|
# File 'app/controllers/users_controller.rb', line 978
def logon_after_password_reset
message =
if Guardian.new(@user).can_access_forum?
log_on_user(@user)
"password_reset.success"
else
@requires_approval = true
"password_reset.success_unapproved"
end
@success = I18n.t(message)
end
|
#my_redirect ⇒ Object
485
486
487
488
489
490
491
492
493
494
|
# File 'app/controllers/users_controller.rb', line 485
def my_redirect
raise Discourse::NotFound if params[:path] !~ %r{\A[a-z_\-/]+\z}
if current_user.blank?
cookies[:destination_url] = path("/my/#{params[:path]}")
redirect_to path("/login-preferences")
else
redirect_to(path("/u/#{current_user.encoded_username}/#{params[:path]}"))
end
end
|
#notification_level ⇒ Object
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
|
# File 'app/controllers/users_controller.rb', line 1413
def notification_level
target_user = fetch_user_from_params
acting_user = current_user
if params[:acting_user_id].present? && params[:acting_user_id].to_i != current_user.id
if current_user.staff?
acting_user = User.find(params[:acting_user_id])
else
@error_message = "error"
raise Discourse::InvalidAccess
end
end
if params[:notification_level] == "ignore"
@error_message = "ignore_error"
guardian.ensure_can_ignore_user!(target_user)
MutedUser.where(user: acting_user, muted_user: target_user).delete_all
ignored_user = IgnoredUser.find_by(user: acting_user, ignored_user: target_user)
if ignored_user.present?
ignored_user.update(expiring_at: DateTime.parse(params[:expiring_at]))
else
IgnoredUser.create!(
user: acting_user,
ignored_user: target_user,
expiring_at: Time.parse(params[:expiring_at]),
)
end
elsif params[:notification_level] == "mute"
@error_message = "mute_error"
guardian.ensure_can_mute_user!(target_user)
IgnoredUser.where(user: acting_user, ignored_user: target_user).delete_all
MutedUser.find_or_create_by!(user: acting_user, muted_user: target_user)
elsif params[:notification_level] == "normal"
MutedUser.where(user: acting_user, muted_user: target_user).delete_all
IgnoredUser.where(user: acting_user, ignored_user: target_user).delete_all
else
return(
render_json_error(
I18n.t("notification_level.invalid_value", value: params[:notification_level]),
)
)
end
render json: success_json
rescue Discourse::InvalidAccess
render_json_error(I18n.t("notification_level.#{@error_message}"))
end
|
#password_reset_show ⇒ Object
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
|
# File 'app/controllers/users_controller.rb', line 819
def password_reset_show
expires_now
token = params[:token]
password_reset_find_user(token, committing_change: false)
if !@error
security_params = {
is_developer: UsernameCheckerService.is_developer?(@user.email),
admin: @user.admin?,
second_factor_required: @user.totp_enabled?,
security_key_required: @user.security_keys_enabled?,
backup_enabled: @user.backup_codes_enabled?,
multiple_second_factor_methods: @user.has_multiple_second_factor_methods?,
}
end
respond_to do |format|
format.html do
return render "password_reset", layout: "no_ember" if @error
DiscourseWebauthn.stage_challenge(@user, secure_session)
store_preloaded(
"password_reset",
MultiJson.dump(
security_params.merge(DiscourseWebauthn.allowed_credentials(@user, secure_session)),
),
)
render "password_reset"
end
format.json do
return render json: { message: @error } if @error
DiscourseWebauthn.stage_challenge(@user, secure_session)
render json:
security_params.merge(DiscourseWebauthn.allowed_credentials(@user, secure_session))
end
end
end
|
#password_reset_update ⇒ Object
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
|
# File 'app/controllers/users_controller.rb', line 861
def password_reset_update
expires_now
token = params[:token]
password_reset_find_user(token, committing_change: true)
rate_limit_second_factor!(@user)
if @user
raise Discourse::ReadOnly if staff_writes_only_mode? && !@user.staff?
if !secure_session["second-factor-#{token}"]
second_factor_authentication_result =
@user.authenticate_second_factor(params, secure_session)
if !second_factor_authentication_result.ok
user_error_key =
(
if second_factor_authentication_result.reason == "invalid_security_key"
:user_second_factors
else
:security_keys
end
)
@user.errors.add(user_error_key, :invalid)
@error = second_factor_authentication_result.error
else
secure_session["second-factor-#{token}"] = true
end
end
if @invalid_password =
params[:password].blank? || params[:password].size > User.max_password_length
@user.errors.add(:password, :invalid)
end
if @user.errors.empty?
@user.update_timezone_if_missing(params[:timezone]) if params[:timezone]
@user.password = params[:password]
@user.password_required!
@user.user_auth_tokens.destroy_all
if @user.save
Invite.invalidate_for_email(@user.email) secure_session["password-#{token}"] = nil
secure_session["second-factor-#{token}"] = nil
if SiteSetting.delete_associated_accounts_on_password_reset
@user.user_associated_accounts.destroy_all
end
UserHistory.create!(
target_user: @user,
acting_user: @user,
action: UserHistory.actions[:change_password],
)
logon_after_password_reset
end
end
end
respond_to do |format|
format.html do
return render "password_reset", layout: "no_ember" if @error
DiscourseWebauthn.stage_challenge(@user, secure_session)
security_params = {
is_developer: UsernameCheckerService.is_developer?(@user.email),
admin: @user.admin?,
second_factor_required: @user.totp_enabled?,
security_key_required: @user.security_keys_enabled?,
backup_enabled: @user.backup_codes_enabled?,
multiple_second_factor_methods: @user.has_multiple_second_factor_methods?,
}.merge(DiscourseWebauthn.allowed_credentials(@user, secure_session))
store_preloaded("password_reset", MultiJson.dump(security_params))
return redirect_to(wizard_path) if Wizard.user_requires_completion?(@user)
render "password_reset"
end
format.json do
if @error || @user&.errors&.any?
render json: {
success: false,
message: @error,
errors: @user&.errors&.to_hash,
friendly_messages: @user&.errors&.full_messages,
is_developer: UsernameCheckerService.is_developer?(@user&.email),
admin: @user&.admin?,
}
else
render json: {
success: true,
message: @success,
requires_approval: !Guardian.new(@user).can_access_forum?,
redirect_to: Wizard.user_requires_completion?(@user) ? wizard_path : nil,
}
end
end
end
end
|
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
|
# File 'app/controllers/users_controller.rb', line 1114
def perform_account_activation
raise Discourse::InvalidAccess.new if honeypot_or_challenge_fails?(params)
if @user = EmailToken.confirm(params[:token], scope: EmailToken.scopes[:signup])
if Guardian.new(@user).can_access_forum?
@user.enqueue_welcome_message("welcome_user") if @user.send_welcome_message
log_on_user(@user)
destination_url = cookies.delete(:destination_url)
if destination_url.blank?
topic =
Invite
.joins(:invited_users)
.find_by(invited_users: { user_id: @user.id })
&.topics
&.first
destination_url = path(topic.relative_url) if @user.guardian.can_see?(topic)
end
if Wizard.user_requires_completion?(@user)
@redirect_to = wizard_path
elsif destination_url.present?
@redirect_to = destination_url
elsif SiteSetting.enable_discourse_connect_provider &&
payload = cookies.delete(:sso_payload)
@redirect_to = session_sso_provider_url + "?" + payload
end
else
@needs_approval = true
end
else
return render_json_error(I18n.t("activation.already_done"))
end
render json:
success_json.merge(redirect_to: @redirect_to, needs_approval: @needs_approval || false)
end
|
#pick_avatar ⇒ Object
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
|
# File 'app/controllers/users_controller.rb', line 1308
def pick_avatar
user = fetch_user_from_params
guardian.ensure_can_edit!(user)
return render json: failed_json, status: 422 if SiteSetting.discourse_connect_overrides_avatar
type = params[:type]
invalid_type = type.present? && !AVATAR_TYPES_WITH_UPLOAD.include?(type) && type != "system"
return render json: failed_json, status: 422 if invalid_type
if type.blank? || type == "system"
upload_id = nil
elsif !user.in_any_groups?(SiteSetting.uploaded_avatars_allowed_groups_map) &&
!user.is_system_user?
return render json: failed_json, status: 422
else
upload_id = params[:upload_id]
upload = Upload.find_by(id: upload_id)
return render_json_error I18n.t("avatar.missing") if upload.nil?
user.create_user_avatar unless user.user_avatar
guardian.ensure_can_pick_avatar!(user.user_avatar, upload)
if type == "gravatar"
user.user_avatar.gravatar_upload_id = upload_id
else
user.user_avatar.custom_upload_id = upload_id
end
end
SiteSetting.use_site_small_logo_as_system_avatar = false if user.is_system_user?
user.uploaded_avatar_id = upload_id
user.save!
user.user_avatar.save!
render json: success_json
end
|
#preferences ⇒ Object
481
482
483
|
# File 'app/controllers/users_controller.rb', line 481
def preferences
render body: nil
end
|
#private_message_topic_tracking_state ⇒ Object
#profile_hidden ⇒ Object
496
497
498
|
# File 'app/controllers/users_controller.rb', line 496
def profile_hidden
render nothing: true
end
|
#read_faq ⇒ Object
1464
1465
1466
1467
1468
1469
1470
1471
|
# File 'app/controllers/users_controller.rb', line 1464
def read_faq
if user = current_user
user.user_stat.read_faq = 1.second.ago
user.user_stat.save
end
render json: success_json
end
|
#recent_searches ⇒ Object
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
|
# File 'app/controllers/users_controller.rb', line 1473
def recent_searches
if !SiteSetting.log_search_queries
return(
render json: failed_json.merge(error: I18n.t("user_activity.no_log_search_queries")),
status: 403
)
end
query = SearchLog.where(user_id: current_user.id)
if current_user.user_option.oldest_search_log_date
query = query.where("created_at > ?", current_user.user_option.oldest_search_log_date)
end
results =
query.group(:term).order("max(created_at) DESC").limit(MAX_RECENT_SEARCHES).pluck(:term)
render json: success_json.merge(recent_searches: results)
end
|
#register_passkey ⇒ Object
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
|
# File 'app/controllers/users_controller.rb', line 1650
def register_passkey
raise Discourse::NotFound unless SiteSetting.enable_passkeys
params.require(:name)
params.require(:attestation)
params.require(:clientData)
key =
::DiscourseWebauthn::RegistrationService.new(
current_user,
params,
session: secure_session,
factor_type: UserSecurityKey.factor_types[:first_factor],
).register_security_key
render json: success_json.merge(id: key.id, name: key.name)
rescue ::DiscourseWebauthn::SecurityKeyError => err
render_json_error(err.message, status: 401)
end
|
#register_second_factor_security_key ⇒ Object
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
|
# File 'app/controllers/users_controller.rb', line 1619
def register_second_factor_security_key
params.require(:name)
params.require(:attestation)
params.require(:clientData)
::DiscourseWebauthn::RegistrationService.new(
current_user,
params,
session: secure_session,
factor_type: UserSecurityKey.factor_types[:second_factor],
).register_security_key
render json: success_json
rescue ::DiscourseWebauthn::SecurityKeyError => err
render json: failed_json.merge(error: err.message)
end
|
#rename_passkey ⇒ Object
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
|
# File 'app/controllers/users_controller.rb', line 1678
def rename_passkey
raise Discourse::NotFound unless SiteSetting.enable_passkeys
params.require(:id)
params.require(:name)
passkey = current_user.security_keys.find_by(id: params[:id].to_i)
raise Discourse::InvalidParameters.new(:id) unless passkey
passkey.update!(name: params[:name])
render json: success_json
end
|
#render_available_true ⇒ Object
595
596
597
|
# File 'app/controllers/users_controller.rb', line 595
def render_available_true
render(json: { available: true })
end
|
#reset_recent_searches ⇒ Object
1493
1494
1495
1496
|
# File 'app/controllers/users_controller.rb', line 1493
def reset_recent_searches
current_user.user_option.update!(oldest_search_log_date: 1.second.ago)
render json: success_json
end
|
#revoke_account ⇒ Object
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
|
# File 'app/controllers/users_controller.rb', line 1786
def revoke_account
user = fetch_user_from_params
guardian.ensure_can_edit!(user)
provider_name = params.require(:provider_name)
authenticator = Discourse.authenticators.find { |a| a.name == provider_name }
raise Discourse::NotFound if authenticator.nil? || !authenticator.can_revoke?
skip_remote = params.permit(:skip_remote)
hijack do
DiscourseEvent.trigger(:before_auth_revoke, authenticator, user)
result = authenticator.revoke(user, skip_remote: skip_remote)
if result
render json: success_json
else
render json: {
success: false,
message: I18n.t("associated_accounts.revoke_failed", provider_name: provider_name),
}
end
end
end
|
#revoke_auth_token ⇒ Object
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
|
# File 'app/controllers/users_controller.rb', line 1813
def revoke_auth_token
user = fetch_user_from_params
guardian.ensure_can_edit!(user)
if params[:token_id]
token = UserAuthToken.find_by(id: params[:token_id], user_id: user.id)
if !token || guardian.auth_token == token.auth_token
raise Discourse::InvalidParameters.new(:token_id)
end
UserAuthToken.where(id: params[:token_id], user_id: user.id).each(&:destroy!)
MessageBus.publish "/file-change", ["refresh"], user_ids: [user.id]
else
UserAuthToken.where(user_id: user.id).each(&:destroy!)
end
render json: success_json
end
|
#search_users ⇒ Object
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
|
# File 'app/controllers/users_controller.rb', line 1227
def search_users
term = params[:term].to_s.strip
usernames = params[:usernames]&.split(",")&.map { |username| username.downcase.strip }
topic_id = params[:topic_id].to_i if params[:topic_id].present?
category_id = params[:category_id].to_i if params[:category_id].present?
topic_allowed_users = params[:topic_allowed_users] || false
group_names = params[:groups] || []
group_names << params[:group] if params[:group]
@groups = Group.where(name: group_names) if group_names.present?
options = {
topic_allowed_users: topic_allowed_users,
searching_user: current_user,
groups: @groups,
}
options[:include_staged_users] = !!ActiveModel::Type::Boolean.new.cast(
params[:include_staged_users],
)
options[:last_seen_users] = !!ActiveModel::Type::Boolean.new.cast(params[:last_seen_users])
if limit = fetch_limit_from_params(default: nil, max: SEARCH_USERS_LIMIT)
options[:limit] = limit
end
options[:topic_id] = topic_id if topic_id
options[:category_id] = category_id if category_id
results =
if usernames.blank?
UserSearch.new(term, options).search
else
User.where(username_lower: usernames).includes(:user_option).limit(limit)
end
to_render = serialize_found_users(results)
groups =
if (term.present? || usernames.present?) && current_user
if params[:include_groups] == "true"
Group.visible_groups(current_user)
elsif params[:include_mentionable_groups] == "true"
Group.mentionable(current_user)
elsif params[:include_messageable_groups] == "true"
Group.messageable(current_user)
end
end
if groups
DiscoursePluginRegistry
.groups_callback_for_users_search_controller_action
.each do |param_name, block|
groups = block.call(groups, current_user) if params[param_name.to_s]
end
groups = DiscoursePluginRegistry.apply_modifier(:groups_for_users_search, groups)
groups =
if usernames.blank?
Group.search_groups(term, groups: groups, sort: :auto)
else
groups.where(name: usernames).limit(limit)
end
to_render[:groups] = groups.map { |m| { name: m.name, full_name: m.full_name } }
end
render json: to_render
end
|
#select_avatar ⇒ Object
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
|
# File 'app/controllers/users_controller.rb', line 1351
def select_avatar
user = fetch_user_from_params
guardian.ensure_can_edit!(user)
url = params[:url]
return render json: failed_json, status: 422 if url.blank?
if SiteSetting.selectable_avatars_mode == "disabled"
return render json: failed_json, status: 422
end
return render json: failed_json, status: 422 if SiteSetting.selectable_avatars.blank?
unless upload = Upload.get_from_url(url)
return render json: failed_json, status: 422
end
return render json: failed_json, status: 422 if SiteSetting.selectable_avatars.exclude?(upload)
user.uploaded_avatar_id = upload.id
SiteSetting.use_site_small_logo_as_system_avatar = false if user.is_system_user?
user.save!
avatar = user.user_avatar || user.create_user_avatar
avatar.custom_upload_id = upload.id
avatar.save!
render json: {
avatar_template: user.avatar_template,
custom_avatar_template: user.avatar_template,
uploaded_avatar_id: upload.id,
}
end
|
#send_activation_email ⇒ Object
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
|
# File 'app/controllers/users_controller.rb', line 1197
def send_activation_email
if current_user.blank? || !current_user.staff?
RateLimiter.new(nil, "activate-hr-#{request.remote_ip}", 30, 1.hour).performed!
RateLimiter.new(nil, "activate-min-#{request.remote_ip}", 6, 1.minute).performed!
end
raise Discourse::InvalidAccess.new if SiteSetting.must_approve_users?
@user = User.find_by_username_or_email(params[:username].to_s) if params[:username].present?
raise Discourse::NotFound unless @user
if !current_user&.staff? && @user.id != session[SessionController::ACTIVATE_USER_KEY]
raise Discourse::InvalidAccess.new
end
session.delete(SessionController::ACTIVATE_USER_KEY)
if @user.active && @user.email_confirmed?
render_json_error(I18n.t("activation.activated"), status: 409)
else
@email_token =
@user.email_tokens.create!(email: @user.email, scope: EmailToken.scopes[:signup])
EmailToken.enqueue_signup_email(@email_token, to_address: @user.email)
render body: nil
end
end
|
#show(for_card: false) ⇒ Object
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
|
# File 'app/controllers/users_controller.rb', line 117
def show(for_card: false)
guardian.ensure_public_can_see_profiles!
@user =
fetch_user_from_params(
include_inactive: current_user&.staff? || for_card || SiteSetting.show_inactive_accounts,
)
user_serializer = nil
if !current_user&.staff? && !@user.active?
user_serializer = InactiveUserSerializer.new(@user, scope: guardian, root: "user")
elsif !guardian.can_see_profile?(@user)
user_serializer = HiddenProfileSerializer.new(@user, scope: guardian, root: "user")
else
serializer_class = for_card ? UserCardSerializer : UserSerializer
user_serializer = serializer_class.new(@user, scope: guardian, root: "user")
topic_id = params[:include_post_count_for].to_i
if topic_id != 0 && guardian.can_see?(Topic.find_by_id(topic_id))
user_serializer.topic_post_count = {
topic_id => Post.secured(guardian).where(topic_id: topic_id, user_id: @user.id).count,
}
end
end
track_visit_to_user_profile if !params[:skip_track_visit] && (@user != current_user)
if params[:external_id] && params[:external_id].ends_with?(".json")
return render_json_dump(user_serializer)
end
respond_to do |format|
format.html do
@restrict_fields = guardian.restrict_user_fields?(@user)
store_preloaded("user_#{@user.username}", MultiJson.dump(user_serializer))
render :show
end
format.json { render_json_dump(user_serializer) }
end
end
|
#show_card ⇒ Object
161
162
163
|
# File 'app/controllers/users_controller.rb', line 161
def show_card
show(for_card: true)
end
|
#staff_info ⇒ Object
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
|
# File 'app/controllers/users_controller.rb', line 1498
def staff_info
@user = fetch_user_from_params(include_inactive: true)
guardian.ensure_can_see_staff_info!(@user)
result = {}
%W[
number_of_deleted_posts
number_of_flagged_posts
number_of_flags_given
number_of_suspensions
warnings_received_count
number_of_rejected_posts
].each { |info| result[info] = @user.public_send(info) }
render json: result
end
|
#summary ⇒ Object
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
|
# File 'app/controllers/users_controller.rb', line 500
def summary
guardian.ensure_public_can_see_profiles!
@user =
fetch_user_from_params(
include_inactive:
current_user.try(:staff?) || (current_user && SiteSetting.show_inactive_accounts),
)
raise Discourse::NotFound unless guardian.can_see_profile?(@user)
response.["X-Robots-Tag"] = "noindex"
respond_to do |format|
format.html do
@restrict_fields = guardian.restrict_user_fields?(@user)
render :show
end
format.json do
summary_json =
Discourse
.cache
.fetch(summary_cache_key(@user), expires_in: 1.hour) do
summary = UserSummary.new(@user, guardian)
serializer = UserSummarySerializer.new(summary, scope: guardian)
MultiJson.dump(serializer)
end
render json: summary_json
end
end
end
|
#toggle_anon ⇒ Object
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
|
# File 'app/controllers/users_controller.rb', line 1061
def toggle_anon
user =
AnonymousShadowCreator.get_master(current_user) || AnonymousShadowCreator.get(current_user)
if user
log_on_user(user)
render json: success_json
else
render json: failed_json, status: 403
end
end
|
#topic_tracking_state ⇒ Object
407
408
409
410
411
412
413
414
415
|
# File 'app/controllers/users_controller.rb', line 407
def topic_tracking_state
user = fetch_user_from_params
guardian.ensure_can_edit!(user)
report = TopicTrackingState.report(user)
serializer = TopicTrackingStateSerializer.new(report, scope: guardian, root: false)
render json: MultiJson.dump(serializer.as_json[:data])
end
|
#trusted_session ⇒ Object
1549
1550
1551
|
# File 'app/controllers/users_controller.rb', line 1549
def trusted_session
render json: secure_session_confirmed? || user_just_created ? success_json : failed_json
end
|
#update ⇒ Object
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
|
# File 'app/controllers/users_controller.rb', line 201
def update
user = fetch_user_from_params
guardian.ensure_can_edit!(user)
attributes = user_params.except(:username, :email, :password)
if params[:user_fields].present?
attributes[:custom_fields] ||= {}
fields = UserField.all
fields = fields.where(editable: true) unless current_user.staff?
fields.each do |field|
field_id = field.id.to_s
next unless params[:user_fields].has_key?(field_id)
value = clean_custom_field_values(field)
value = nil if value === "false"
value = value[0...UserField.max_length] if value
if value.blank? &&
(
field.for_all_users? ||
field.on_signup? &&
user.custom_fields["#{User::USER_FIELD_PREFIX}#{field_id}"].present?
)
return render_json_error(I18n.t("login.missing_user_field"))
end
attributes[:custom_fields]["#{User::USER_FIELD_PREFIX}#{field.id}"] = value
end
end
if params[:external_ids].is_a?(ActionController::Parameters) && current_user&.admin? && is_api?
attributes[:user_associated_accounts] = []
params[:external_ids].each do |provider_name, provider_uid|
if provider_name == "discourse_connect"
unless SiteSetting.enable_discourse_connect
raise Discourse::InvalidParameters.new(:external_ids)
end
attributes[:discourse_connect] = { external_id: provider_uid }
next
end
authenticator = Discourse.enabled_authenticators.find { |a| a.name == provider_name }
raise Discourse::InvalidParameters.new(:external_ids) if !authenticator&.is_managed?
attributes[:user_associated_accounts] << {
provider_name: provider_name,
provider_uid: provider_uid,
}
end
end
json_result(
user,
serializer: UserSerializer,
additional_errors: %i[user_profile user_option],
) do |u|
updater = UserUpdater.new(current_user, user)
updater.update(attributes.permit!)
end
end
|
#update_activation_email ⇒ Object
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
|
# File 'app/controllers/users_controller.rb', line 1159
def update_activation_email
RateLimiter.new(nil, "activate-edit-email-hr-#{request.remote_ip}", 5, 1.hour).performed!
if params[:username].present?
RateLimiter.new(
nil,
"activate-edit-email-hr-username-#{params[:username]}",
5,
1.hour,
).performed!
@user = User.find_by_username_or_email(params[:username])
raise Discourse::InvalidAccess.new if @user.blank?
raise Discourse::InvalidAccess.new unless @user.confirm_password?(params[:password])
elsif user_key = session[SessionController::ACTIVATE_USER_KEY]
RateLimiter.new(nil, "activate-edit-email-hr-user-key-#{user_key}", 5, 1.hour).performed!
@user = User.where(id: user_key.to_i).first
end
if @user.blank? || @user.active? || current_user.present? || @user.from_staged?
raise Discourse::InvalidAccess.new
end
User.transaction do
primary_email = @user.primary_email
primary_email.email = params[:email]
primary_email.skip_validate_email = false
if primary_email.save
@email_token =
@user.email_tokens.create!(email: @user.email, scope: EmailToken.scopes[:signup])
EmailToken.enqueue_signup_email(@email_token, to_address: @user.email)
render json: success_json
else
render_json_error(primary_email)
end
end
end
|
#update_primary_email ⇒ Object
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
|
# File 'app/controllers/users_controller.rb', line 347
def update_primary_email
return render json: failed_json, status: 410 if !SiteSetting.enable_secondary_emails
params.require(:email)
user = fetch_user_from_params
guardian.ensure_can_edit_email!(user)
old_primary = user.primary_email
return render json: success_json if old_primary.email == params[:email]
new_primary = user.user_emails.find_by(email: params[:email])
if new_primary.blank?
return(
render json: failed_json.merge(errors: [I18n.t("change_email.doesnt_exist")]), status: 428
)
end
User.transaction do
old_primary.update!(primary: false)
new_primary.update!(primary: true)
DiscourseEvent.trigger(:user_updated, user)
if current_user.staff? && current_user != user
StaffActionLogger.new(current_user).log_update_email(user)
else
UserHistory.create!(action: UserHistory.actions[:update_email], acting_user_id: user.id)
end
end
render json: success_json
end
|
#update_second_factor ⇒ Object
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
|
# File 'app/controllers/users_controller.rb', line 1743
def update_second_factor
params.require(:second_factor_target)
update_second_factor_method = params[:second_factor_target].to_i
if update_second_factor_method == UserSecondFactor.methods[:totp]
params.require(:id)
second_factor_id = params[:id].to_i
user_second_factor = current_user.user_second_factors.totps.find_by(id: second_factor_id)
elsif update_second_factor_method == UserSecondFactor.methods[:backup_codes]
user_second_factor = current_user.user_second_factors.backup_codes
end
raise Discourse::InvalidParameters unless user_second_factor
user_second_factor.update!(name: params[:name]) if params[:name] && !params[:name].blank?
if params[:disable] == "true"
if update_second_factor_method == UserSecondFactor.methods[:backup_codes]
current_user
.user_second_factors
.where(method: UserSecondFactor.methods[:backup_codes])
.destroy_all
else
user_second_factor.update!(enabled: false)
end
end
render json: success_json
end
|
#update_security_key ⇒ Object
1691
1692
1693
1694
1695
1696
1697
1698
1699
|
# File 'app/controllers/users_controller.rb', line 1691
def update_security_key
user_security_key = current_user.security_keys.find_by(id: params[:id].to_i)
raise Discourse::InvalidParameters unless user_security_key
user_security_key.update!(name: params[:name]) if params[:name] && !params[:name].blank?
user_security_key.update!(enabled: false) if params[:disable] == "true"
render json: success_json
end
|
#user_from_params_or_current_user ⇒ Object
656
657
658
|
# File 'app/controllers/users_controller.rb', line 656
def user_from_params_or_current_user
params[:for_user_id] ? User.find(params[:for_user_id]) : current_user
end
|
#user_just_created ⇒ Object
1773
1774
1775
|
# File 'app/controllers/users_controller.rb', line 1773
def user_just_created
current_user.created_at > 5.minutes.ago
end
|
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
|
# File 'app/controllers/users_controller.rb', line 1904
def
if !current_user.username_equals_to?(params[:username])
raise Discourse::InvalidAccess.new("username doesn't match current_user's username")
end
reminder_notifications =
BookmarkQuery.new(user: current_user).unread_notifications(limit: USER_MENU_LIST_LIMIT)
if reminder_notifications.size < USER_MENU_LIST_LIMIT
exclude_bookmark_ids =
reminder_notifications.filter_map { |notification| notification.data_hash[:bookmark_id] }
bookmark_list =
UserBookmarkList.new(
user: current_user,
guardian: guardian,
per_page: USER_MENU_LIST_LIMIT - reminder_notifications.size,
)
bookmark_list.load do |query|
if exclude_bookmark_ids.present?
query.where("bookmarks.id NOT IN (?)", exclude_bookmark_ids)
end
end
end
if reminder_notifications.present?
if SiteSetting.
Notification.populate_acting_user(reminder_notifications)
end
serialized_notifications =
ActiveModel::ArraySerializer.new(
reminder_notifications,
each_serializer: NotificationSerializer,
scope: guardian,
)
end
if bookmark_list
bookmark_list.bookmark_serializer_opts = { link_to_first_unread_post: true }
serialized_bookmarks =
serialize_data(bookmark_list, UserBookmarkListSerializer, scope: guardian, root: false)[
:bookmarks
]
end
render json: {
notifications: serialized_notifications || [],
bookmarks: serialized_bookmarks || [],
}
end
|
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
|
# File 'app/controllers/users_controller.rb', line 1955
def
if !current_user.username_equals_to?(params[:username])
raise Discourse::InvalidAccess.new("username doesn't match current_user's username")
end
if !current_user.staff? &&
!current_user.in_any_groups?(SiteSetting.personal_message_enabled_groups_map)
raise Discourse::InvalidAccess.new("personal messages are disabled.")
end
unread_notifications =
Notification
.(current_user.id, limit: USER_MENU_LIST_LIMIT)
.unread
.where(
notification_type: [
Notification.types[:private_message],
Notification.types[:group_message_summary],
],
)
.to_a
if unread_notifications.size < USER_MENU_LIST_LIMIT
exclude_topic_ids = unread_notifications.filter_map(&:topic_id).uniq
limit = USER_MENU_LIST_LIMIT - unread_notifications.size
messages_list =
TopicQuery
.new(current_user, per_page: limit)
.list_private_messages_direct_and_groups(
current_user,
groups_messages_notification_level: :watching,
) do |query|
if exclude_topic_ids.present?
query.where("topics.id NOT IN (?)", exclude_topic_ids)
else
query
end
end
read_notifications =
Notification
.(current_user.id, limit: limit)
.where(read: true, notification_type: Notification.types[:group_message_summary])
.to_a
end
if unread_notifications.present?
Notification.populate_acting_user(unread_notifications) if SiteSetting.
serialized_unread_notifications =
ActiveModel::ArraySerializer.new(
unread_notifications,
each_serializer: NotificationSerializer,
scope: guardian,
)
end
if messages_list
serialized_messages =
serialize_data(messages_list, TopicListSerializer, scope: guardian, root: false)[:topics]
serialized_users =
if SiteSetting.
users = messages_list.topics.map { |t| t.posters.last.user }.flatten.compact.uniq(&:id)
serialize_data(users, BasicUserSerializer, scope: guardian, root: false)
else
[]
end
end
if read_notifications.present?
Notification.populate_acting_user(read_notifications) if SiteSetting.
serialized_read_notifications =
ActiveModel::ArraySerializer.new(
read_notifications,
each_serializer: NotificationSerializer,
scope: guardian,
)
end
render json: {
unread_notifications: serialized_unread_notifications || [],
read_notifications: serialized_read_notifications || [],
topics: serialized_messages || [],
users: serialized_users || [],
}
end
|
#username ⇒ Object
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
|
# File 'app/controllers/users_controller.rb', line 268
def username
params.require(:new_username)
if clashing_with_existing_route?(params[:new_username]) ||
User.reserved_username?(params[:new_username])
return render_json_error(I18n.t("login.reserved_username"))
end
user = fetch_user_from_params
guardian.ensure_can_edit_username!(user)
result = UsernameChanger.change(user, params[:new_username], current_user)
if result
render json: { id: user.id, username: user.username }
else
render_json_error(user.errors.full_messages.join(","))
end
rescue Discourse::InvalidAccess
if current_user&.staff?
render_json_error(I18n.t("errors.messages.auth_overrides_username"))
else
render json: failed_json, status: 403
end
end
|