Sha256: feda4e80fc1f09b9ffcf39225fbd4e4736274207f4ec6e4813538a63de801710

Contents?: true

Size: 1.05 KB

Versions: 1

Compression:

Stored size: 1.05 KB

Contents

module Passwd::Rails
  module ActiveRecordExt
    def with_authenticate(passwd: nil, user_id: :email, password: :password)
      passwd ||= Passwd.current
      define_singleton_auth_with_passwd(user_id)
      define_instance_auth_with_passwd(passwd, password)
      define_instance_set_password(passwd, password)
    end

    private

      def define_singleton_auth_with_passwd(user_id_col)
        define_singleton_method :authenticate do |user_id, plain|
          user = find_by(user_id_col => user_id)
          return nil unless user

          user.authenticate(plain) ? user : nil
        end
      end

      def define_instance_auth_with_passwd(passwd, password_col)
        define_method :authenticate do |plain|
          BCrypt::Password.new(send(password_col)) == plain
        end
      end

      def define_instance_set_password(passwd, password_col)
        define_method :set_password do |plain = nil|
          plain ||= passwd.random
          send("#{password_col}=", passwd.password_hashing(plain))
          plain
        end
      end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
passwd-0.4.0 lib/passwd/rails/active_record_ext.rb