1 require 'digest/sha1'
2
3 class User < ActiveRecord::Base
4 has_many :pages, :foreign_key => :created_by_id
5
6 # Default Order
7 default_scope :order => 'name'
8
9 # Associations
10 belongs_to :created_by, :class_name => 'User'
11 belongs_to :updated_by, :class_name => 'User'
12
13 # Validations
14 validates_uniqueness_of :login
15
16 validates_confirmation_of :password, :if => :confirm_password?
17
18 validates_presence_of :name, :login
19 validates_presence_of :password, :password_confirmation, :if => :new_record?
20
21 validates_format_of :email, :allow_nil => true, :with => /^$|^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
22
23 validates_length_of :name, :maximum => 100, :allow_nil => true
24 validates_length_of :login, :within => 3..40, :allow_nil => true
25 validates_length_of :password, :within => 5..40, :allow_nil => true, :if => :validate_length_of_password?
26 validates_length_of :email, :maximum => 255, :allow_nil => true
27
28 attr_writer :confirm_password
29 class << self
30 def unprotected_attributes
31 @unprotected_attributes ||= [:name, :email, :login, :password, :password_confirmation, :locale]
32 end
33
34 def unprotected_attributes=(array)
35 @unprotected_attributes = array.map{|att| att.to_sym }
36 end
37 end
38
39 def has_role?(role)
40 respond_to?("#{role}?") && send("#{role}?")
41 end
42
43 def sha1(phrase)
44 Digest::SHA1.hexdigest("--#{salt}--#{phrase}--")
45 end
46
47 def self.authenticate(login_or_email, password)
48 user = find(:first, :conditions => ["login = ? OR email = ?", login_or_email, login_or_email])
49 user if user && user.authenticated?(password)
50 end
51
52 def authenticated?(password)
53 self.password == sha1(password)
54 end
55
56 def after_initialize
57 @confirm_password = true
58 end
59
60 def confirm_password?
61 @confirm_password
62 end
63
64 def remember_me
65 update_attribute(:session_token, sha1(Time.now + Radiant::Config['session_timeout'].to_i)) unless self.session_token?
66 end
67
68 def forget_me
69 update_attribute(:session_token, nil)
70 end
71
72 private
73
74 def validate_length_of_password?
75 new_record? or not password.to_s.empty?
76 end
77
78 before_create :encrypt_password
79 def encrypt_password
80 self.salt = Digest::SHA1.hexdigest("--#{Time.now}--#{login}--sweet harmonious biscuits--")
81 self.password = sha1(password)
82 end
83
84 before_update :encrypt_password_unless_empty_or_unchanged
85 def encrypt_password_unless_empty_or_unchanged
86 user = self.class.find(self.id)
87 case password
88 when ''
89 self.password = user.password
90 when user.password
91 else
92 encrypt_password
93 end
94 end
95
96 end