Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class User < ActiveRecord::Base
- attr_accessible :email,
- :email_confirmation,
- :password,
- :password_confirmation,
- :username
- attr_accessor :password, :password_confirmation, :email_confirmation
- belongs_to :group
- name_regex = /\A[\w+\-.]+\z/i
- email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
- validates :username, :presence => true,
- :length => { :maximum => 25 },
- :format => { :with => name_regex }
- validates :password, :length => { :in => 5..20 }
- validates :password, :confirmation => true
- validates :password_confirmation, :presence => true
- validates :email, :confirmation => true,
- :uniqueness => { :case_sensitive => false },
- :format => { :with => email_regex }
- validates :email_confirmation, :presence => true
- before_save :encrypt_password
- 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)
- return nil if user.nil?
- return user if user.salt == cookie_salt
- end
- def has_password?(string)
- password_hash == encrypt(string)
- end
- def role?(s)
- group.nil? || new_record? ? false : group.groupname.to_sym == s
- end
- private
- def encrypt_password
- self.salt = generate_salt if new_record?
- self.password_hash = encrypt(password)
- end
- def encrypt(string)
- secure_hash("#{salt}:#{string}")
- end
- def generate_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