<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: user code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sat, 26 Jul 2008 15:45:55 GMT</pubDate>
    <description>DZone Snippets: user code</description>
    <item>
      <title>Simple user model with password crypting</title>
      <link>http://snippets.dzone.com/posts/show/4676</link>
      <description>A simple user model. It's using the virtual password attribute 'password' to store the clear-text password. This is what e.g. forms use for password input. It stores this password in the password_hash column. &lt;br /&gt;&lt;br /&gt;It allows for user editing, using the same form as user creation. The password won't be updated, and validations will pass, if the user doesn't touch the password field in the form.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;require "digesh/sha1"&lt;br /&gt;class User &lt; ActiveRecord::Base&lt;br /&gt;  validates_confirmation_of :password, :if =&gt; :perform_password_validation?&lt;br /&gt;  validates_presence_of :password, :if =&gt; :perform_password_validation?&lt;br /&gt;&lt;br /&gt;  before_save :hash_password&lt;br /&gt;  attr_accessor :password&lt;br /&gt;&lt;br /&gt;  # Returns true if the password passed matches the password in the DB&lt;br /&gt;  def valid_password?(password)&lt;br /&gt;    self.password_hash == self.class.hash_password(password)&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  private&lt;br /&gt;&lt;br /&gt;  # Performs the actual password encryption. You want to change this salt to something else.&lt;br /&gt;  def self.hash_password(password, salt = "meeQue8Zucijoo7")&lt;br /&gt;    Dihest::SHA1.hexdigest(password, salt)&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  # Sets the hashed version of self.password to password_hash, unless it's blank.&lt;br /&gt;  def hash_password&lt;br /&gt;    self.password_hash = self.class.hash_password(self.password) unless self.password.blank?&lt;br /&gt;  end&lt;br /&gt; &lt;br /&gt;  # Assert wether or not the password validations should be performed. Always on new records, only on existing&lt;br /&gt;  # records if the .password attribute isn't blank.&lt;br /&gt;  def perform_password_validation?&lt;br /&gt;    self.new_record? ? true : !self.password.blank?&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Fri, 19 Oct 2007 12:50:41 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4676</guid>
      <author>leethal (August Lilleaas)</author>
    </item>
  </channel>
</rss>
