From a3ac7bd83bfd2ece98e2450dcab83f89860c74de Mon Sep 17 00:00:00 2001 From: Genaro Rocha Date: Thu, 21 Feb 2019 16:36:35 -0800 Subject: [PATCH] When a controller action fails to be autorized, redirect back if a referrer is present or redirect to /unauthorized --- .../lib/spree/core/controller_helpers/auth.rb | 4 ++-- .../core/controller_helpers/auth_spec.rb | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/core/lib/spree/core/controller_helpers/auth.rb b/core/lib/spree/core/controller_helpers/auth.rb index 5f2bec80cc8..e7915264be7 100644 --- a/core/lib/spree/core/controller_helpers/auth.rb +++ b/core/lib/spree/core/controller_helpers/auth.rb @@ -11,7 +11,7 @@ module Auth # @!attribute [rw] unauthorized_redirect # @!scope class # Extension point for overriding behaviour of access denied errors. - # Default behaviour is to redirect to "/unauthorized" with a flash + # Default behaviour is to redirect back or to "/unauthorized" with a flash # message. # @return [Proc] action to take when access denied error is raised. @@ -22,7 +22,7 @@ module Auth class_attribute :unauthorized_redirect self.unauthorized_redirect = -> do flash[:error] = I18n.t('spree.authorization_failure') - redirect_to "/unauthorized" + redirect_back(fallback_location: "/unauthorized") end rescue_from CanCan::AccessDenied do diff --git a/core/spec/lib/spree/core/controller_helpers/auth_spec.rb b/core/spec/lib/spree/core/controller_helpers/auth_spec.rb index 577030adc52..7fc29e96870 100644 --- a/core/spec/lib/spree/core/controller_helpers/auth_spec.rb +++ b/core/spec/lib/spree/core/controller_helpers/auth_spec.rb @@ -70,4 +70,23 @@ def index expect(controller.try_spree_current_user).to eq nil end end + + describe '#unauthorized_redirect' do + controller(FakesController) do + def index; authorize!(:read, :something); end + end + + context "http_referrer is present" do + before { request.env['HTTP_REFERER'] = '/redirect' } + it "redirects back" do + get :index + expect(response).to redirect_to('/redirect') + end + end + + it "redirects to unauthorized" do + get :index + expect(response).to redirect_to('/unauthorized') + end + end end