|
require 'digest/sha1'
|
|
|
|
class User < ActiveRecord::Base
|
|
validates_presence_of :login, :salt
|
|
validates_presence_of :password, :if => :password_changed?
|
|
validates_confirmation_of :password
|
|
validates_uniqueness_of :login
|
|
validates_uniqueness_of :real_name, :email, :allow_nil => true
|
|
validates_length_of :login, :within => 3..64, :allow_nil => true
|
|
validates_length_of :password, :within => 4..128, :if => :password_changed?, :allow_nil => true, :allow_blank => true
|
|
validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => _("Invalid email"), :allow_blank => true
|
|
|
|
attr_protected :id, :salt
|
|
attr_accessor :password, :password_confirmation
|
|
|
|
def self.random_string(len)
|
|
#generate a random password consisting of strings and digits
|
|
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
|
|
newpass = ""
|
|
1.upto(len) {|i| newpass << chars[rand(chars.size - 1)] }
|
|
return newpass
|
|
end
|
|
|
|
def password=(pass)
|
|
@password = pass
|
|
self.salt = self.class.random_string(10) if not self.salt
|
|
self.hashed_password = self.class.encrypt(@password, self.salt)
|
|
end
|
|
|
|
def self.encrypt(pass, salt)
|
|
Digest::SHA1.hexdigest(pass + salt)
|
|
end
|
|
|
|
def self.authenticate(login, pass)
|
|
u = find(:first, :conditions => ["login = ?", login])
|
|
return nil if u.nil?
|
|
return u if self.encrypt(pass, u.salt) == u.hashed_password
|
|
nil
|
|
end
|
|
|
|
def password_changed?
|
|
self.new_record? or not @password.blank?
|
|
end
|
|
end
|