title: How to protect a user password with bcrypt and mongoid
body: <p>I've just started out using <code>MongoDB</code> and, in particular, <code>Mongoid</code>.</p>
  
  <p>naturally I'd like to ensure my <code>User</code>'s passwords are kept nice and secure, and previously I'd have done this with <code>ActiveRecord</code> and used <code>bcrypt</code>. I'm looking for a nice, clean, secure, simple way to implement the same sort of thing using <code>Mongoid</code>.</p>
  
  <p>I've taken a look at <a href="https://github.com/juno/mongoid-encryptor" rel="nofollow">mongoid-encryptor</a> but I've not quite got my head around how to use it.</p>
  
  <p>Assume my simplified <code>User</code> looks like this, as per the example in <code>mongoid-encryptor</code>'s Readme file.</p>
  
  <pre><code>class User
    include Mongoid::Document
    include Mongoid::Encryptor
    field :name
    field :password
    encrypts :password
  end
  </code></pre>
  
  <p>And in my WebApp (using <code>Sinatra</code> in this case) I'd define a helper such as</p>
  
  <pre><code>def login (name, cleartxtpass)
    return User.where(name: name, password: cleartxtpass).first
  end
  </code></pre>
  
  <ol>
  <li>How do I get it to use <code>bcrypt</code>?</li>
  <li>Is there any pre-processing I need to do with <code>cleartxtpass</code> or will <code>Mongoid::Encryptor</code> just handle that?  It's not clear from the docs.</li>
  </ol>