【问题标题】:Displaying failure messages using Devise gem in Rails在 Rails 中使用 Devise gem 显示失败消息
【发布时间】:2021-11-29 11:41:13
【问题描述】:

您好
我在显示设计失败消息时遇到问题。无论我做什么,即使帐户被锁定,我总是会收到“无效”消息。我的目标是在 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 上找到了其他主题(例如 Some devise messages are not shownDevise: lockable - last_attempt_warning not displaying),人们说这是因为偏执模式,这就是我禁用它的原因,但它仍然不能解决我的问题。无论我在 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."

我试图通过在 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-rails ruby devise


    【解决方案1】:

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

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

    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
    

    【讨论】:

    • 太棒了。这对我行得通。一个额外的问题。任何想法为什么设计的默认功能不起作用?理想情况下,我想摆脱这种方法,只依靠设计来显示锁定的消息。
    • @BartoszChodyła 乍一看并非如此。唯一不合适的是config.unlock_keys = [:time]。该值通常为:email,因为它用于查找用户(Source code),但我不相信在会话控制器中调用此方法
    • 我从这里拿的:stackoverflow.com/questions/13184514/… 我相信它是标准配置 config.unlock_strategy = :time
    猜你喜欢
    • 2012-12-19
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多