2

I've just started out using MongoDB and, in particular, Mongoid.

naturally I'd like to ensure my User's passwords are kept nice and secure, and previously I'd have done this with ActiveRecord and used bcrypt. I'm looking for a nice, clean, secure, simple way to implement the same sort of thing using Mongoid.

I've taken a look at mongoid-encryptor but I've not quite got my head around how to use it.

Assume my simplified User looks like this, as per the example in mongoid-encryptor's Readme file.

class User
  include Mongoid::Document
  include Mongoid::Encryptor
  field :name
  field :password
  encrypts :password
end

And in my WebApp (using Sinatra in this case) I'd define a helper such as

def login (name, cleartxtpass)
  return User.where(name: name, password: cleartxtpass).first
end
  1. How do I get it to use bcrypt?
  2. Is there any pre-processing I need to do with cleartxtpass or will Mongoid::Encryptor just handle that? It's not clear from the docs.
Dave Sag
  • 13,266
  • 14
  • 86
  • 134

2 Answers2

4

Okay well after some digging I decided to not bother using Mongoid::Encryptor but to stick to the tried and tested way I used to do these things when using ActiveRecord.

So now my User looks like

class User
  include Mongoid::Document
  field :name, type: String
  field :password_hash, type: String
  index({name: 1}, {unique: true, name: 'user_name_index'})

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

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

and my authenticate helper method looks like

  def auth_user(username, password)
    user = User.where(name: username).first
    return user if user && user.password == password
    return nil
  end

That works a treat.

Dave Sag
  • 13,266
  • 14
  • 86
  • 134
0

The simply way to do it is:

class User
  include Mongoid::Document
  include ActiveModel::SecurePassword

  field :name, type: String
  field :password_digest, type: String

  has_secure_password
end
Di Sheng
  • 1
  • 1