为 Devise 按 success/failure 自定义 flash 消息

Customizing flash messages per success/failure for Devise

我正在尝试根据用户会话成功或登录失败生成不同外观的闪存消息。 (主要是改jped图片)

我有一个局部视图处理即显消息并检查密钥,然后显示不同的图像:

_flash_message.html.erb

<% if flash.present? %>
    <% case flash.first[0] %>

<% when "devise_deconnexion" %>

        <div id="flash-message">
            <div id="image">
                <%= image_tag "deconnecte.svg" %>
            </div>
            <div id="affiche">
                <div id="message">
                    <h1>Succès</h1>
                    <h2><%= flash.first[1] %></h2>
                </div>
                <div id="check" style="background-color: #00e691;">
                    <%= image_tag "check_blanc.svg" %>
                </div>
            </div>
        </div>

...

在上面的位中,我检查密钥是否匹配 "devise_deconnexion" 字符串,以便在 flash 消息中显示不同的图像。

我已经能够通过为每个 Devise 模型生成设计会话控制器并按以下方式进行更改来对此进行调整:

sessions_controller.rb

def destroy
    #   super    
    signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name))
    set_flash_message! :devise_deconnexion, :signed_out if signed_out
    yield if block_given?
    respond_to_on_destroy
  end

效果很好。

虽然我很难在用户输入错误密码的情况下更改图像。我不知道在哪里修改闪存密钥。

这是从 github 中获取的 Devise 会话#create 代码:

 # POST /resource/sign_in
  def create
    self.resource = warden.authenticate!(auth_options)
    set_flash_message!(:notice, :signed_in)
    sign_in(resource_name, resource)
    yield resource if block_given?
    respond_with resource, location: after_sign_in_path_for(resource)
  end

我只看到与 :signed_in 消息一起使用的 :notice 键。

我看不到 "wrong password or username" 的闪现消息是在哪里触发的(虽然我确实在输入错误密码时收到了闪现消息)

当用户输入错误的密码时,控制器中的代码执行将停止在此行:

self.resource = warden.authenticate!(auth_options)

之后,失败的请求由所谓的 'Devise Failure application' 处理。

https://github.com/plataformatec/devise/blob/master/lib/devise/failure_app.rb

您可以将那个失败的应用程序替换为您自己的自定义应用程序。

1) 创建自定义故障应用:

class CustomFailureApp < Devise::FailureApp
    # your custom code goes here ....
end

2) 告诉 Devise 使用您的自定义故障应用程序

# initializers/devise.rb
Devise.setup do |config|
  config.warden do |manager|
    manager.failure_app = CustomFailureApp
  end
end

如何自定义 Devise 的 Failure 应用程序以实现您的目标是您要弄清楚的。祝你好运!