密码

时间:2015-07-12 13:57:51

标签: ruby-on-rails

我创建了一个项目,允许用户通过添加他们的电子邮件来邀请其他用户。当他们添加电子邮件时,会创建一个用户。但是我在跳过验证方面遇到了一些问题。

在邀请函中,我想跳过密码验证。因为只需要电子邮件。我正在使用BCrypt和has_secure_password。有没有人知道如何跳过这个?

我的邀请_控制器:

def create
  @user = User.new(invite_params)
  if @user.save
    @user.create_invitation_digest
    @user.send_invitation_email
    flash[:success] = 'User invited'
    redirect_to new_invitation_path
  else
    flash.now[:danger] = 'Unable to invite'
    render 'new'
  end
end

和我的用户模型:

validates :name, presence: true, length: { maximum: 50 }, unless: :invited?
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
                  format: { with: VALID_EMAIL_REGEX },
                  uniqueness: { case_sensitive: false }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
belongs_to :company

def invited?
 controller_name = 'invitations'
end

2 个答案:

答案 0 :(得分:1)

一种方法是从模型中 删除 has_secure_password并更改密码验证,如下所示。

validates :password, presence: true, length: { minimum: 6 }, allow_nil: true, unless: :invited?

如果您希望has_secure_password提供 确认密码 ,请手动提供密码确认验证,如下所示。

validates_confirmation_of :password

如果您希望对has_secure_password提供的密码进行身份验证,则可以编写自己的 自定义身份验证 ,如下所示。

def password=(password_str)
  @password = password_str
  self.password_salt   = BCrypt::Engine.generate_salt
  self.password_digest = BCrypt::Engine.hash_secret(password_str, password_salt)
end

def authenticate(password)
  password.present? && password_digest.present? && password_digest == BCrypt::Engine.hash_secret(password, password_salt)
end

答案 1 :(得分:0)

你也可以这样做:

在模型中声明属性并在控制器中将其值设置为true。仅当模型的值为false时才在模型中执行has_secured_pa​​ssword。

user.rb

attr_accessor: skip_validation // Add this line
has_secured_password, :unless => :skip_validation  // Add IF condition here

user_controller.rb

def create
@user = User.new(invite_params)
@user.skip_validation = true // Add this line
  if @user.save
    @user.create_invitation_digest
    @user.send_invitation_email
    flash[:success] = 'User invited'
    redirect_to new_invitation_path
  else
    flash.now[:danger] = 'Unable to invite'
    render 'new'
  end
end