-
Notifications
You must be signed in to change notification settings - Fork 8.2k
/
users_controller_spec.rb
4575 lines (3635 loc) · 152 KB
/
users_controller_spec.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
require 'rails_helper'
require 'rotp'
describe UsersController do
let(:user) { Fabricate(:user) }
describe "#full account registration flow" do
it "will correctly handle honeypot and challenge" do
get '/session/hp.json'
expect(response.status).to eq(200)
json = response.parsed_body
params = {
email: 'jane@jane.com',
name: 'jane',
username: 'jane',
password_confirmation: json['value'],
challenge: json['challenge'].reverse,
password: SecureRandom.hex
}
secure_session = SecureSession.new(session["secure_session_id"])
expect(secure_session[UsersController::HONEYPOT_KEY]).to eq(json["value"])
expect(secure_session[UsersController::CHALLENGE_KEY]).to eq(json["challenge"])
post '/u.json', params: params
expect(response.status).to eq(200)
jane = User.find_by(username: 'jane')
expect(jane.email).to eq('jane@jane.com')
expect(secure_session[UsersController::HONEYPOT_KEY]).to eq(nil)
expect(secure_session[UsersController::CHALLENGE_KEY]).to eq(nil)
end
end
describe '#perform_account_activation' do
let(:token) do
return @token if @token.present?
email_token = EmailToken.create!(expired: false, confirmed: false, user: user, email: user.email)
@token = email_token.token
@token
end
before do
UsersController.any_instance.stubs(:honeypot_or_challenge_fails?).returns(false)
end
context 'invalid token' do
it 'return success' do
put "/u/activate-account/invalid-tooken"
expect(response.status).to eq(200)
expect(flash[:error]).to be_present
end
end
context 'valid token' do
context 'welcome message' do
it 'enqueues a welcome message if the user object indicates so' do
user.update(active: false)
put "/u/activate-account/#{token}"
expect(response.status).to eq(200)
expect(Jobs::SendSystemMessage.jobs.size).to eq(1)
expect(Jobs::SendSystemMessage.jobs.first["args"].first["message_type"]).to eq("welcome_user")
end
it "doesn't enqueue the welcome message if the object returns false" do
user.update(active: true)
put "/u/activate-account/#{token}"
expect(response.status).to eq(200)
expect(Jobs::SendSystemMessage.jobs.size).to eq(0)
end
end
context "honeypot" do
it "raises an error if the honeypot is invalid" do
UsersController.any_instance.stubs(:honeypot_or_challenge_fails?).returns(true)
put "/u/activate-account/#{token}"
expect(response.status).to eq(403)
end
end
context 'response' do
before do
Guardian.any_instance.expects(:can_access_forum?).returns(true)
EmailToken.expects(:confirm).with("#{token}").returns(user)
end
it 'correctly logs on user' do
events = DiscourseEvent.track_events do
put "/u/activate-account/#{token}"
end
expect(events.map { |event| event[:event_name] }).to contain_exactly(
:user_logged_in, :user_first_logged_in
)
expect(response.status).to eq(200)
expect(flash[:error]).to be_blank
expect(session[:current_user_id]).to be_present
expect(CGI.unescapeHTML(response.body))
.to_not include(I18n.t('activation.approval_required'))
end
end
context 'user is not approved' do
before do
SiteSetting.must_approve_users = true
EmailToken.expects(:confirm).with("#{token}").returns(user)
put "/u/activate-account/#{token}"
end
it 'should return the right response' do
expect(response.status).to eq(200)
expect(CGI.unescapeHTML(response.body))
.to include(I18n.t('activation.approval_required'))
expect(response.body).to_not have_tag(:script, with: {
src: '/assets/application.js'
})
expect(flash[:error]).to be_blank
expect(session[:current_user_id]).to be_blank
end
end
end
context 'when cookies contains a destination URL' do
it 'should redirect to the URL' do
destination_url = 'http://thisisasite.com/somepath'
cookies[:destination_url] = destination_url
put "/u/activate-account/#{token}"
expect(response).to redirect_to(destination_url)
end
end
end
describe '#password_reset' do
fab!(:user) { Fabricate(:user) }
let(:token) { SecureRandom.hex }
context "you can view it even if login is required" do
it "returns success" do
SiteSetting.login_required = true
get "/u/password-reset/#{token}"
expect(response.status).to eq(200)
expect(CGI.unescapeHTML(response.body)).to include(I18n.t('password_reset.no_token'))
end
end
context 'missing token' do
it 'disallows login' do
get "/u/password-reset/#{token}"
expect(response.status).to eq(200)
expect(CGI.unescapeHTML(response.body))
.to include(I18n.t('password_reset.no_token'))
expect(response.body).to_not have_tag(:script, with: {
src: '/assets/application.js'
})
expect(session[:current_user_id]).to be_blank
end
it "responds with proper error message" do
get "/u/password-reset/#{token}.json"
expect(response.status).to eq(200)
expect(response.parsed_body["message"]).to eq(I18n.t('password_reset.no_token'))
expect(session[:current_user_id]).to be_blank
end
end
context 'invalid token' do
it 'disallows login' do
get "/u/password-reset/ev!l_trout@!"
expect(response.status).to eq(200)
expect(CGI.unescapeHTML(response.body))
.to include(I18n.t('password_reset.no_token'))
expect(response.body).to_not have_tag(:script, with: {
src: '/assets/application.js'
})
expect(session[:current_user_id]).to be_blank
end
it "responds with proper error message" do
put "/u/password-reset/evil_trout!.json", params: { password: "awesomeSecretPassword" }
expect(response.status).to eq(200)
expect(response.parsed_body["message"]).to eq(I18n.t('password_reset.no_token'))
expect(session[:current_user_id]).to be_blank
end
end
context 'valid token' do
context 'when rendered' do
it 'renders referrer never on get requests' do
user = Fabricate(:user)
token = user.email_tokens.create(email: user.email).token
get "/u/password-reset/#{token}"
expect(response.status).to eq(200)
expect(response.body).to include('<meta name="referrer" content="never">')
end
end
it 'returns success' do
user = Fabricate(:user)
user_auth_token = UserAuthToken.generate!(user_id: user.id)
token = user.email_tokens.create(email: user.email).token
events = DiscourseEvent.track_events do
put "/u/password-reset/#{token}", params: { password: 'hg9ow8yhg98o' }
end
expect(events.map { |event| event[:event_name] }).to contain_exactly(
:user_logged_in, :user_first_logged_in
)
expect(response.status).to eq(200)
expect(response.body).to have_tag("div#data-preloaded") do |element|
json = JSON.parse(element.current_scope.attribute('data-preloaded').value)
expect(json['password_reset']).to include('{"is_developer":false,"admin":false,"second_factor_required":false,"security_key_required":false,"backup_enabled":false,"multiple_second_factor_methods":false}')
end
expect(session["password-#{token}"]).to be_blank
expect(UserAuthToken.where(id: user_auth_token.id).count).to eq(0)
end
it 'disallows double password reset' do
user = Fabricate(:user)
token = user.email_tokens.create(email: user.email).token
put "/u/password-reset/#{token}", params: { password: 'hg9ow8yHG32O' }
put "/u/password-reset/#{token}", params: { password: 'test123987AsdfXYZ' }
user.reload
expect(user.confirm_password?('hg9ow8yHG32O')).to eq(true)
# logged in now
expect(user.user_auth_tokens.count).to eq(1)
end
it "doesn't redirect to wizard on get" do
user = Fabricate(:admin)
UserAuthToken.generate!(user_id: user.id)
token = user.email_tokens.create(email: user.email).token
get "/u/password-reset/#{token}.json"
expect(response).not_to redirect_to(wizard_path)
end
it "redirects to the wizard if you're the first admin" do
user = Fabricate(:admin)
UserAuthToken.generate!(user_id: user.id)
token = user.email_tokens.create(email: user.email).token
get "/u/password-reset/#{token}"
put "/u/password-reset/#{token}", params: { password: 'hg9ow8yhg98oadminlonger' }
expect(response).to redirect_to(wizard_path)
end
it "sets the users timezone if the param is present" do
user = Fabricate(:admin)
UserAuthToken.generate!(user_id: user.id)
token = user.email_tokens.create(email: user.email).token
get "/u/password-reset/#{token}"
expect(user.user_option.timezone).to eq(nil)
put "/u/password-reset/#{token}", params: { password: 'hg9ow8yhg98oadminlonger', timezone: "America/Chicago" }
expect(user.user_option.reload.timezone).to eq("America/Chicago")
end
it "logs the password change" do
user = Fabricate(:admin)
UserAuthToken.generate!(user_id: user.id)
token = user.email_tokens.create(email: user.email).token
get "/u/password-reset/#{token}"
expect do
put "/u/password-reset/#{token}", params: { password: 'hg9ow8yhg98oadminlonger' }
end.to change { UserHistory.count }.by (1)
entry = UserHistory.last
expect(entry.target_user_id).to eq(user.id)
expect(entry.action).to eq(UserHistory.actions[:change_password])
end
it "doesn't invalidate the token when loading the page" do
user = Fabricate(:user)
user_token = UserAuthToken.generate!(user_id: user.id)
email_token = user.email_tokens.create(email: user.email)
get "/u/password-reset/#{email_token.token}.json"
expect(response.status).to eq(200)
email_token.reload
expect(email_token.confirmed).to eq(false)
expect(UserAuthToken.where(id: user_token.id).count).to eq(1)
end
context "rate limiting" do
before { RateLimiter.clear_all!; RateLimiter.enable }
after { RateLimiter.disable }
it "rate limits reset passwords" do
freeze_time
token = user.email_tokens.create!(email: user.email).token
3.times do
put "/u/password-reset/#{token}", params: {
second_factor_token: 123456,
second_factor_method: 1
}
expect(response.status).to eq(200)
end
put "/u/password-reset/#{token}", params: {
second_factor_token: 123456,
second_factor_method: 1
}
expect(response.status).to eq(429)
end
end
context '2 factor authentication required' do
let!(:second_factor) { Fabricate(:user_second_factor_totp, user: user) }
it 'does not change with an invalid token' do
token = user.email_tokens.create!(email: user.email).token
get "/u/password-reset/#{token}"
expect(response.body).to have_tag("div#data-preloaded") do |element|
json = JSON.parse(element.current_scope.attribute('data-preloaded').value)
expect(json['password_reset']).to include('{"is_developer":false,"admin":false,"second_factor_required":true,"security_key_required":false,"backup_enabled":false,"multiple_second_factor_methods":false}')
end
put "/u/password-reset/#{token}", params: {
password: 'hg9ow8yHG32O',
second_factor_token: '000000',
second_factor_method: UserSecondFactor.methods[:totp]
}
expect(response.body).to include(I18n.t("login.invalid_second_factor_code"))
user.reload
expect(user.confirm_password?('hg9ow8yHG32O')).not_to eq(true)
expect(user.user_auth_tokens.count).not_to eq(1)
end
it 'changes password with valid 2-factor tokens' do
token = user.email_tokens.create(email: user.email).token
get "/u/password-reset/#{token}"
put "/u/password-reset/#{token}", params: {
password: 'hg9ow8yHG32O',
second_factor_token: ROTP::TOTP.new(second_factor.data).now,
second_factor_method: UserSecondFactor.methods[:totp]
}
user.reload
expect(response.status).to eq(200)
expect(user.confirm_password?('hg9ow8yHG32O')).to eq(true)
expect(user.user_auth_tokens.count).to eq(1)
end
end
context 'security key authentication required' do
let!(:user_security_key) do
Fabricate(
:user_security_key,
user: user,
credential_id: valid_security_key_data[:credential_id],
public_key: valid_security_key_data[:public_key]
)
end
let(:token) { user.email_tokens.create!(email: user.email).token }
before do
simulate_localhost_webauthn_challenge
# store challenge in secure session by visiting the email login page
get "/u/password-reset/#{token}"
end
it 'preloads with a security key challenge and allowed credential ids' do
expect(response.body).to have_tag("div#data-preloaded") do |element|
json = JSON.parse(element.current_scope.attribute('data-preloaded').value)
password_reset = JSON.parse(json['password_reset'])
expect(password_reset['challenge']).not_to eq(nil)
expect(password_reset['allowed_credential_ids']).to eq([user_security_key.credential_id])
expect(password_reset['security_key_required']).to eq(true)
end
end
it 'stages a webauthn challenge and rp-id for the user' do
secure_session = SecureSession.new(session["secure_session_id"])
expect(Webauthn.challenge(user, secure_session)).not_to eq(nil)
expect(Webauthn.rp_id(user, secure_session)).to eq(Discourse.current_hostname)
end
it 'changes password with valid security key challenge and authentication' do
put "/u/password-reset/#{token}.json", params: {
password: 'hg9ow8yHG32O',
second_factor_token: valid_security_key_auth_post_data,
second_factor_method: UserSecondFactor.methods[:security_key]
}
user.reload
expect(response.status).to eq(200)
expect(user.confirm_password?('hg9ow8yHG32O')).to eq(true)
expect(user.user_auth_tokens.count).to eq(1)
end
it "does not change a password if a fake TOTP token is provided" do
put "/u/password-reset/#{token}.json", params: {
password: 'hg9ow8yHG32O',
second_factor_token: 'blah',
second_factor_method: UserSecondFactor.methods[:security_key]
}
user.reload
expect(response.status).to eq(200)
expect(user.confirm_password?('hg9ow8yHG32O')).to eq(false)
end
context "when security key authentication fails" do
it 'shows an error message and does not change password' do
put "/u/password-reset/#{token}", params: {
password: 'hg9ow8yHG32O',
second_factor_token: {
signature: 'bad',
clientData: 'bad',
authenticatorData: 'bad',
credentialId: 'bad'
},
second_factor_method: UserSecondFactor.methods[:security_key]
}
user.reload
expect(user.confirm_password?('hg9ow8yHG32O')).to eq(false)
expect(response.status).to eq(200)
expect(response.body).to include(I18n.t("webauthn.validation.not_found_error"))
end
end
end
end
context 'submit change' do
let(:token) { EmailToken.generate_token }
before do
EmailToken.expects(:confirm).with(token).returns(user)
end
it "fails when the password is blank" do
put "/u/password-reset/#{token}.json", params: { password: '' }
expect(response.status).to eq(200)
expect(response.parsed_body["errors"]).to be_present
expect(session[:current_user_id]).to be_blank
end
it "fails when the password is too long" do
put "/u/password-reset/#{token}.json", params: { password: ('x' * (User.max_password_length + 1)) }
expect(response.status).to eq(200)
expect(response.parsed_body["errors"]).to be_present
expect(session[:current_user_id]).to be_blank
end
it "logs in the user" do
put "/u/password-reset/#{token}.json", params: { password: 'ksjafh928r' }
expect(response.status).to eq(200)
expect(response.parsed_body["errors"]).to be_blank
expect(session[:current_user_id]).to be_present
end
it "doesn't log in the user when not approved" do
SiteSetting.must_approve_users = true
put "/u/password-reset/#{token}.json", params: { password: 'ksjafh928r' }
expect(response.parsed_body["errors"]).to be_blank
expect(session[:current_user_id]).to be_blank
end
end
end
describe '#confirm_email_token' do
fab!(:user) { Fabricate(:user) }
it "token doesn't match any records" do
email_token = user.email_tokens.create(email: user.email)
get "/u/confirm-email-token/#{SecureRandom.hex}.json"
expect(response.status).to eq(200)
expect(email_token.reload.confirmed).to eq(false)
end
it "token matches" do
email_token = user.email_tokens.create(email: user.email)
get "/u/confirm-email-token/#{email_token.token}.json"
expect(response.status).to eq(200)
expect(email_token.reload.confirmed).to eq(true)
end
end
describe '#admin_login' do
fab!(:admin) { Fabricate(:admin) }
fab!(:user) { Fabricate(:user) }
context 'enqueues mail' do
it 'enqueues mail with admin email and sso enabled' do
put "/u/admin-login", params: { email: admin.email }
expect(response.status).to eq(200)
expect(Jobs::CriticalUserEmail.jobs.size).to eq(1)
args = Jobs::CriticalUserEmail.jobs.first["args"].first
expect(args["user_id"]).to eq(admin.id)
end
end
context 'when email is incorrect' do
it 'should return the right response' do
put "/u/admin-login", params: { email: 'random' }
expect(response.status).to eq(200)
response_body = response.body
expect(response_body).to match(I18n.t("admin_login.errors.unknown_email_address"))
expect(response_body).to_not match(I18n.t("login.second_factor_description"))
end
end
end
describe '#toggle_anon' do
it 'allows you to toggle anon if enabled' do
SiteSetting.allow_anonymous_posting = true
user = sign_in(Fabricate(:user))
user.trust_level = 1
user.save!
post "/u/toggle-anon.json"
expect(response.status).to eq(200)
expect(session[:current_user_id]).to eq(AnonymousShadowCreator.get(user).id)
post "/u/toggle-anon.json"
expect(response.status).to eq(200)
expect(session[:current_user_id]).to eq(user.id)
end
end
describe '#create' do
def honeypot_magic(params)
get '/session/hp.json'
json = response.parsed_body
params[:password_confirmation] = json["value"]
params[:challenge] = json["challenge"].reverse
params
end
before do
UsersController.any_instance.stubs(:honeypot_value).returns(nil)
UsersController.any_instance.stubs(:challenge_value).returns(nil)
SiteSetting.allow_new_registrations = true
@user = Fabricate.build(:user, email: "foobar@example.com", password: "strongpassword")
end
let(:post_user_params) do
{ name: @user.name,
username: @user.username,
password: "strongpassword",
email: @user.email }
end
def post_user(extra_params = {})
post "/u.json", params: post_user_params.merge(extra_params)
end
context 'when email params is missing' do
it 'should raise the right error' do
post "/u.json", params: {
name: @user.name,
username: @user.username,
password: 'tesing12352343'
}
expect(response.status).to eq(400)
end
end
context 'when creating a user' do
it 'sets the user locale to I18n.locale' do
SiteSetting.default_locale = 'en'
I18n.stubs(:locale).returns(:fr)
post_user
expect(User.find_by(username: @user.username).locale).to eq('fr')
end
it 'requires invite code when specified' do
expect(SiteSetting.require_invite_code).to eq(false)
SiteSetting.invite_code = "abc def"
expect(SiteSetting.require_invite_code).to eq(true)
post_user(invite_code: "abcd")
expect(response.status).to eq(200)
json = response.parsed_body
expect(json["success"]).to eq(false)
# case insensitive and stripped of leading/ending spaces
post_user(invite_code: " AbC deF ")
expect(response.status).to eq(200)
json = response.parsed_body
expect(json["success"]).to eq(true)
end
context "when timezone is provided as a guess on signup" do
it "sets the timezone" do
post_user(timezone: "Australia/Brisbane")
expect(response.status).to eq(200)
expect(User.find_by(username: @user.username).user_option.timezone).to eq("Australia/Brisbane")
end
end
context "with local logins disabled" do
before do
SiteSetting.enable_local_logins = false
SiteSetting.enable_google_oauth2_logins = true
end
it "blocks registration without authenticator information" do
post_user
expect(response.status).to eq(403)
end
it "blocks with a regular api key" do
api_key = Fabricate(:api_key, user: user)
post "/u.json", params: post_user_params, headers: { HTTP_API_KEY: api_key.key }
expect(response.status).to eq(403)
end
it "works with an admin api key" do
api_key = Fabricate(:api_key, user: Fabricate(:admin))
post "/u.json", params: post_user_params, headers: { HTTP_API_KEY: api_key.key }
expect(response.status).to eq(200)
end
end
end
context 'when creating a non active user (unconfirmed email)' do
it 'returns 403 forbidden when local logins are disabled' do
SiteSetting.enable_local_logins = false
post_user
expect(response.status).to eq(403)
end
it 'returns an error when new registrations are disabled' do
SiteSetting.allow_new_registrations = false
post_user
expect(response.status).to eq(200)
json = response.parsed_body
expect(json['success']).to eq(false)
expect(json['message']).to be_present
end
it 'creates a user correctly' do
post_user
expect(response.status).to eq(200)
expect(response.parsed_body['active']).to be_falsey
# should save user_created_message in session
expect(session["user_created_message"]).to be_present
expect(session[SessionController::ACTIVATE_USER_KEY]).to be_present
expect(Jobs::SendSystemMessage.jobs.size).to eq(0)
expect(Jobs::CriticalUserEmail.jobs.size).to eq(1)
args = Jobs::CriticalUserEmail.jobs.first["args"].first
expect(args["type"]).to eq("signup")
end
context "`must approve users` site setting is enabled" do
before { SiteSetting.must_approve_users = true }
it 'creates a user correctly' do
post_user
expect(response.status).to eq(200)
expect(response.parsed_body['active']).to be_falsey
# should save user_created_message in session
expect(session["user_created_message"]).to be_present
expect(session[SessionController::ACTIVATE_USER_KEY]).to be_present
expect(Jobs::SendSystemMessage.jobs.size).to eq(0)
expect(Jobs::CriticalUserEmail.jobs.size).to eq(1)
args = Jobs::CriticalUserEmail.jobs.first["args"].first
expect(args["type"]).to eq("signup")
end
end
context 'users already exists with given email' do
let!(:existing) { Fabricate(:user, email: post_user_params[:email]) }
it 'returns an error if hide_email_address_taken is disabled' do
SiteSetting.hide_email_address_taken = false
post_user
expect(response.status).to eq(200)
json = response.parsed_body
expect(json['success']).to eq(false)
expect(json['message']).to be_present
end
it 'returns success if hide_email_address_taken is enabled' do
SiteSetting.hide_email_address_taken = true
expect {
post_user
}.to_not change { User.count }
expect(response.status).to eq(200)
expect(session["user_created_message"]).to be_present
json = response.parsed_body
expect(json['active']).to be_falsey
expect(json['message']).to eq(I18n.t("login.activate_email", email: post_user_params[:email]))
end
end
end
context "creating as active" do
it "won't create the user as active" do
post "/u.json", params: post_user_params.merge(active: true)
expect(response.status).to eq(200)
expect(response.parsed_body['active']).to be_falsey
end
context "with a regular api key" do
fab!(:user) { Fabricate(:user) }
fab!(:api_key, refind: false) { Fabricate(:api_key, user: user) }
it "won't create the user as active with a regular key" do
post "/u.json",
params: post_user_params.merge(active: true), headers: { HTTP_API_KEY: api_key.key }
expect(response.status).to eq(200)
expect(response.parsed_body['active']).to be_falsey
end
end
context "with an admin api key" do
fab!(:admin) { Fabricate(:admin) }
fab!(:api_key, refind: false) { Fabricate(:api_key, user: admin) }
it "creates the user as active with a an admin key" do
SiteSetting.send_welcome_message = true
SiteSetting.must_approve_users = true
#Sidekiq::Client.expects(:enqueue).never
post "/u.json", params: post_user_params.merge(approved: true, active: true), headers: { HTTP_API_KEY: api_key.key }
expect(Jobs::CriticalUserEmail.jobs.size).to eq(0)
expect(Jobs::SendSystemMessage.jobs.size).to eq(0)
expect(response.status).to eq(200)
json = response.parsed_body
new_user = User.find(json["user_id"])
email_token = new_user.email_tokens.active.where(email: new_user.email).first
expect(json['active']).to be_truthy
expect(new_user.active).to eq(true)
expect(new_user.approved).to eq(true)
expect(new_user.approved_by_id).to eq(admin.id)
expect(new_user.approved_at).to_not eq(nil)
expect(email_token.confirmed?).to eq(true)
end
it "will create a reviewable when a user is created as active but not approved" do
Jobs.run_immediately!
SiteSetting.must_approve_users = true
post "/u.json", params: post_user_params.merge(active: true), headers: { HTTP_API_KEY: api_key.key }
expect(response.status).to eq(200)
json = response.parsed_body
new_user = User.find(json["user_id"])
expect(json['active']).to be_truthy
expect(new_user.approved).to eq(false)
expect(ReviewableUser.pending.find_by(target: new_user)).to be_present
end
it "won't create a reviewable when a user is not active" do
Jobs.run_immediately!
SiteSetting.must_approve_users = true
post "/u.json", params: post_user_params, headers: { HTTP_API_KEY: api_key.key }
expect(response.status).to eq(200)
json = response.parsed_body
new_user = User.find(json["user_id"])
expect(json['active']).to eq(false)
expect(new_user.approved).to eq(false)
expect(ReviewableUser.pending.find_by(target: new_user)).to be_blank
end
it "won't create the developer as active" do
UsernameCheckerService.expects(:is_developer?).returns(true)
post "/u.json", params: post_user_params.merge(active: true), headers: { HTTP_API_KEY: api_key.key }
expect(response.status).to eq(200)
expect(response.parsed_body['active']).to be_falsy
end
it "won't set the new user's locale to the admin's locale" do
SiteSetting.allow_user_locale = true
admin.update!(locale: :fr)
post "/u.json", params: post_user_params.merge(active: true), headers: { HTTP_API_KEY: api_key.key }
expect(response.status).to eq(200)
json = response.parsed_body
new_user = User.find(json["user_id"])
expect(new_user.locale).not_to eq("fr")
end
it "will auto approve user if the user email domain matches auto_approve_email_domains setting" do
Jobs.run_immediately!
SiteSetting.must_approve_users = true
SiteSetting.auto_approve_email_domains = "example.com"
post "/u.json", params: post_user_params.merge(active: true), headers: { HTTP_API_KEY: api_key.key }
expect(response.status).to eq(200)
json = response.parsed_body
new_user = User.find(json["user_id"])
expect(json['active']).to be_truthy
expect(new_user.approved).to be_truthy
expect(ReviewableUser.pending.find_by(target: new_user)).to be_blank
end
end
end
context "creating as staged" do
it "won't create the user as staged" do
post "/u.json", params: post_user_params.merge(staged: true)
expect(response.status).to eq(200)
new_user = User.where(username: post_user_params[:username]).first
expect(new_user.staged?).to eq(false)
end
context "with a regular api key" do
fab!(:user) { Fabricate(:user) }
fab!(:api_key, refind: false) { Fabricate(:api_key, user: user) }
it "won't create the user as staged with a regular key" do
post "/u.json", params: post_user_params.merge(staged: true), headers: { HTTP_API_KEY: api_key.key }
expect(response.status).to eq(200)
new_user = User.where(username: post_user_params[:username]).first
expect(new_user.staged?).to eq(false)
end
end
context "with an admin api key" do
fab!(:user) { Fabricate(:admin) }
fab!(:api_key, refind: false) { Fabricate(:api_key, user: user) }
it "creates the user as staged with a regular key" do
post "/u.json", params: post_user_params.merge(staged: true), headers: { HTTP_API_KEY: api_key.key }
expect(response.status).to eq(200)
new_user = User.where(username: post_user_params[:username]).first
expect(new_user.staged?).to eq(true)
end
it "won't create the developer as staged" do
UsernameCheckerService.expects(:is_developer?).returns(true)
post "/u.json", params: post_user_params.merge(staged: true), headers: { HTTP_API_KEY: api_key.key }
expect(response.status).to eq(200)
new_user = User.where(username: post_user_params[:username]).first
expect(new_user.staged?).to eq(false)
end
end
end
context 'when creating an active user (confirmed email)' do
before { User.any_instance.stubs(:active?).returns(true) }
it 'enqueues a welcome email' do
User.any_instance.expects(:enqueue_welcome_message).with('welcome_user')
post_user
expect(response.status).to eq(200)
# should save user_created_message in session
expect(session["user_created_message"]).to be_present
expect(session[SessionController::ACTIVATE_USER_KEY]).to be_present
end
it "shows the 'active' message" do
User.any_instance.expects(:enqueue_welcome_message)
post_user
expect(response.status).to eq(200)
expect(response.parsed_body['message']).to eq(
I18n.t 'login.active'
)
end
it "should be logged in" do
User.any_instance.expects(:enqueue_welcome_message)
post_user
expect(response.status).to eq(200)
expect(session[:current_user_id]).to be_present
end
it 'indicates the user is active in the response' do
User.any_instance.expects(:enqueue_welcome_message)
post_user
expect(response.status).to eq(200)
expect(response.parsed_body['active']).to be_truthy
end
it 'doesn\'t succeed when new registrations are disabled' do
SiteSetting.allow_new_registrations = false
post_user
expect(response.status).to eq(200)
json = response.parsed_body
expect(json['success']).to eq(false)
expect(json['message']).to be_present
end
context 'authentication records for' do
before do
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new(
provider: 'twitter',
uid: '123545',
info: OmniAuth::AuthHash::InfoHash.new(
email: "osama@mail.com",
nickname: "testosama",
name: "Osama Test"
)
)
Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:twitter]
SiteSetting.enable_twitter_logins = true
get "/auth/twitter/callback.json"
end
after do
Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:twitter] = nil
OmniAuth.config.test_mode = false
end