New User Form with Rails and Bcrypt

907 views Asked by At

For my small Rails application, I am using bcrypt to hash users' passwords when they are stored. However, when loading the new user form, I was hit with "invalid hash" for the password, as my new action was

def new
  @user = User.new
end

which does not make a new password, which is thus invalid. To remedy this, I tried using

<%= form_for :user, url: users_path do |f| %>

which does not require a user object, allowing me to make that in the create action. However, error handling still needs the User object and throws a nil error

I feel that there should be a "right" way to do this. Can anyone enlighten me?

My user model is as such:

require 'bcrypt'

class User < ActiveRecord::Base
# For user of user.password_hash. Thanks, bcrypt!
include BCrypt

before_save { self.email = email.downcase }

# Validates uniqueness of email
validates_uniqueness_of :email

# Set relationship to lists
has_many :lists

def make_new_password
    new_password = Array.new(10).map { (65 + rand(58)).chr }.join
    self.password_hash = Password.create(new_password)
end

def password
    @password ||= Password.new(password_hash)
end

def password=(new_password)
    @password = Password.create(new_password)
    self.password_hash = @password
end
end
1

There are 1 answers

2
Dmitry Matveev On BEST ANSWER

I feel like this book can help you find the right way to do user authentication. (sorry that is the best I can do with the information you have provided).

Hope this helps :)