Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RoR | Devise redirect loop because of cancan authorize

Hers is my application.rb

class ApplicationController < ActionController::Base
  protect_from_forgery

  rescue_from CanCan::AccessDenied do |exception|
    flash[:error] = "You must first login to view this page"
    session[:user_return_to] = request.url
    redirect_to "/users/sign_in"
  end                                                                                                                                                  

end

This will redirect the use to the login page if the AccessDenied is throw and the user is not logged in ("works nicely"), but once logged in it will cause a redirect loop if logged in but not authorized by cancan since the login page will just redirect them back to the user right back via session[:user_return_to] = request.url.

The question is: how do I handle this logic if the user is logged in but not authorized.

like image 711
Polygon Pusher Avatar asked Jun 21 '12 15:06

Polygon Pusher


1 Answers

I added a little condition to make this work.

class ApplicationController < ActionController::Base
  protect_from_forgery

    #Redirects to login for secure resources
    rescue_from CanCan::AccessDenied do |exception|

      if user_signed_in?
        flash[:error] = "Not authorized to view this page"
        session[:user_return_to] = nil
        redirect_to root_url

      else              
        flash[:error] = "You must first login to view this page"
        session[:user_return_to] = request.url
        redirect_to "/users/sign_in"
      end 

    end 
end
like image 60
Polygon Pusher Avatar answered Oct 15 '22 16:10

Polygon Pusher