如何在AJAX中使用Devise用户帐户未确认或锁定状态?

时间:2015-08-21 23:53:16

标签: javascript ruby-on-rails ajax devise devise-confirmable

我正在尝试使用JS处理设计视图来处理响应。我想使用默认设计错误消息,但由于warden.authenticate,我无法获得各种类型的错误(例如未确认;锁定帐户)。所以,我正在使用“抓住”所以它不会抛出406或者其他错误。 我的问题:我知道“抓住[:message] ==:未经证实”给了我“未经证实”的用户状态,应该是“锁定”的相应符号? :锁定不起作用,我找不到文档。

我的Sessions_controller是这样的:     def创建           caught = catch(:warden)做               self.resource = warden.authenticate:scope => RESOURCE_NAME          端

    if resource 
      # User is confirmed
      sign_in(resource_name, resource)
      puts "LOGGED IN!!!"
      respond_to js{
          set_flash_message(:success, :signed_in)
          render :template => "remote_content/flashes.js.erb"
          flash.discard
        }
    elsif caught and caught[:message] == :unconfirmed
      # User is unconfirmed
      puts "UNCONFIRMED ACCOUNT!!!"
      # send the email or display the flash with link to send email
      respond_to js{
          set_flash_message(:error, :problem) #:problem is in devise.en.yml "There is problem in your account, check you email."
          render :template => "remote_content/form_flashes.js.erb"
          flash.discard
        }
    else
      # User is not signed in, should be... error in credentials or locked account....
      puts "ERROR IN CREDENTIALS!!!"
      respond_to js{
          set_flash_message(:error, :invalid)
          render :template => "remote_content/form_flashes.js.erb"
          flash.discard
        }
    end
  end

flashes.js.erb / form_flashes.js.erb执行得很好,没问题!它是这样的:

$('.modal').modal('hide');
// append flash to the body
$('.body').append("<%= escape_javascript raw(flash_normal) %>");

您如何看待我的方法?我应该使用CustomFailure吗?我找不到任何CustomFailure或Devise原创的例子,所以我可以把它用来回应我的JS文件。

1 个答案:

答案 0 :(得分:0)

我通过检查caught发现唯一的消息是unconfirmed并且它从未捕获unlocked状态。所以我必须通过电子邮件获取User并使用设计帮助器access_locked?来获取他的信息。我知道这可能是一个安全故障,但如果它被锁定,你就无法做任何事情。这是上面缺少的代码的一部分:

  ...
  else
  ## User is not signed in, should be... error in credentials or locked...
  ## Let's see if it's locked

  # This function is only used like this (without security)
  # only when the authentication already failed in that action
  # but we still need to get the user in order to check if its locked

  user = User.find_by email: params[:user][:email]
  if !user.nil? and user.access_locked?
    # The small issue: anyone can know that an email is locked without typing the password
    puts "ACCOUNT LOCKED!!!"
    respond_to js{
        set_flash_message(:error, :locked)
        render :template => "remote_content/form_flashes.js.erb"
        flash.discard
      }
  else
    ## If it's not Locked, then it's error in credentials
    puts "ERROR IN CREDENTIALS!!!"
    respond_to js{
        set_flash_message(:error, :invalid)
        render :template => "remote_content/form_flashes.js.erb"
        flash.discard
      }
  end
end

我知道这不是最漂亮的方式,但有效。