Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After a successful DEVISE login, how to redirect user back to previous action that required login?

I have an ajax voting button: If a user clicks on a "thumbs up" image, but is not logged in, then they should see a dialog box that asks them to login first.

To do this dialog box,I'm using jQuery and facebox bound to ajax:failure event. Devise will raise a 401 Unauthorized if the user is not logged in. facebox loads the remote html for the login in a pop-up dialog box that presents the DEVISE signin form.

Everything works except after successful login, user is redirected to the homepage. It would be more intuitive if user was redirected back to the post they were looking at so they can continue their vote.

Is there a best practices way of achieving this behavior?

Thanks.

like image 930
Homan Avatar asked Aug 08 '11 22:08

Homan


2 Answers

I do the following with Authlogic on Rails 3, perhaps you could use it or do something similar:

class ApplicationController < ActionController::Base
  after_filter :store_location
private
  def store_location
    session[:return_to] = request.fullpath
  end

  def clear_stored_location
    session[:return_to] = nil
  end

  def redirect_back_or_to(alternate)
    redirect_to(session[:return_to] || alternate)
    clear_stored_location
  end
end

Then you can use something like redirect_back_or_to dashboard_path in your login action.

For some controllers/actions, I don't want to store the location (e.g. the login page). For those I just skip the filter:

class UserController < ApplicationController
  skip_after_filter :store_location
end

There's also a page in the Devise wiki on doing this: https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-in

like image 52
coreyward Avatar answered Oct 23 '22 11:10

coreyward


In ApplicationController write following:

after_filter :store_location
def store_location
  session[:previous_urls] ||= []
  # store unique urls only
  session[:previous_urls].prepend request.fullpath if session[:previous_urls].first != request.fullpath
  # For Rails < 3.2
  # session[:previous_urls].unshift request.fullpath if session[:previous_urls].first != request.fullpath 
  session[:previous_urls].pop if session[:previous_urls].count > 2
end
def after_sign_in_path_for(resource)
  session[:previous_urls].last || root_path
end

Source: https://github.com/plataformatec/devise/wiki/How-To:-Redirect-back-to-current-page-after-sign-in,-sign-out,-sign-up,-update

like image 4
ricardomerjan Avatar answered Oct 23 '22 09:10

ricardomerjan