覆盖设计SessionsController销毁

时间:2014-10-07 17:03:00

标签: ruby-on-rails json devise destroy

我试图从Devise的SessionsController覆盖destroy方法,但我还没有成功。我已经为create方法完成了该操作,但我不知道为什么它不适用于destroy方法。

这是我的SessionsController

module Api
  module V1
    class SessionsController < Devise::SessionsController
      skip_before_filter :verify_authenticity_token, if: :json_request?

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

      def sign_in_and_redirect(resource_or_scope, resource=nil)
        scope = Devise::Mapping.find_scope!(resource_or_scope)
        resource ||= resource_or_scope
        sign_in(scope, resource) unless warden.user(scope) == resource
        return render :json => {:success => true}
      end

      # DELETE /resource/sign_out
      def destroy
        puts "DELETE /resource/sign_out"

        return render :json => {:success => true}
      end

      def failure
        return render :json => {:success => false, :errors => ["Login failed."]}
      end

      protected

      def json_request?
        request.format.json?
      end
    end
  end
end

如果我使用以下curl请求,则create方法可以正常运行:

curl -X POST -H "Accept: application/json"  -H "Content-Type: application/json" http://localhost:3000/users/sign_in -d '{"user":{"email":"demian@toptierlabs.com", "password":"TopTier2011"}}'

但是当我使用它时:

curl -X DELETE -H "Accept: application/json"  -H "Content-Type: application/json" http://localhost:3000/users/sign_out

我得到<html><body>You are being <a href="http://localhost:3000/">redirected</a>.</body></html>作为回复,puts "DELETE /resource/sign_out"来电永远不会发生。

这是我在Rails STDOUT输出中得到的结果:

Started DELETE "/users/sign_out" for 127.0.0.1 at 2014-10-07 14:51:40 -0200
Processing by Api::V1::SessionsController#destroy as JSON
  Parameters: {"session"=>{}}
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
Redirected to http://localhost:3000/
Filter chain halted as :verify_signed_out_user rendered or redirected
Completed 302 Found in 278ms (ActiveRecord: 0.0ms)

谢谢你,对不起我的英文!

1 个答案:

答案 0 :(得分:24)

您可能需要skip_before_action :verify_signed_out_user。 请查看https://github.com/plataformatec/devise/blob/master/app/controllers/devise/sessions_controller.rb第4行。