Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom XML response for auth failure using Devise

I'm using an XML POST to sign in my users and I need to return an XML response if the authentication didn't work. However, the format of the XML response needs to be custom, and I can't tell where in Devise I should change this output.

In my 'create' method for the 'user_sessions_controller.rb' I have the vanilla call:

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

This is returned:

<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>
like image 599
beeudoublez Avatar asked Jan 02 '12 00:01

beeudoublez


1 Answers

You can redefine http_auth_body method in your custom failure app:

# 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>
like image 103
Vasiliy Ermolovich Avatar answered Oct 16 '22 14:10

Vasiliy Ermolovich