首页 > 解决方案 > 在 Rails 中使用 Devise gem 显示失败消息

问题描述

您好
,我在显示设计失败消息时遇到问题。无论我做什么,即使帐户被锁定,我总是会收到“无效”消息。我的目标是在 5 次尝试失败后显示“锁定”消息 10 分钟。

gem 配置正确,因为帐户被正确锁定。我唯一的问题是消息。

这是我的 devise.rb 文件中的代码,它与可锁定模块有关:

  config.paranoid = false
  config.lock_strategy = :failed_attempts
  config.unlock_keys = [:time]
  config.unlock_strategy = :time
  config.maximum_attempts = 5
  config.unlock_in = 10.minutes
  config.last_attempt_warning = true

我在 stackoverflow 上找到了其他主题(例如,一些设计消息未显示设计:可锁定 - last_attempt_warning 未显示),人们说这是因为偏执模式,这就是我禁用它的原因,但它仍然不能解决我的问题。无论我在 Devise 配置文件中输入什么(last_attempt_warning 也没有显示),Devise 似乎都没有显示除“无效”之外的任何其他消息。

这是与失败相关的 devise.en.yml 的一部分:

en:  
  devise:
   failure:
    already_authenticated: "You are already logged in."
    deactivated: "Your account is no longer active. Please contact your administrator for access."
    inactive: "Your account is not activated yet."
    invalid: "Sorry, the email or password you entered is incorrect."
    last_attempt: "You have one more attempt before your account will be locked."
    locked: "Your account has been locked. Try to log in again in 5 minutes."
    not_found_in_database: "Sorry, the email or password you entered is incorrect."
    timeout: "Your session expired. Please log in again to continue."
    unauthenticated: "You need to log in or sign up before continuing."
    unconfirmed: "You have to confirm your account before continuing."

我试图通过在 Sessions Controller 中创建一个方法来解决它:

before_action :check_failed_attempts, only: :create
def check_failed_attempts
  flash.clear

  email = params["educator"]["email"]
  return unless email

  user = Person.find_by(email: email)
  return unless user

  if user.access_locked?
    flash[:alert] = I18n.t "devise.failure.locked"
  end
end

但设计似乎覆盖了 flash[:alert] 并显示无效消息。

我花了几个小时试图修复它并且已经用完了想法,所以我很感激任何帮助。

标签: ruby-on-railsrubydevise

解决方案


before_action没有停止. 从文档中:createflash[:alert]

如果“之前”过滤器呈现或重定向,则该操作将不会运行。如果有其他过滤器计划在该过滤器之后运行,它们也会被取消。

def check_failed_attempts
  flash.clear

  email = params["educator"]["email"]
  return unless email

  user = Person.find_by(email: email)
  return unless user

  if user.access_locked?
    flash[:alert] = I18n.t "devise.failure.locked"
    redirect_to new_educator_session_path
  end
end

推荐阅读