Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Has_secure_password rails change password_digest to password

Hello I'm using my Rails app to access an existing project with a database that cannot be changed. So my question is how can i create a session using Bcrypt without the need of having the column password_digest in my DB?, I already have stored in my DB the password in the column password.

Here is my code

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
like image 223
mdiaz00147 Avatar asked Oct 19 '22 02:10

mdiaz00147


1 Answers

Take a look at this quick and dirty sample. It will allow you to use another column for the password digest.

You will still need to update your existing column to the correct hash values and/or override the appropriate methods to use another algorithm if needed.

The has_secure_password code is pretty simple, so you could use it as a template to roll your own authentication that works for your situation.

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
like image 144
TWA Avatar answered Oct 31 '22 16:10

TWA