Search code examples
ruby-on-railsruby-on-rails-3authlogic

Authlogic - return user to intended page after login


How can you adapt a standard Authlogic app so instead of the home page every time, it directs a user to whatever link they were trying to get to?

Example 1 - standard log in works as expected

User goes to app.com
Goes through 'login' process
Redirected to home_url

Example 2 - user attempts to visit a specific page

User goes to app.com/specific_link
Redirected to login_url for authentication
Expects to be sent back to /special_link; instead sent to home_url

How can I return the user to the link they want in Example 2?


Solution

  • Save the page when you go to login, then used that to return the user to that page after login, e.g.

    # redirect to the login page. Call this in the login action, when successful.
    def redirect_away(*params)
      session[:original_uri] = request.request_uri
      redirect_to(*params)
    end
    
    # returns to the original url from a redirect_away or to a default url
    def redirect_back(*params)
      uri = session[:original_uri]
      session[:original_uri] = nil
      if uri
        redirect_to uri
      else
        redirect_to(*params)
      end
    end