bigpotato
bigpotato

Reputation: 27547

Rails + Devise: How to override redirect for the before_filter "authenticate_user!"

I am on Rails 3 and the latest version of Devise, and I have a before filter in my AdminController to authenticate_user! I need to store a session variable for the request.referrer before it redirects so that I can send it back to the /admin page when they try to go on it. Where would I overwrite authenticate_user!?

What I want to do is this, but I don't know where to define it:

def authenticate_user!
  session[:return_to] = request.request_uri
  super
end

Upvotes: 3

Views: 5457

Answers (2)

Cam Price-Austin
Cam Price-Austin

Reputation: 1768

An alternative to Matt's answer, which doesn't require the return page to be recorded upon every page view:

In application_controller.rb:

# Only remembers the page immediately before we 
# redirect them for auth, instead of every page view

def authenticate_user!
  session["user_return_to"] = request.fullpath
  super
end

# Deletes the return path as soon as it's used, so 
# they aren't accidentally redirected back again
# next time they login

def after_sign_in_path_for(resource)
  session.delete("user_return_to") || root_path
end

Upvotes: 0

Matt
Matt

Reputation: 14048

You don't actually need to do that, devise will respect an after_sign_in_path for this exact purpose.

In your application controller:

before_filter :set_return_path 

def after_sign_in_path_for(resource) 
  session["user_return_to"] || root_url 
end

def set_return_path
  unless devise_controller? || request.xhr? || !request.get?
    session["user_return_to"] = request.url
  end
end

From the devise helper:

# The default url to be used after signing in. This is used by all Devise
# controllers and you can overwrite it in your ApplicationController to
# provide a custom hook for a custom resource.
# def after_sign_in_path_for(resource_or_scope)

Upvotes: 3

Related Questions