gpt4 book ai didi

ruby-on-rails - 在登录期间优雅地处理设计 401

转载 作者:行者123 更新时间:2023-12-04 05:31:30 24 4
gpt4 key购买 nike

我有一个非常简单的设计用户登录页面。提交不正确的数据后,日志显示“401 Unauthorized”并将我重定向回登录页面。我想不出一种向用户显示错误消息的方法。

我看了devise::sessions_controller#create如下所示,


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

def auth_options
{ :scope => resource_name, :recall => "#{controller_path}#new" }
end

流程在 warden.authenticate 中断如果身份验证失败,用户将被重定向到"new"页面,即登录页面。

我只需要向用户显示 invalid_credentials 工具提示/flash_message。所以我通过修改 :recall => "#{controller_path}#handle_create_fail" (look at <code>auth_options</code>) which calls handle_create_fails 来做到这一点当身份验证失败时,我在其中设置了错误消息。

我不确定我是否忽略了设计已经提供的东西。

我怎样才能更好地处理这个问题?

最佳答案

'devise' 将错误消息存储在 rails 'flash' 中,使用 flash[:notice] 表示成功消息,使用 flash[:alert] 表示问题。

这是来自 devise documentation 的:

Remember that Devise uses flash messages to let users know if sign in was successful or failed. Devise expects your application to call "flash[:notice]" and "flash[:alert]" as appropriate.

这意味着在您的 View 文件中(或更一般地在您的应用程序布局文件中)您应该包含类似于这些行的内容:

<%= content_tag(:div, flash[:error], :id => "flash_error") if flash[:error] %>
<%= content_tag(:div, flash[:notice], :id => "flash_notice") if flash[:notice] %>
<%= content_tag(:div, flash[:alert], :id => "flash_alert") if flash[:alert] %>

以下是一些类似的问题/答案:

Rails - Devise - Error messages when signing in?

Devise errors are displayed twice

devise - Customizing the User Edit Pages

关于ruby-on-rails - 在登录期间优雅地处理设计 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10446760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com