当登录过程中出现 ldap 错误时,我想在登录页面上显示错误消息,例如“系统此时无法登录。请稍后重试”。
目前,我已使用 custom_failure.rb 方法,如中所述 https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-when-the-user-can-not-be-authenticated 它能够捕获诸如无效用户名/密码之类的错误,并且我已将其重定向到登录页面 根据需要显示错误消息,没有问题。 但这种方法无法捕获 ldap 错误。
这些 ldap 错误显示为非常原始的 html 页面,如下所示:
Devise::SessionsController#create 中的 Errno::ETIMEDOUT
连接尝试失败,因为连接方在一段时间后没有正确响应,或者由于连接的主机未能响应而建立的连接失败。 - 连接(2)
Rails.root:C:/extratxt/2.2.0/source/ruby/messaging 应用追踪 |框架跟踪 |完整跟踪
请求
参数:
{"utf8"=>"✓",
"user"=>{"username"=>"administrator",
"password"=>"[FILTERED]",
"remember_me"=>"0"},
"commit"=>"Sign in"}
显示 session 转储
显示环境转储 回应
标题:
无
如何防止这种情况并显示我指定的页面(例如带有我自己的错误消息的登录页面)? 任何想法 ?谢谢
最佳答案
一种方法是覆盖创建 session 操作,但需要几个步骤才能使其正常工作。首先,复制设备 View (如果您还没有这样做):
rails g devise:views
然后您需要创建一个扩展 Devise::SessionsController 的session_controller.rb 文件:
# /app/controllers/sessions_controller.rb
class SessionsController < Devise::SessionsController
# copied from [...]/gems/devise-1.4.5/app/controllers/sessions_controller.rb
# To find the path to your gem, use 'bundle show devise'
def create
begin
resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
set_flash_message(:notice, :signed_in) if is_navigational_format?
sign_in(resource_name, resource)
respond_with resource, :location => redirect_location(resource_name, resource)
rescue Net::LDAP::LdapError
# handle your error
respond_to do |format|
format.html { redirect_to new_user_session_path, :notice => $!.to_s }
format.json { render json: $!.to_s }
end
end
end
end
最后,在 config/routes.rb 中,您需要告诉 devise 使用您自定义的 Controller :
devise_for :users, :controllers => { :sessions => :sessions }
关于ruby-on-rails - 使用 Devise 和 devise_ldap_authenticable 时如何捕获 Ldap 错误并重定向到指定页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13226733/