challengable_concern_spec.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. # frozen_string_literal: true
  2. require 'rails_helper'
  3. RSpec.describe ChallengableConcern do
  4. controller(ApplicationController) do
  5. include ChallengableConcern
  6. before_action :require_challenge!
  7. def foo
  8. render plain: 'foo'
  9. end
  10. def bar
  11. render plain: 'bar'
  12. end
  13. end
  14. before do
  15. routes.draw do
  16. get 'foo' => 'anonymous#foo'
  17. post 'bar' => 'anonymous#bar'
  18. end
  19. end
  20. context 'with a no-password user' do
  21. let(:user) { Fabricate(:user, external: true, password: nil) }
  22. before do
  23. sign_in user
  24. end
  25. context 'with GET requests' do
  26. before { get :foo }
  27. it 'does not ask for password' do
  28. expect(response.body).to eq 'foo'
  29. end
  30. end
  31. context 'with POST requests' do
  32. before { post :bar }
  33. it 'does not ask for password' do
  34. expect(response.body).to eq 'bar'
  35. end
  36. end
  37. end
  38. context 'with recent challenge in session' do
  39. let(:password) { 'foobar12345' }
  40. let(:user) { Fabricate(:user, password: password) }
  41. before do
  42. sign_in user
  43. end
  44. context 'with GET requests' do
  45. before { get :foo, session: { challenge_passed_at: Time.now.utc } }
  46. it 'does not ask for password' do
  47. expect(response.body).to eq 'foo'
  48. end
  49. end
  50. context 'with POST requests' do
  51. before { post :bar, session: { challenge_passed_at: Time.now.utc } }
  52. it 'does not ask for password' do
  53. expect(response.body).to eq 'bar'
  54. end
  55. end
  56. end
  57. context 'with a password user' do
  58. let(:password) { 'foobar12345' }
  59. let(:user) { Fabricate(:user, password: password) }
  60. before do
  61. sign_in user
  62. end
  63. context 'with GET requests' do
  64. before { get :foo }
  65. it 'renders challenge' do
  66. expect(response).to render_template('auth/challenges/new')
  67. end
  68. # See Auth::ChallengesControllerSpec
  69. end
  70. context 'with POST requests' do
  71. before { post :bar }
  72. it 'renders challenge' do
  73. expect(response).to render_template('auth/challenges/new')
  74. end
  75. it 'accepts correct password' do
  76. post :bar, params: { form_challenge: { current_password: password } }
  77. expect(response.body).to eq 'bar'
  78. expect(session[:challenge_passed_at]).to_not be_nil
  79. end
  80. it 'rejects wrong password' do
  81. post :bar, params: { form_challenge: { current_password: 'dddfff888123' } }
  82. expect(response.body).to render_template('auth/challenges/new')
  83. expect(session[:challenge_passed_at]).to be_nil
  84. end
  85. end
  86. end
  87. end