forked from discourse/discourse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusers_controller.rb
2113 lines (1744 loc) · 67.1 KB
/
users_controller.rb
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 UsersController < ApplicationController
skip_before_action :authorize_mini_profiler, only: [:avatar]
requires_login only: %i[
username
update
upload_user_image
pick_avatar
destroy_user_image
destroy
check_emails
topic_tracking_state
preferences
create_second_factor_totp
enable_second_factor_totp
disable_second_factor
list_second_factors
update_second_factor
create_second_factor_backup
select_avatar
notification_level
revoke_auth_token
register_second_factor_security_key
create_second_factor_security_key
feature_topic
clear_featured_topic
bookmarks
invited
check_sso_email
check_sso_payload
recent_searches
reset_recent_searches
user_menu_bookmarks
user_menu_messages
]
skip_before_action :check_xhr,
only: %i[
show
badges
password_reset_show
password_reset_update
update
account_created
activate_account
perform_account_activation
avatar
my_redirect
toggle_anon
admin_login
confirm_admin
email_login
summary
feature_topic
clear_featured_topic
bookmarks
user_menu_bookmarks
user_menu_messages
]
before_action :second_factor_check_confirmed_password,
only: %i[
create_second_factor_totp
enable_second_factor_totp
disable_second_factor
update_second_factor
create_second_factor_backup
register_second_factor_security_key
create_second_factor_security_key
]
before_action :respond_to_suspicious_request, only: [:create]
# we need to allow account creation with bad CSRF tokens, if people are caching, the CSRF token on the
# page is going to be empty, this means that server will see an invalid CSRF and blow the session
# once that happens you can't log in with social
skip_before_action :verify_authenticity_token, only: [:create]
skip_before_action :redirect_to_login_if_required,
only: %i[
check_username
check_email
create
account_created
activate_account
perform_account_activation
send_activation_email
update_activation_email
password_reset_show
password_reset_update
confirm_email_token
email_login
admin_login
confirm_admin
]
after_action :add_noindex_header, only: %i[show my_redirect]
allow_in_staff_writes_only_mode :admin_login
allow_in_staff_writes_only_mode :email_login
MAX_RECENT_SEARCHES = 5
def index
end
def show(for_card: false)
return redirect_to path("/login") if SiteSetting.hide_user_profiles_from_public && !current_user
@user =
fetch_user_from_params(
include_inactive: current_user&.staff? || for_card || SiteSetting.show_inactive_accounts,
)
user_serializer = nil
if !current_user&.staff? && [email protected]?
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)
# This is a hack to get around a Rails issue where values with periods aren't handled correctly
# when used as part of a route.
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
def show_card
show(for_card: true)
end
# This route is not used in core, but is used by theme components (e.g. https://meta.discourse.org/t/144479)
def cards
return redirect_to path("/login") if SiteSetting.hide_user_profiles_from_public && !current_user
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
def badges
raise Discourse::NotFound unless SiteSetting.enable_badges?
show
end
def update
user = fetch_user_from_params
guardian.ensure_can_edit!(user)
# Exclude some attributes that are only for user creation because they have
# dedicated update routes.
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.required?
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
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
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
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
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
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
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
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
def private_message_topic_tracking_state
user = fetch_user_from_params
guardian.ensure_can_edit!(user)
report = PrivateMessageTopicTrackingState.report(user)
serializer =
ActiveModel::ArraySerializer.new(
report,
each_serializer: PrivateMessageTopicTrackingStateSerializer,
scope: guardian,
)
render json: MultiJson.dump(serializer)
end
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
def preferences
render body: nil
end
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
def profile_hidden
render nothing: true
end
def summary
@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.headers["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
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
def render_available_true
render(json: { available: true })
end
def changing_case_of_own_username(target_user, username)
target_user && username.downcase == (target_user.username.downcase)
end
# Used for checking availability of a username and will return suggestions
# if the username is not available.
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
# The special case where someone is changing the case of their own username
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
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
def user_from_params_or_current_user
params[:for_user_id] ? User.find(params[:for_user_id]) : current_user
end
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)
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
# Handle API approval and
# auto approve users based on auto_approve_email_domains setting
if user.approved? || EmailValidator.can_auto_approve_user?(user.email)
ReviewableUser.set_approved_fields!(user, current_user)
end
# Handle custom fields
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
# Handle associated accounts
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?
# posted email is different that the already validated one?
return fail_with("login.incorrect_username_email_or_password")
end
activation = UserActivator.new(user, request, session, cookies)
activation.start
# just assign a password if we have an authenticator and no password
# this is the case for Twitter
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
# save user email in session, to show on account-created page
session["user_created_message"] = activation.message
session[SessionController::ACTIVATE_USER_KEY] = user.id
# If the user was created as active this will
# ensure their email is confirmed and
# add them to the review queue if they need to be approved
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
if existing_user = User.find_by_email(user.primary_email&.email)
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
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
def password_reset_update
expires_now
token = params[:token]
password_reset_find_user(token, committing_change: true)
rate_limit_second_factor!(@user)
# no point doing anything else if we can't even find
# a user from the token
if @user
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
# this must be set because the first call we authenticate e.g. TOTP, and we do
# not want to re-authenticate on the second call to change the password as this
# will cause a TOTP error saying the code has already been used
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 we have run into no errors then the user is a-ok to
# change the password
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) # invite link can't be used to log in anymore
secure_session["password-#{token}"] = nil
secure_session["second-factor-#{token}"] = nil
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,
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
def confirm_email_token
expires_now
EmailToken.confirm(params[:token], scope: EmailToken.scopes[:signup])
render json: success_json
end
def logon_after_password_reset
message =
if Guardian.new(@user).can_access_forum?
# Log in the user
log_on_user(@user)
"password_reset.success"
else
@requires_approval = true
"password_reset.success_unapproved"
end
@success = I18n.t(message)
end
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
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