如何跳过 has_secure_password 验证 [英] How to skip has_secure_password validations

查看:45
本文介绍了如何跳过 has_secure_password 验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,只有管理员才能创建新的用户记录.用户会通过电子邮件收到一个激活链接,他们可以在其中设置密码.

In my app, only admins can create new User records. The user is emailed an activation link where they set their password.

我想使用 has_secure_passord 方法(railscast):

I'd like to use the has_secure_passord method (railscast):

class User < ActiveRecord::Base
  has_secure_password
  ...
end

效果很好,但它会自动验证密码摘要的存在......因此,当管理员创建记录时,验证失败.我有没有办法只跳过自动添加的 password_digest 验证而不跳过我添加的其他验证?

Works great, but it automatically validates presence of password digest...so when the admin creates the record the validations fail. I there a way to skip just the automatically added password_digest validation without skipping the others I've added?

推荐答案

我决定进行自己的自定义身份验证.以下解决方案将验证密码,但仅在设置密码时.这允许管理员在不添加密码的情况下创建用户.

I decided to do my own custom authentication. The following solution will validate passwords but only when they are being set. This allows admins to create users without adding a password.

class User < ActiveRecord::Base
  include BCrypt

  attr_accessor :password, :password_confirmation

  validates :password, length: (6..32), confirmation: true, if: :setting_password?

  def password=(password)
    @password = password
    self.password_hash = Password.create(password)
  end

  def authenticate(password)
    password.present? && password_hash.present? && Password.new(password_hash) == password
  end

private

  def setting_password?
    password || password_confirmation
  end

end

如果有人发布的答案允许我仍然使用 has_secure_password 方法,我会接受它.

If someone posts an answer that allows me to still use the has_secure_password method, I'll accept it instead.

这篇关于如何跳过 has_secure_password 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆