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

旧巷老猫 提交于 2019-12-24 00:55:35

问题


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

回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/16716679/rails-devise-how-to-override-redirect-for-the-before-filter-authenticate-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!