Has_secure_password Rails 将password_digest 更改为password

mdi*_*147 5 ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

您好,我正在使用 Rails 应用程序访问具有无法更改的数据库的现有项目。所以我的问题是,如何Bcrypt在不需要password_digest数据库中包含该列的情况下创建会话?我已经在数据库中存储了该列中的密码password

这是我的代码

def create
     user = User.find_by(email: params[:session][:email].downcase)
     # user.update_attribute(:last_login, DateTime.now)
    if user && user.authenticate(params[:session][:password])
      log_in user

      flash[:success] = "Bienvenido de nuevo #{current_user.name.upcase}"
      redirect_to user
    else
      flash[:danger] = 'Email invalido/Contrasena incorrecta' # Not quite right!
      render 'new'
    end

  end
Run Code Online (Sandbox Code Playgroud)

Dan*_*olt 3

看看这个快速而肮脏的样本。它将允许您使用另一列作为密码摘要。

您仍然需要将现有列更新为正确的哈希值和/或覆盖适当的方法以使用其他算法(如果需要)。

has_secure_password 代码非常简单,因此您可以使用它作为模板来推出适合您情况的自己的身份验证。

require 'active_record'
require 'active_model'

login = 'jdoe'
password = '12345678'
wrong_password = 'abcdefgh'

ActiveRecord::Base.establish_connection(
  adapter:  'sqlite3',
  database: 'test.db'
)

unless ActiveRecord::Base.connection.table_exists?(:users)
  ActiveRecord::Base.connection.create_table :users do |t|
    t.string :username
    t.string :some_other_digest_column_name
  end
end

class User < ActiveRecord::Base
  has_secure_password
  alias_attribute :password_digest, :some_other_digest_column_name
end

unless User.where(username: login).any?
  User.create(username: login, password: password)
end

user = User.where(username: login).first

puts 'Using correct password:'

if user.authenticate(password)
  puts 'User successfully authenticated!'
else
  puts 'User not authenticated.'
end

puts
puts 'Using wrong password:'

if user.authenticate(wrong_password)
  puts 'User successfully authenticated!'
else
  puts 'User not authenticated.'
end
Run Code Online (Sandbox Code Playgroud)