bee*_*lez 5 ruby xml ruby-on-rails devise
我正在使用XML POST来登录我的用户,如果身份验证不起作用,我需要返回XML响应.但是,XML响应的格式需要自定义,我不知道在Devise中我应该更改此输出.
在'user_sessions_controller.rb'的'create'方法中,我有一个vanilla调用:
def create
resource = warden.authenticate!(:scope => resource_name,
:recall => "#{controller_path}#new")
Run Code Online (Sandbox Code Playgroud)
这是返回:
<errors>
<error>Invalid email or password.</error>
</errors>
Run Code Online (Sandbox Code Playgroud)
但是我需要在它周围加一个包装器:
<AppName>
<errors>
<error>Invalid email or password.</error>
</errors>
</AppName>
Run Code Online (Sandbox Code Playgroud)
您可以http_auth_body在自定义失败应用中重新定义方法:
# lib/custom_failure_app.rb
class CustomFailure < Devise::FailureApp
protected
def http_auth_body
return i18n_message unless request_format
method = "to_#{request_format}"
if method == "to_xml"
{ :errors => { :error => i18n_message } }.to_xml(:root => Rails.application.class.parent_name)
elsif {}.respond_to?(method)
{ :error => i18n_message }.send(method)
else
i18n_message
end
end
end
Run Code Online (Sandbox Code Playgroud)
然后将其添加到initializers/devise.rb:
config.warden do |manager|
manager.failure_app = CustomFailure
end
Run Code Online (Sandbox Code Playgroud)
并将其添加到application.rb:
config.autoload_paths += %W(#{config.root}/lib)
Run Code Online (Sandbox Code Playgroud)
结果:
curl -X POST http://localhost:3000/users/sign_in.xml -d "{}"
<?xml version="1.0" encoding="UTF-8"?>
<DeviseCustom>
<errors>
<error>You need to sign in or sign up before continuing.</error>
</errors>
</DeviseCustom>
Run Code Online (Sandbox Code Playgroud)