Search code examples
ruby-on-railsruby-on-rails-4authorizationcancan

CanCan Rails Authorization


I am creating REST API and also using Authorization in REST API. Whenever a user is not authorized for a action it redirects to home page using the following code

rescue_from CanCan::AccessDenied do |exception|
  redirect_to "/", :alert => exception.message
end

For Rest API method, I don't want to be redirected to this page on unauthorized access. Instead, I want to display json

{"Error_msg": "Not Authorized"}.

My controller has following code:

authorize_resource :class => false, :only => [:create_or_update]

where create_or_update is an action(method) on which I want to check authorization.

My ability.rb has following code in editor role

can :create_or_update, :topology

Can someone help me not getting redirected to home page only for this action.


Solution

  • rescue_from CanCan::AccessDenied do |exception|
     if exception.action.to_s == "create_or_update"
       err ={}
       err[:error_id] = "AUTHORIZATION_ERROR"
       err[:error_msg] = exception.message
       render json: err, status: 403
     else
       redirect_to "/", :alert => exception.message
     end
    end