2012-01-02 82 views
5

我正在使用XML POST登錄我的用戶,如果身份驗證不起作用,我需要返回XML響應。但是,XML響應的格式需要是自定義的,我不能告訴Devise在哪裏應該更改此輸出。使用Devise自動驗證失敗的自定義XML響應

在我的「user_sessions_controller.rb」我有香草調用「create」方法:

def create 
    resource = warden.authenticate!(:scope => resource_name, 
            :recall => "#{controller_path}#new") 

這將返回:

<errors> 
    <error>Invalid email or password.</error> 
</errors> 

,但我需要把一個包裝解決此:

<AppName> 
    <errors> 
    <error>Invalid email or password.</error> 
    </errors> 
</AppName> 

回答

7

您可以在自定義的應用程序失敗重​​新定義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 

然後將其添加到initializers/devise.rb

config.warden do |manager| 
    manager.failure_app = CustomFailure 
end 

,這增加application.rb

config.autoload_paths += %W(#{config.root}/lib) 

結果:

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> 
+0

美麗的迴應,謝謝! – beeudoublez 2012-01-03 03:37:05