matthewtodd / has_digest

ActiveRecord macro that helps encrypt passwords and generate api tokens before_save.

This URL has Read+Write access

matthewtodd (author)
Mon Nov 10 23:33:13 -0800 2008
commit  c9793a8134933b4ecd328ebf0228e39db6d2ee1a
tree    d75b49dd0153da6afe6e258ee587b8d744652083
parent  3df9dbab1b99aa388a57a82693b34768f139ff11
has_digest / README.rdoc
100644 56 lines (35 sloc) 1.312 kb

HasDigest

HasDigest is an ActiveRecord macro that makes it easy to write things like encrypted passwords and api tokens before_save. Digest attributes may either stand alone or depend on the values of other attributes. Digests with dependencies are also magically salted for models having a salt attribute.

See the documentation for the has_digest method for options.

Installation

As a gem:

  config.gem 'matthewtodd-has_digest', :lib => 'has_digest', :source => 'http://gems.github.com'

As a plugin:

  script/plugin install git://github.com/matthewtodd/has_digest.git

Usage

In your model:

  class User < ActiveRecord::Base
    has_digest :encrypted_password, :depends => :password
  end

In your migrations:

  class CreateUsers < ActiveRecord::Migration
    def self.up
      create_table :users do |t|
        t.string :salt, :encrypted_password, :limit => 40
      end
    end

    def self.down
      drop_table :users
    end
  end

In your tests:

  class UserTest < ActiveSupport::TestCase
    should_have_digest :encrypted_password, :depends => :password
  end

Back in your model:

  class User < ActiveRecord::Base
    def authenticate(password)
      encrypted_password == digest(salt, password)
    end
  end

Copyright © 2008 Matthew Todd, released under the MIT license