我有一个用户模型:
class User < ActiveRecord::Base
has_secure_password
# validation lets users update accounts without entering password
validates :password, presence: { on: :create }, allow_blank: { on: :update }
validates :password_confirmation, presence: { if: :password_digest_changed? }
end
我还有一个password_reset_controller:
def update
# this is emailed to the user by the create action - not shown
@user=User.find_by_password_reset_token!(params[:id])
if @user.update_attributes(params[:user])
# user is signed in if password and confirmation pass validations
sign_in @user
redirect_to root_url, :notice => "Password has been reset."
else
flash.now[:error] = "Something went wrong, please try again."
render :edit
end
end
你能看出这里的问题吗?用户可以提交一个空白的密码/确认,rails 将让他们登录,因为 User 模型允许在更新时为空白。
这不是安全问题,因为攻击者仍然需要访问用户的电子邮件帐户才能接近此操作,但我的问题是提交 6 个空白字符的用户将被登录,并且他们的密码不会被更改对他们来说,这可能会导致以后的混乱。
所以,我想出了以下解决方案,我想在投入生产之前检查是否有更好的方法:
def update
@user=User.find_by_password_reset_token!(params[:id])
# if user submits blank password, add an error, and render edit action
if params[:user][:password].blank?
@user.errors.add(:password_digest, "can't be blank.")
render :edit
elsif @user.update_attributes(params[:user])
sign_in @user
redirect_to root_url, :notice => "Password has been reset."
else
flash.now[:error] = "Something went wrong, please try again."
render :edit
end
end
我应该检查 nil 和空白吗?是否有任何 Rails 模式或惯用的 ruby 技术来解决这个问题?
[Fwiw,我有required: true
html 输入,但也想要这个处理的服务器端。]