Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'openssl'
- require 'digest/sha2'
- require 'base64'
- class User < ActiveRecord::Base
- attr_accessor :password, :password_confirmation
- attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :birthday, :weight, :bodyfat, :gender
- validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
- validates_uniqueness_of :email, :case_sensitive => false
- validates_length_of :first_name, :in => 1..30, :too_short => "can't be blank"
- validates_length_of :last_name, :in => 1..30, :too_short => "can't be blank"
- validates_length_of :password, :minimum => 6, :if => :password_needs_validating?
- validates_confirmation_of :password, :if => :password_needs_validating?
- validates_inclusion_of :gender, :in => %w( M F )
- has_many :weight_entries
- has_many :bodyfat_entries
- has_many :workouts
- acts_as_tagger
- # returns the users full name
- def full_name
- first_name + " " + last_name
- end
- # sets the password
- def password=(password)
- if !password.blank?
- @password_changed = true
- @password = password
- # generate a new salt and hash the password
- self.salt = User.random_salt
- self.hashed_password = encrypt_password(password)
- end
- end
- # encrypts a password based on the user's salt and the current encryption
- # technique
- def encrypt_password(password)
- Digest::SHA256.hexdigest(password + self.salt)
- end
- # verifies a password against the existing password
- def verify_password(password)
- return hashed_password == encrypt_password(password)
- end
- # returns a salt for a password
- def self.random_salt
- return Salt.random_salt
- end
- # sets this object's password reset hash and expiration date
- def set_password_reset_hash
- self.password_reset_expires = 3.days.from_now
- self.password_reset_hash = Digest::SHA256.hexdigest(rand().to_s + Time.now.to_s)
- save!
- end
- # finds a user by a valid password reset hash
- def self.find_by_valid_password_reset_hash(hash)
- return nil if hash.blank?
- User.find(:first,
- :conditions => ["password_reset_hash = ? AND password_reset_expires > ?",
- hash, Time.now])
- end
- # builds a remember_token and saves it to the user
- def remember_login
- token = RememberToken.new
- token.user = self
- token.expires = 1.month.from_now
- token.token = Digest::SHA2.hexdigest("#{rand.to_s}--#{Time.now.to_i}")
- token.save!
- return token
- end
- # forgets the user's login
- def forget_login(token)
- token = RememberToken.find_by_token(token)
- token.destroy if token
- end
- private
- # lets us know that we need to validate the password
- def password_needs_validating?
- self.new_record? || @password_changed
- end
- end
Add Comment
Please, Sign In to add comment