Подтвердить что ты не робот

Как удалить перенаправление html в devity authenticate_user

Я использую devity authenticate_user! метод в контроллере. Это нормально работает, когда auth_token, предоставленный в запросе, является правильным, но если аутентификация завершается неудачно, я получаю:

curl -XGET 'http://localhost:3000/my_obj?auth_token=wrongtoken'

<html><body>You are being <a href="#" onclick="location.href='http://localhost:3000/users/sign_in'; return false;">redirected</a>.</body></html>

Как я использую rabl, лучший способ иметь что-то вроде

{'error' : 'authentication error'}

вернулся с перенаправлением html?

4b9b3361

Ответ 1

Я делаю это, чтобы избежать фильтра с помощью: format = > : json response и сделать собственный фильтр, чтобы отобразить мой ответ JSON, если no current_user не прошел

class MyController < ApplicationController
  before_filter :authenticate_user!, :unless => { request.format == :json }
  before_filter :user_needed, :if => { request.format == :json }

  def user_needed
    unless current_user
      render :json => {'error' => 'authentication error'}, :status => 401
    end
  end
end

Другой способ, может быть более чистым - определить свой собственный FailureApp (https://github.com/plataformatec/devise/blob/master/lib/devise/failure_app.rb)

class MyFailureApp < Devise::FailureApp
  def respond
    if request.format == :json
      json_failure
    else
      super
    end
  end

  def json_failure
    self.status = 401
    self.content_type = 'application/json'
    self.response_body = "{'error' : 'authentication error'}"
  end
end

В вашем конфигурационном файле Devise добавьте:

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

Ответ 2

В новых версиях Devise (я использую 2.2.0) вы можете использовать опцию navigational_formats в конфигурационном файле Devise, devise.rb:

# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
config.navigational_formats = ["*/*", :html]

Пока :json не находится в этом списке, а ваш запрос заканчивается на .json, он будет вести себя так, как вы хотите.