Skip to content

Commit 0c8a156

Browse files
authored
Merge pull request #32 from RadiusNetworks/no-redirect-on-format-js
do not redirect if format is :js
2 parents 9bdef95 + 63b7cba commit 0c8a156

File tree

2 files changed

+35
-8
lines changed

2 files changed

+35
-8
lines changed

lib/kracken/controllers/authenticatable.rb

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,13 @@ def authenticate_user
3737

3838
def authenticate_user!
3939
check_token_expiry!
40-
unless user_signed_in?
41-
if request.format == :json
42-
render json: {error: '401 Unauthorized'}, status: :unauthorized
43-
else
44-
redirect_to_sign_in
45-
end
40+
return if user_signed_in?
41+
if request.format == :json
42+
render json: {error: '401 Unauthorized'}, status: :unauthorized
43+
elsif request.format == :js
44+
head :unauthorized
45+
else
46+
redirect_to_sign_in
4647
end
4748
end
4849

spec/kracken/controllers/authenticatable_spec.rb

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,12 @@ class ControllerDouble < BaseControllerDouble
4343
end
4444

4545
context "when no users are logged in" do
46-
it "#authenticate! redirects to root_url" do
47-
allow(controller).to receive(:request).and_return(double(format: nil, fullpath: nil))
46+
let(:html) { Mime::Type.lookup("text/html") }
47+
let(:json) { Mime::Type.lookup("application/json") }
48+
let(:js) { Mime::Type.lookup("application/javascript") }
49+
50+
it "#authenticate! redirects to root_url for format html" do
51+
allow(controller).to receive(:request).and_return(double(format: html, fullpath: nil))
4852
allow(controller).to receive(:redirect_to)
4953

5054
controller.authenticate_user!
@@ -56,6 +60,28 @@ class ControllerDouble < BaseControllerDouble
5660
expect(controller.user_signed_in?).to be_falsey
5761
end
5862

63+
it "#authenticate! doesn't redirect for format json" do
64+
allow(controller).to receive(:request).and_return(double(format: json, fullpath: nil))
65+
allow(controller).to receive(:redirect_to)
66+
allow(controller).to receive(:render)
67+
68+
controller.authenticate_user!
69+
70+
expect(controller).not_to have_received(:redirect_to)
71+
expect(controller).to have_received(:render)
72+
end
73+
74+
it "#authenticate! doesn't redirect for format js" do
75+
allow(controller).to receive(:request).and_return(double(format: js, fullpath: nil))
76+
allow(controller).to receive(:redirect_to)
77+
allow(controller).to receive(:head)
78+
79+
controller.authenticate_user!
80+
81+
expect(controller).not_to have_received(:redirect_to)
82+
expect(controller).to have_received(:head).with(:unauthorized)
83+
end
84+
5985
end
6086

6187
context "when a user is logged in" do

0 commit comments

Comments
 (0)