Project

General

Profile

Download (1.45 KB) Statistics
| Branch: | Tag: | Revision:

root / app / models / user.rb @ a579432b

1
require 'digest/sha1'
2

    
3
class User < ActiveRecord::Base
4
  validates_presence_of :login, :salt
5
  validates_presence_of :password, :password_confirmation, :if => :password_changed?
6
  validates_confirmation_of :password
7
  validates_uniqueness_of :login
8
  validates_uniqueness_of :real_name, :email, :allow_nil => true
9
  validates_length_of :login, :within => 3..64, :allow_nil => true
10
  validates_length_of :password, :within => 4..128, :if => :password_changed?, :allow_nil => true
11
  validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => _("Invalid email"), :allow_blank => true
12

    
13
  attr_protected :id, :salt
14
  attr_accessor :password, :password_confirmation
15

    
16
  def self.random_string(len)
17
    #generate a random password consisting of strings and digits
18
    chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
19
    newpass = ""
20
    1.upto(len) {|i| newpass << chars[rand(chars.size - 1)] }
21
    return newpass
22
  end
23

    
24
  def password=(pass)
25
    @password = pass
26
    self.salt = self.class.random_string(10) if not self.salt?
27
    self.hashed_password = self.class.encrypt(@password, self.salt)
28
  end
29

    
30
  def self.encrypt(pass, salt)
31
     Digest::SHA1.hexdigest(pass + salt)
32
  end
33

    
34
  def self.authenticate(login, pass)
35
    u=find(:first, :conditions => ["login = ?", login])
36
    return nil if u.nil?
37
    return u if self.encrypt(pass, u.salt) == u.hashed_password
38
    nil
39
  end
40

    
41
  def password_changed?
42
    self.new_record? or @password
43
  end
44
end
(12-12/12)