Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # == Schema Information
- # Schema version: 20110127044339
- #
- # Table name: users
- #
- # id :integer not null, primary key
- # name :string(255)
- # email :string(255)
- # created_at :datetime
- # updated_at :datetime
- # encrypted_password :string(255)
- # salt :string(255)
- # gender :string
- # birthday :date
- # city :string(255)
- #
- require 'digest'
- class User < ActiveRecord::Base
- attr_accessor :password
- attr_accessible :name, :email, :password, :password_confirmation,
- :gender, :birthday, :city, :educations_attributes
- email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
- gender_regex = /[MFU]/i
- validates :name, :presence => true,
- :length => { :maximum => 50 }
- validates :email, :presence => true,
- :format => { :with => email_regex },
- :uniqueness => { :case_sensitive => false }
- validates :password, :presence => true,
- :confirmation => true,
- :length => { :within => 6..40 }
- validates :gender, :format => { :with => gender_regex }
- #validates :birthday, :presence => false
- validates :city, :length => { :minimum => 1 }, :allow_nil => true
- before_save :encrypt_password
- has_many :friendships
- has_many :friends, :through => :friendships
- has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
- has_many :inverse_friends, :through => :inverse_friendships, :source => :user
- has_many :educations
- accepts_nested_attributes_for :educations,
- :allow_destroy => true,
- :reject_if => proc {
- |attrs| attrs[:title].blank?
- }
- def self.authenticate(email, submitted_password)
- user = find_by_email(email)
- return nil if user.nil?
- return user if user.has_password?(submitted_password)
- end
- def self.authenticate_with_salt(id, cookie_salt)
- user = find_by_id(id)
- (user && user.salt == cookie_salt) ? user : nil
- end
- def has_password?(submitted_password)
- encrypted_password == encrypt(submitted_password)
- end
- private
- def encrypt_password
- self.salt = make_salt if new_record?
- self.encrypted_password = encrypt(password)
- end
- def encrypt(string)
- secure_hash("#{salt}--#{string}")
- end
- def make_salt
- secure_hash("#{Time.now.utc}--#{password}")
- end
- def secure_hash(string)
- Digest::SHA2.hexdigest(string)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement