Custom XML response for auth fail using Devise

I use XML POST to log in to my users, and I need to return an XML response if authentication does not work. However, the XML response format should be normal, and I cannot say where in Devise I have to change this output.

In my create method for user_sessions_controller.rb, I have a vanilla call:

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

This is returning:

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

but I need to put a wrapper around this:

<AppName>
  <errors>
    <error>Invalid email or password.</error>
  </errors>
</AppName>
+5
source share
1 answer

You can override the method http_auth_bodyin your custom reject application:

# 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

then add this to initializers/devise.rb:

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

and add this to application.rb:

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

result:

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

All Articles