我找到的所有问题都与使用辅助函数 after_sign_in_path_for(resource)
成功登录有关。
我在站点的主页(index)上有一个登录表单,当登录失败时,它会重定向到“users/sign_in”
但是当登录失败时,如何重定向到我的site#index
?
我找到的所有问题都与使用辅助函数 after_sign_in_path_for(resource)
成功登录有关。
我在站点的主页(index)上有一个登录表单,当登录失败时,它会重定向到“users/sign_in”
但是当登录失败时,如何重定向到我的site#index
?
在你的lib目录下创建一个名为custom_failure.rb的文件,其中包含:
class CustomFailure < Devise::FailureApp
def redirect_url
your_path
end
def respond
if http_auth?
http_auth
else
redirect
end
end
end
在您的Devise初始化器中,包含:
In your Devise initializer, include:
config.warden do |manager|
manager.failure_app = CustomFailure
end
确保Rails能够加载你的lib文件,在你的application.rb文件中:
config.autoload_paths += %W(#{config.root}/lib)
不要忘记重新启动你的服务器。
我认为没有比这更容易的方法了。
SessionsController
,您可以重新分配auth_options
中的:recall
值来回调您想要运行的controller#method
,然后再运行warden.authenticate!(auth_options)
。例如,在app/controllers/users/sessions_controller.rb
中:class Users::SessionsController < Devise::SessionsController
#...
def create
#...
auth_options = { :recall => 'site#index', :scope => :user }
resource = warden.authenticate!(auth_options)
#...
end
#...
end
通过这种方式,您无需创建自定义的 FailureApp 并修改配置。Started POST "/users/sign_in"
Processing by Devise::SessionsController#create
Completed 401 Unauthorized
Processing by Devise::SessionsController#new
由于在gems/devise-3.1.0/app/controllers/devise/sessions_controller.rb末尾定义了auth_options,因此会调用new。
您应该重新定义create操作中使用的auth_options。我将控制器复制到了我的Rails应用程序中的app/controllers/devise/sessions_controller.rb,并像这样替换了auth_options方法。
def auth_options
{ :scope => resource_name, :recall => "Home#new" }
end
这个方法有效,但URL仍然是/users/sign_in。
我也会尝试修复它。
Class CustomFailure < Devise::FailureApp
def respond
binding.pry
super
end
end
def respond
if http_auth?
http_auth
elsif warden_options[:recall]
recall
else
redirect
end
end
respond
代码条件最终返回redirect
。respond
方法代码是否返回http_auth
。http_auth?
的定义。特别要注意的是:request.xhr?
方法,它将为json请求返回0(请记住,在ruby中,0实际上等于true)。def http_auth?
if request.xhr?
Devise.http_authenticatable_on_xhr
else
!(request_format && is_navigational_format?)
end
end
也许您需要检查初始化程序/设备文件中的config.http_authenticatable_on_xhr
或config.navigational_formats
,以控制所需的响应。此配置确实会影响Devise返回的内容,并且由于其在底层执行的操作,通常会导致意外行为。
respond
方法的内容可以重构为http_auth? ? http_auth : redirect
。非常好用! - RyanScottLewisNameError - undefined local variable or method 'login' for #<CustomFailure:0x007ffc4aeb9328>
。 - Omni