RoR | Devise redirect loop because of cancan authorize
Asked Answered
H

1

7

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.

Hearttoheart answered 21/6, 2012 at 15:54 Comment(1)
if you use devise for authentication you can check current_user if the user is logged in or notClaytor
H
13

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
Hearttoheart answered 21/6, 2012 at 16:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.