回顾与设计不同的行动

时间:2014-05-13 05:51:44

标签: ruby-on-rails devise warden

class Api::V1::SessionsController < Devise::SessionsController
  skip_before_filter :verify_authenticity_token,
                     :if => Proc.new { |c| c.request.format == 'application/json'}

  respond_to :json

  def create
    warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")
    render :status => 200,
           :json => { :success => true,
                      :info => "Logged in",
                      :data => { :auth_token => current_user.authentication_token } }
  end

  def destroy
    warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")
    current_user.update_column(:authentication_token, nil)
    render :status => 200,
           :json => { :success => true,
                      :info => "Logged out",
                      :data => {} }
  end

  def failure
    render :status => 401,
           :json => { :success => false,
                      :info => "Login Failed",
                      :data  => {} }
  end

end

当我输入错误的电子邮件或密码时,我会收到以下json:{error:"Invalid email or password"}。这很好,并且解决了我遇到的最初问题,但是监狱长什么时候回忆起#failure

1 个答案:

答案 0 :(得分:0)

这是因为Devise将始终将其FailureApp#http_auth回调here称为非导航请求格式(例如json)。

我不知道如何在不实现自己的FailureApp的情况下解决这种问题。来自Devise Wiki的This is an example使用自定义FailureApp但问题略有不同。

PS。您也可以考虑使用Warden::Proxy#authenticate方法。