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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With