Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 28th, 2012  |  syntax: None  |  size: 1.16 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. require 'digest'
  2. class User < ActiveRecord::Base
  3.   attr_accessor :password
  4.  
  5.   validates :email, :uniqueness => true,
  6.                     :length => { :within => 5..50 },
  7.                     :format => { :with => /^[^@][\w.-]+@[\w.-]+[.][a-z]{2,4}$/i }
  8.   validates :password, :confirmation => true,
  9.                        :length => { :within => 4..20 },
  10.                        :presence => true,
  11.                        :if => :password_required?
  12.  
  13.   has_one :profile
  14.   has_many :articles, :order => 'published_at DESC, title ASC',
  15.                       :dependent => :nullify
  16.   has_many :replies, :through => :articles, :source => :comments
  17.  
  18.   before_save :encrypt_new_password
  19.  
  20.   def self.authenticate(email, password)
  21.     user = find_by_email(email)
  22.     return user if user && user.authenticated?(password)
  23.   end
  24.  
  25.   def authenticated?(password)
  26.     self.hashed_password == encrypt(password)
  27.   end
  28.  
  29.   protected
  30.     def encrypt_new_password
  31.       return if password.blank?
  32.       self.hashed_password = encrypt(password)
  33.     end
  34.  
  35.     def password_required?
  36.       hashed_password.blank? || password.present?
  37.     end
  38.  
  39.     def encrypt(string)
  40.       Digest::SHA1.hexdigest(string)
  41.     end
  42. end