Skip to content

Instantly share code, notes, and snippets.

@atheken
Created April 30, 2011 15:21
Show Gist options
  • Save atheken/949743 to your computer and use it in GitHub Desktop.
Save atheken/949743 to your computer and use it in GitHub Desktop.
Critique my model
# == Schema Information
# Schema version: 20110429204914
#
# Table name: users
#
# id :integer not null, primary key
# full_name :string(255)
# email :string(255)
# salt :string(255)
# created_at :datetime
# updated_at :datetime
# crypted_password :string(255)
#
require 'digest/sha1'
class User < ActiveRecord::Base
# :password_confirmation will be generated by the validation machinery below.
attr_accessor :password
# Set the properties that are accessible by the world.
# Note: "salt" and "crypted_password" are not in this list.
attr_accessible :email, :full_name, :email, :password, :password_confirmation
# 'validates_xyz_of' is a shorthand for the real 'validates' method
validates_presence_of :email, :full_name
validates_confirmation_of :password
validates_format_of :email, :with => /.+@.+/
validates_uniqueness_of :email, :case_sensitive => false
# ActiveRecord will run this before each save.
before_save :encrypt_password
def encrypt(value)
# many people use the format "#{salt}--#{value}", why?
Digest::SHA1.hexdigest("#{salt}#{value}")
end
def password_matches?(submitted_password)
crypted_password == encrypt(submitted_password)
end
def self.authenticate(email, submitted_password)
# no need to prefix with 'User', because this is a class method.
u = find_by_email(email)
# return nil if the user doesn't exist, or the password doesn't match.
return nil unless u && u.password_matches?(submitted_password)
return u
end
protected
def encrypt_password
return if password.blank?
#will only run if being saved, and password is set.
self.salt = gen_salt if new_record?
self.crypted_password = encrypt(password)
end
def gen_salt
# lifted seed generation from "mephisto" cms.
Digest::SHA1.hexdigest("#{Time.now.to_s.split(//).sort_by{rand}.join}#{email}")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment