Handle AccessDenied in management sessions

We were raising a `CanCan::AcessDenied` and were getting a 500 Internal
Server Error.

I've chosen to do the same thing we do in the ApplicationController.
There are other options to handle this request, like redirecting to the
login page or returning a 401 Unauthorized HTTP status.
This commit is contained in:
Javi Martín
2019-04-24 15:44:05 +02:00
parent b33401ca0f
commit 286e0ca878
4 changed files with 23 additions and 11 deletions

View File

@@ -3,6 +3,7 @@ require "application_responder"
class ApplicationController < ActionController::Base
include HasFilters
include HasOrders
include AccessDeniedHandler
protect_from_forgery with: :exception
@@ -17,13 +18,6 @@ class ApplicationController < ActionController::Base
check_authorization unless: :devise_controller?
self.responder = ApplicationResponder
rescue_from CanCan::AccessDenied do |exception|
respond_to do |format|
format.html { redirect_to main_app.root_url, alert: exception.message }
format.json { render json: {error: exception.message}, status: :forbidden }
end
end
layout :set_layout
respond_to :html
helper_method :current_budget

View File

@@ -0,0 +1,12 @@
module AccessDeniedHandler
extend ActiveSupport::Concern
included do
rescue_from CanCan::AccessDenied do |exception|
respond_to do |format|
format.html { redirect_to main_app.root_url, alert: exception.message }
format.json { render json: { error: exception.message }, status: :forbidden }
end
end
end
end

View File

@@ -1,6 +1,7 @@
require "manager_authenticator"
class Management::SessionsController < ActionController::Base
include AccessDeniedHandler
def create
destroy_session

View File

@@ -3,11 +3,13 @@ require "rails_helper"
describe Management::SessionsController do
describe "Sign in" do
it "denies access if wrong manager credentials" do
allow_any_instance_of(ManagerAuthenticator).to receive(:auth).and_return(false)
expect {
get :create, params: { login: "nonexistent", clave_usuario: "wrong" }
}.to raise_error CanCan::AccessDenied
expect(response).to redirect_to "/"
expect(flash[:alert]).to eq "You do not have permission to access this page."
expect(session[:manager]).to be_nil
end
@@ -42,7 +44,10 @@ describe Management::SessionsController do
it "denies access if user is not admin or manager" do
sign_in create(:user)
expect { get :create}.to raise_error CanCan::AccessDenied
get :create
expect(response).to redirect_to "/"
expect(flash[:alert]).to eq "You do not have permission to access this page."
expect(session[:manager]).to be_nil
end
end