我有一个用户模型:
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
您可以在这里看到问题吗?用户可以提交空白密码/确认,而导轨将签名,因为用户模型允许更新时空白。
这不是安全问题,因为攻击者仍需要访问用户的电子邮件帐户,然后才能接近此操作,但我的问题是,提交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
我应该检查零和空白吗?是否有用于解决此问题的轨道图案或惯用红宝石技术?
[fwiw,我在HTML输入上有required: true
,但也想要此处理的服务器端。]
请尝试:
我们可以使用 - 存在?
ex:
if !params[:user][:password].present?