I’d like to be able to set the root url in routes.rb based on the logged in/out state of Authlogic. Here is an example of what I need to do:
root :to => 'users#index', :constraints => lambda { |request| # ??? }
root :to => 'welcome#index'
get '/' => 'users#index', :as => 'user_root'
This would enable logged in users to go to users#index and logged out users to go to welcome#index without doing a redirect. I do know how to set a before_filter and redirect accordingly, but I’d rather not do that.
I know this is possible with Devise but I need to solve this for Authlogic. Similar question here without an answer.
You can create a custom route constraint pretty easily. Any object that responds to
matches?can be handed to the:constraintsroute option. To check for Authlogic authentication, you would need to pull your Authlogic methods from your ApplicationController and put them somewhere else. I recommend using a concern for these anyways.Note that we’re instantiating a new
RouteConstraints::LoggedInobject. This is because the Authlogic methodscurrent_userandcurrent_user_sessionare defined as instance methods and create instance variables — if they aren’t separated for each request, you won’t be sure a user is actually logged in or another one was logged in before.You might run into problems if Authlogic tries to access
paramsdirectly. In this case, you will probably need to override theUserSession.newmethod to accept therequestobject as an argument and callrequest.paramsto get the params.