root/app/models/user.rb @ 5c2a70ab
a579432b | Marc Dequènes (Duck) | require 'digest/sha1'
|
|
class User < ActiveRecord::Base
|
|||
validates_presence_of :login, :salt
|
|||
03256d87 | Marc Dequènes (Duck) | validates_presence_of :password, :if => :password_changed?
|
|
a579432b | Marc Dequènes (Duck) | 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
|
|||
d3d4a9b0 | Marc Dequènes (Duck) | validates_length_of :password, :within => 4..128, :if => :password_changed?, :allow_nil => true, :allow_blank => true
|
|
a579432b | Marc Dequènes (Duck) | 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
|
|||
c257c9f9 | Marc Dequènes (Duck) | self.salt = self.class.random_string(10) if not self.salt
|
|
a579432b | Marc Dequènes (Duck) | 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)
|
|||
03256d87 | Marc Dequènes (Duck) | u = find(:first, :conditions => ["login = ?", login])
|
|
a579432b | Marc Dequènes (Duck) | return nil if u.nil?
|
|
return u if self.encrypt(pass, u.salt) == u.hashed_password
|
|||
nil
|
|||
end
|
|||
def password_changed?
|
|||
03256d87 | Marc Dequènes (Duck) | self.new_record? or not @password.blank?
|
|
a579432b | Marc Dequènes (Duck) | end
|
|
end
|