在 Rails 中使用 Devise gem 显示失败消息

Displaying failure messages using Devise gem in Rails

你好
我在显示设计失败消息时遇到问题。无论我做什么,即使帐户被锁定,我也总是收到“无效”消息。我的目标是在 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

我在 Whosebug 上找到了其他主题(例如 Some devise messages are not shown, ),那里有人说是因为偏执模式,所以我禁用了它,但它仍然没有解决我的问题。无论我在 Devise 配置文件中输入什么,Devise 似乎都不会显示除“无效”之外的任何其他消息(last_attempt_warning 也没有显示)。

这是与失败相关的 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."

我试图通过在会话控制器中创建一个方法来解决它:

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] 并显示无效消息。

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

您没有在 before_action 中停止请求周期,因此请求继续调用覆盖 flash[:alert]create 操作。来自 documentation:

If a "before" filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter, they are also cancelled.

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