/app/models/user.rb

https://github.com/abalasu3/bc_app · Ruby · 65 lines · 52 code · 13 blank · 0 comment · 6 complexity · f647be412899d142421affefd849028b MD5 · raw file

  1. require 'digest'
  2. class User < ActiveRecord::Base
  3. has_many :posts, :dependent => :destroy
  4. has_many :replies, :dependent => :destroy
  5. has_many :vote_posts
  6. has_many :votereplies
  7. attr_accessor :password
  8. attr_accessible :name, :email, :password, :password_confirmation
  9. email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  10. validates :name, :presence => true,
  11. :length => { :maximum => 50 }
  12. validates :email, :presence => true,
  13. :format => { :with => email_regex },
  14. :uniqueness => { :case_sensitive => false }
  15. validates :password, :presence => true,
  16. :confirmation => true,
  17. :length => { :within => 6..40 }
  18. before_save :encrypt_password
  19. def has_password?(submitted_password)
  20. encrypted_password == encrypt(submitted_password)
  21. end
  22. def self.authenticate(email, submitted_password)
  23. user = find_by_email(email)
  24. return nil if user.nil?
  25. return user if user.has_password?(submitted_password)
  26. end
  27. def self.authenticate_with_salt(id, cookie_salt)
  28. user = find_by_id(id)
  29. (user && user.salt == cookie_salt) ? user : nil
  30. end
  31. def self.search(search)
  32. if search
  33. find(:all, :conditions => ['name LIKE ?',"%#{search}%"])
  34. else
  35. find(:all)
  36. end
  37. end
  38. private
  39. def encrypt_password
  40. self.salt = make_salt unless has_password?(password)
  41. self.encrypted_password = encrypt(password)
  42. end
  43. def encrypt(string)
  44. secure_hash("#{salt}--#{string}")
  45. end
  46. def make_salt
  47. secure_hash("#{Time.now.utc}--#{password}")
  48. end
  49. def secure_hash(string)
  50. Digest::SHA2.hexdigest(string)
  51. end
  52. end