【问题标题】:warden custom_failure典狱长custom_failure
【发布时间】:2011-12-17 17:51:20
【问题描述】:

我使用设计进行 API 身份验证。我已经像这样覆盖了SessionController:create 方法:

class Users::SessionsController < Devise::SessionsController

  def create
    resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
    set_flash_message(:notice, :signed_in) if is_navigational_format?
    val = sign_in(resource_name, resource)
    current_user.reset_authentication_token!

    respond_to do |format|
      format.html do
        respond_with resource, :location => redirect_location(resource_name, resource)
      end
      format.json do
        render :json => { :status => OK_OK, :auth_token => current_user.authentication_token }.to_json, :status => :ok
      end
    end
  end
end 

如您所见,在使用 JSON 进行身份验证时,我会返回一个状态码。当身份验证失败时,我会收到以下响应:

{"error":"Invalid email or password."}

如何更改此消息?我不知道在哪里覆盖这个warden.authenticate! 方法。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 devise warden


    【解决方案1】:

    您应该实现自己的失败应用。您可以在此处查看和/或继承设计的默认值 https://github.com/plataformatec/devise/blob/master/lib/devise/failure_app.rb

    要设置它,请在您的 config/initializers/devise.rb 配置文件中:

    Devise.setup do |config|
      config.warden do |manager|
        manager.failure_app = CustomFailureApp
      end
    end
    

    【讨论】:

    • 你好 polmiro。当我在上面的文件中设置config.warden do |manager| manager.failure_app = CustomAuthFailure end 并重新启动服务器时,我收到一条错误消息:uninitialized constant CustomAuthFailure (NameError),尽管这是我在lib/devise/custom_auth_failure.rb 中自定义派生的 Devise::FailureApp 的名称。知道我可能做错了什么吗?谢谢!
    • 我根据github.com/heartcombo/devise/wiki/…config/application.rb 中添加了config.autoload_paths &lt;&lt; Rails.root.join('lib/devise') 但现在当我在/sign_up 中发出错误凭据时,我仍然无法进入我的自定义FailureApp 类???
    【解决方案2】:

    在您的语言环境文件(config/locales/ 目录中的文件)上,根据您的 i18n 配置(英文为 en.yml)添加:

    en:
      devise:
        invalid: 'My custom message for invalid login'
    

    当然,将My custom message for invalid login 替换为您想要的消息。

    【讨论】:

    • 不,这不是解决方案。如您所见,我对更改消息本身不感兴趣,而是发送一些我想要的代码。例如:render :json =&gt; { :status =&gt; OK_OK, :auth_token =&gt; current_user.authentication_token }.to_json, :status =&gt; :ok 用于正确的身份验证。对于不正确的我想要类似的东西:render :json =&gt; { :status =&gt; ERROR_AUTH }.to_json, :status =&gt; :unauthorized.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 2017-09-05
    • 2013-12-21
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    相关资源
    最近更新 更多