在 Authlogic 中强制验证空白密码
-
24-09-2019 - |
题
我正在向使用 Authlogic 的 Rails 应用程序添加密码重置功能。我正在遵循这里的指南: http://www.binarylogic.com/2008/11/16/tutorial-reset-passwords-with-authlogic/ 除了一件事之外,一切都按照我的意愿进行:密码重置表单接受空白密码,并且不会更改它们。
我一直在四处寻找,并了解到这是预期的默认行为,因为它允许您使用户编辑表单仅在输入新密码时更改用户的密码,否则忽略它。但在这种情况下,我特别想强制验证密码,就像用户最初注册时一样。我已经找到了解决此问题的两种可能的解决方案,但无法弄清楚如何实现其中任何一个。
1)有人在 Google 网上论坛上问了同样的问题:
本的回应是使用 @user.validate_password = true
强制验证密码。我尝试了这个,但出现了未定义的方法错误: undefined method 'validate_password_field=' for #<User>
.
2)似乎有一个名为 Authlogic 配置选项 ignore_blank_passwords
. 。它记录在这里:
模块:Authlogic::ActsAsAuthentic::密码::Config#ignore_blank_passwords
这看起来像是可行的,但我的理解是,这是您在初始配置中使用的全局配置选项 acts_as_authentic
调用用户模型,我不想在应用程序范围内更改它,因为我确实有一个针对用户的常规编辑表单,我希望默认情况下忽略空白密码。
有人找到解决这个问题的方法吗?我懂了 validate_password=
在 Authlogic 1.4.1 的更改日志中,此后没有任何内容被删除。我只是错误地使用它吗?有没有办法使用 ignore_blank_passwords
基于每个请求?
解决方案
这就是我所做的。
class User < ActiveRecord::Base
attr_accessor :ignore_blank_passwords
# object level attribute overrides the config level
# attribute
def ignore_blank_passwords?
ignore_blank_passwords.nil? ? super : (ignore_blank_passwords == true)
end
end
现在在你的控制器中,设置 ignore_blank_passwords
属性为 false。
user.ignore_blank_passwords = false
在这里,您是在 AuthLogic 的范围内工作。您不必更改验证逻辑。
其他提示
这是一个旧线程,但由于尚未得到答复,我将发布此内容。
我已经设法比其他解决方案做得更干净一点,用我自己的解决方案“帮助”authlogic 验证。
我将其添加到用户:
class User < ActiveRecord::Base
...
attr_writer :password_required
validates_presence_of :password, :if => :password_required?
def password_required?
@password_required
end
...
end
您可以通过制作将其减少为两行 attr_accessor
并使用 :if => :password_required
(没有询问),但我更喜欢带有询问符号的其他语法。
然后你的控制器操作可以像这样完成:
def update
@user.password = params[:user][:password]
@user.password_confirmation = params[:user][: password_confirmation]
@user.password_required = true
if @user.save
flash[:notice] = "Password successfully updated"
redirect_to account_url
else
render :action => :edit
end
end
这将产生局部影响;应用程序的其余部分不会受到影响(除非 password_required
在其他地方设置为true,即)。
我希望它有帮助。
User.ignore_blank_passwords = false
使用模型而不是对象来设置此属性。
def update_passwords
User.ignore_blank_passwords = false
if @user.update_attributes(params[:user])
...
end
User.ignore_blank_passwords = true
end
也许测试控制器中的参数值?(航空代码):
def update
@user.password = params[:user][:password]
@user.password_confirmation = params[:user][: password_confirmation]
if @user.password.blank?
flash[:error] = "Password cannot be blank"
render :action => :edit
return
end
if @user.save
flash[:notice] = "Password successfully updated"
redirect_to account_url
else
render :action => :edit
end
end
除了 zetetic 的解决方案之外,您还可以这样做:
def update
@user.password = params[:user][:password]
@user.password_confirmation = params[:user][: password_confirmation]
if @user.changed? && @user.save
flash[:notice] = "Password successfully updated"
redirect_to account_url
else
render :action => :edit
end
end
您基本上是在检查 authlogic 是否更改了用户记录(如果密码为空则不会更改)。在 else 块中,您可以检查密码是否为空,并向用户记录添加适当的错误消息或显示闪现消息。