Wylliam Judd
Wylliam Judd

Reputation: 10925

uninitialized constant User::BCrypt (version related?)

I'm getting the error "uninitialized constant User::BCrypt".

I checked this question: https://github.com/ryanb/nifty-generators/issues/68

Suggested solution to bundle install doesn't work (of course, I bundle install frequently).

I checked this question: https://github.com/codahale/bcrypt-ruby/issues/89

Suggested solution to change the gem to 'bcrypt-ruby' instead of just 'bcrypt' does update my gem to a newer version, but doesn't solve the problem.

Here's my User Model

class User < ActiveRecord::Base
  validates :username, :password_digest, :session_token, presence: true
  validates :session_token, uniqueness: true
  attr_reader :password

  def self.find_by_credentials(username, password)
    user = User.find_by_username(username)
    user.try(:valid_password?, password) ? user : nil
  end

  def valid_password?(password)
    BCrypt::Password.new(self.password_digest).is_password?(password)
  end

  def password=(password)
    @password = password
    self.password_digest = BCrypt::Password.create(password)
  end

  def reset_session_token
    self.session_token = SecureRandom.urlsafe_base64
    self.save!
    self.session_token
  end
end

Upvotes: 4

Views: 4583

Answers (2)

max
max

Reputation: 102240

Unless your application is purely for learning purposes you should seriously consider using ActiveModel::SecurePassword which is built into rails.

Reinventing the authentication wheel is one the most common security failures.

# make sure your users table has a password_digest column!
class User < ActiveRecord::Base
  has_secure_password
end

You also don't wan't to store session tokens on your user model in the database. Instead you should use Rails built in session mechanism.

The rails middleware issues a session identifier in a cookie to all visitors. The cookie simply contains an 32 byte long MD5 hash which is linked to a session storage (stored in another cookie by default).

You can invalidate the session at any point by calling reset_session.

In fact your models SHOULD NOT be aware of the session in any way.

See:

Upvotes: 0

Shani
Shani

Reputation: 2541

from what I can see I cant see are requiring 'bcrypt' in your user model

require 'bcrypt'
class User < ActiveRecord::Base
 ...
end

Upvotes: 7

Related Questions