RoR | Devise redirect loop because of cancan authorize
cancan, devise, ruby, ruby-on-rails, ruby-on-rails-3
Solution
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
Problem
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.