Search code examples
rubysequel

validate presence of password without having a password column in Sequel


I'm trying to validate presence of a 'password' though I don't want to have a password column in my database... I convert the password to a password salt. How can I validate the presence of a password for the before save encryption without having a password column?

SCHEMA:

migration "create users table" do
  database.create_table :users do
    primary_key :id
    text        :name
    text        :email
    text        :username
    text        :password_hash
    text        :password_salt
    index       :username, :unique => true
  end
end

USER MODEL:

class User < Sequel::Model

  require 'bcrypt'

  def before_save
    if password
      self.password_salt = BCrypt::Engine.generate_salt
      self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
    end
  end

  def validate
    super
    validates_presence  [:password,:email] if new?
    validates_unique    [:email]
  end

  def self.authenticate(email, password)
    user = User.find(:email=>email)
    if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
      user
    else
      nil
    end
  end

  def encrypt_password
    if password.present?
      self.password_salt = BCrypt::Engine.generate_salt
      self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
    end
  end

end

When I attempt to validate the presence of a password, I get

NoMethodError: undefined method `password' for #<User @values={:email=>"[email protected]"}>

Solution

  • OK got it...

    I just added:

      attr_accessor :password
    

    It validates its presence without attempting to save to a password column. Thanks :)