##// END OF EJS Templates
Merged r1561 from trunk....
Jean-Philippe Lang -
r1615:8af523c69462
parent child
Show More
@@ -1,290 +1,290
1 # redMine - project management software
1 # redMine - project management software
2 # Copyright (C) 2006-2007 Jean-Philippe Lang
2 # Copyright (C) 2006-2007 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 require "digest/sha1"
18 require "digest/sha1"
19
19
20 class User < ActiveRecord::Base
20 class User < ActiveRecord::Base
21
21
22 class OnTheFlyCreationFailure < Exception; end
22 class OnTheFlyCreationFailure < Exception; end
23
23
24 # Account statuses
24 # Account statuses
25 STATUS_ANONYMOUS = 0
25 STATUS_ANONYMOUS = 0
26 STATUS_ACTIVE = 1
26 STATUS_ACTIVE = 1
27 STATUS_REGISTERED = 2
27 STATUS_REGISTERED = 2
28 STATUS_LOCKED = 3
28 STATUS_LOCKED = 3
29
29
30 USER_FORMATS = {
30 USER_FORMATS = {
31 :firstname_lastname => '#{firstname} #{lastname}',
31 :firstname_lastname => '#{firstname} #{lastname}',
32 :firstname => '#{firstname}',
32 :firstname => '#{firstname}',
33 :lastname_firstname => '#{lastname} #{firstname}',
33 :lastname_firstname => '#{lastname} #{firstname}',
34 :lastname_coma_firstname => '#{lastname}, #{firstname}',
34 :lastname_coma_firstname => '#{lastname}, #{firstname}',
35 :username => '#{login}'
35 :username => '#{login}'
36 }
36 }
37
37
38 has_many :memberships, :class_name => 'Member', :include => [ :project, :role ], :conditions => "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}", :order => "#{Project.table_name}.name", :dependent => :delete_all
38 has_many :memberships, :class_name => 'Member', :include => [ :project, :role ], :conditions => "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}", :order => "#{Project.table_name}.name", :dependent => :delete_all
39 has_many :projects, :through => :memberships
39 has_many :projects, :through => :memberships
40 has_many :custom_values, :dependent => :delete_all, :as => :customized
40 has_many :custom_values, :dependent => :delete_all, :as => :customized
41 has_many :issue_categories, :foreign_key => 'assigned_to_id', :dependent => :nullify
41 has_many :issue_categories, :foreign_key => 'assigned_to_id', :dependent => :nullify
42 has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
42 has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
43 has_one :rss_token, :dependent => :destroy, :class_name => 'Token', :conditions => "action='feeds'"
43 has_one :rss_token, :dependent => :destroy, :class_name => 'Token', :conditions => "action='feeds'"
44 belongs_to :auth_source
44 belongs_to :auth_source
45
45
46 attr_accessor :password, :password_confirmation
46 attr_accessor :password, :password_confirmation
47 attr_accessor :last_before_login_on
47 attr_accessor :last_before_login_on
48 # Prevents unauthorized assignments
48 # Prevents unauthorized assignments
49 attr_protected :login, :admin, :password, :password_confirmation, :hashed_password
49 attr_protected :login, :admin, :password, :password_confirmation, :hashed_password
50
50
51 validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
51 validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
52 validates_uniqueness_of :login, :if => Proc.new { |user| !user.login.blank? }
52 validates_uniqueness_of :login, :if => Proc.new { |user| !user.login.blank? }
53 validates_uniqueness_of :mail, :if => Proc.new { |user| !user.mail.blank? }
53 validates_uniqueness_of :mail, :if => Proc.new { |user| !user.mail.blank? }
54 # Login must contain lettres, numbers, underscores only
54 # Login must contain lettres, numbers, underscores only
55 validates_format_of :login, :with => /^[a-z0-9_\-@\.]*$/i
55 validates_format_of :login, :with => /^[a-z0-9_\-@\.]*$/i
56 validates_length_of :login, :maximum => 30
56 validates_length_of :login, :maximum => 30
57 validates_format_of :firstname, :lastname, :with => /^[\w\s\'\-]*$/i
57 validates_format_of :firstname, :lastname, :with => /^[\w\s\'\-\.]*$/i
58 validates_length_of :firstname, :lastname, :maximum => 30
58 validates_length_of :firstname, :lastname, :maximum => 30
59 validates_format_of :mail, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :allow_nil => true
59 validates_format_of :mail, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :allow_nil => true
60 validates_length_of :mail, :maximum => 60, :allow_nil => true
60 validates_length_of :mail, :maximum => 60, :allow_nil => true
61 validates_length_of :password, :minimum => 4, :allow_nil => true
61 validates_length_of :password, :minimum => 4, :allow_nil => true
62 validates_confirmation_of :password, :allow_nil => true
62 validates_confirmation_of :password, :allow_nil => true
63 validates_associated :custom_values, :on => :update
63 validates_associated :custom_values, :on => :update
64
64
65 def before_create
65 def before_create
66 self.mail_notification = false
66 self.mail_notification = false
67 true
67 true
68 end
68 end
69
69
70 def before_save
70 def before_save
71 # update hashed_password if password was set
71 # update hashed_password if password was set
72 self.hashed_password = User.hash_password(self.password) if self.password
72 self.hashed_password = User.hash_password(self.password) if self.password
73 end
73 end
74
74
75 def self.active
75 def self.active
76 with_scope :find => { :conditions => [ "status = ?", STATUS_ACTIVE ] } do
76 with_scope :find => { :conditions => [ "status = ?", STATUS_ACTIVE ] } do
77 yield
77 yield
78 end
78 end
79 end
79 end
80
80
81 def self.find_active(*args)
81 def self.find_active(*args)
82 active do
82 active do
83 find(*args)
83 find(*args)
84 end
84 end
85 end
85 end
86
86
87 # Returns the user that matches provided login and password, or nil
87 # Returns the user that matches provided login and password, or nil
88 def self.try_to_login(login, password)
88 def self.try_to_login(login, password)
89 # Make sure no one can sign in with an empty password
89 # Make sure no one can sign in with an empty password
90 return nil if password.to_s.empty?
90 return nil if password.to_s.empty?
91 user = find(:first, :conditions => ["login=?", login])
91 user = find(:first, :conditions => ["login=?", login])
92 if user
92 if user
93 # user is already in local database
93 # user is already in local database
94 return nil if !user.active?
94 return nil if !user.active?
95 if user.auth_source
95 if user.auth_source
96 # user has an external authentication method
96 # user has an external authentication method
97 return nil unless user.auth_source.authenticate(login, password)
97 return nil unless user.auth_source.authenticate(login, password)
98 else
98 else
99 # authentication with local password
99 # authentication with local password
100 return nil unless User.hash_password(password) == user.hashed_password
100 return nil unless User.hash_password(password) == user.hashed_password
101 end
101 end
102 else
102 else
103 # user is not yet registered, try to authenticate with available sources
103 # user is not yet registered, try to authenticate with available sources
104 attrs = AuthSource.authenticate(login, password)
104 attrs = AuthSource.authenticate(login, password)
105 if attrs
105 if attrs
106 onthefly = new(*attrs)
106 onthefly = new(*attrs)
107 onthefly.login = login
107 onthefly.login = login
108 onthefly.language = Setting.default_language
108 onthefly.language = Setting.default_language
109 if onthefly.save
109 if onthefly.save
110 user = find(:first, :conditions => ["login=?", login])
110 user = find(:first, :conditions => ["login=?", login])
111 logger.info("User '#{user.login}' created from the LDAP") if logger
111 logger.info("User '#{user.login}' created from the LDAP") if logger
112 else
112 else
113 logger.error("User '#{onthefly.login}' found in LDAP but could not be created (#{onthefly.errors.full_messages.join(', ')})") if logger
113 logger.error("User '#{onthefly.login}' found in LDAP but could not be created (#{onthefly.errors.full_messages.join(', ')})") if logger
114 raise OnTheFlyCreationFailure.new
114 raise OnTheFlyCreationFailure.new
115 end
115 end
116 end
116 end
117 end
117 end
118 user.update_attribute(:last_login_on, Time.now) if user
118 user.update_attribute(:last_login_on, Time.now) if user
119 user
119 user
120 rescue => text
120 rescue => text
121 raise text
121 raise text
122 end
122 end
123
123
124 # Return user's full name for display
124 # Return user's full name for display
125 def name(formatter = nil)
125 def name(formatter = nil)
126 f = USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname]
126 f = USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname]
127 eval '"' + f + '"'
127 eval '"' + f + '"'
128 end
128 end
129
129
130 def active?
130 def active?
131 self.status == STATUS_ACTIVE
131 self.status == STATUS_ACTIVE
132 end
132 end
133
133
134 def registered?
134 def registered?
135 self.status == STATUS_REGISTERED
135 self.status == STATUS_REGISTERED
136 end
136 end
137
137
138 def locked?
138 def locked?
139 self.status == STATUS_LOCKED
139 self.status == STATUS_LOCKED
140 end
140 end
141
141
142 def check_password?(clear_password)
142 def check_password?(clear_password)
143 User.hash_password(clear_password) == self.hashed_password
143 User.hash_password(clear_password) == self.hashed_password
144 end
144 end
145
145
146 def pref
146 def pref
147 self.preference ||= UserPreference.new(:user => self)
147 self.preference ||= UserPreference.new(:user => self)
148 end
148 end
149
149
150 def time_zone
150 def time_zone
151 self.pref.time_zone.nil? ? nil : TimeZone[self.pref.time_zone]
151 self.pref.time_zone.nil? ? nil : TimeZone[self.pref.time_zone]
152 end
152 end
153
153
154 def wants_comments_in_reverse_order?
154 def wants_comments_in_reverse_order?
155 self.pref[:comments_sorting] == 'desc'
155 self.pref[:comments_sorting] == 'desc'
156 end
156 end
157
157
158 # Return user's RSS key (a 40 chars long string), used to access feeds
158 # Return user's RSS key (a 40 chars long string), used to access feeds
159 def rss_key
159 def rss_key
160 token = self.rss_token || Token.create(:user => self, :action => 'feeds')
160 token = self.rss_token || Token.create(:user => self, :action => 'feeds')
161 token.value
161 token.value
162 end
162 end
163
163
164 # Return an array of project ids for which the user has explicitly turned mail notifications on
164 # Return an array of project ids for which the user has explicitly turned mail notifications on
165 def notified_projects_ids
165 def notified_projects_ids
166 @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
166 @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
167 end
167 end
168
168
169 def notified_project_ids=(ids)
169 def notified_project_ids=(ids)
170 Member.update_all("mail_notification = #{connection.quoted_false}", ['user_id = ?', id])
170 Member.update_all("mail_notification = #{connection.quoted_false}", ['user_id = ?', id])
171 Member.update_all("mail_notification = #{connection.quoted_true}", ['user_id = ? AND project_id IN (?)', id, ids]) if ids && !ids.empty?
171 Member.update_all("mail_notification = #{connection.quoted_true}", ['user_id = ? AND project_id IN (?)', id, ids]) if ids && !ids.empty?
172 @notified_projects_ids = nil
172 @notified_projects_ids = nil
173 notified_projects_ids
173 notified_projects_ids
174 end
174 end
175
175
176 def self.find_by_rss_key(key)
176 def self.find_by_rss_key(key)
177 token = Token.find_by_value(key)
177 token = Token.find_by_value(key)
178 token && token.user.active? ? token.user : nil
178 token && token.user.active? ? token.user : nil
179 end
179 end
180
180
181 def self.find_by_autologin_key(key)
181 def self.find_by_autologin_key(key)
182 token = Token.find_by_action_and_value('autologin', key)
182 token = Token.find_by_action_and_value('autologin', key)
183 token && (token.created_on > Setting.autologin.to_i.day.ago) && token.user.active? ? token.user : nil
183 token && (token.created_on > Setting.autologin.to_i.day.ago) && token.user.active? ? token.user : nil
184 end
184 end
185
185
186 def <=>(user)
186 def <=>(user)
187 if user.nil?
187 if user.nil?
188 -1
188 -1
189 elsif lastname.to_s.downcase == user.lastname.to_s.downcase
189 elsif lastname.to_s.downcase == user.lastname.to_s.downcase
190 firstname.to_s.downcase <=> user.firstname.to_s.downcase
190 firstname.to_s.downcase <=> user.firstname.to_s.downcase
191 else
191 else
192 lastname.to_s.downcase <=> user.lastname.to_s.downcase
192 lastname.to_s.downcase <=> user.lastname.to_s.downcase
193 end
193 end
194 end
194 end
195
195
196 def to_s
196 def to_s
197 name
197 name
198 end
198 end
199
199
200 def logged?
200 def logged?
201 true
201 true
202 end
202 end
203
203
204 # Return user's role for project
204 # Return user's role for project
205 def role_for_project(project)
205 def role_for_project(project)
206 # No role on archived projects
206 # No role on archived projects
207 return nil unless project && project.active?
207 return nil unless project && project.active?
208 if logged?
208 if logged?
209 # Find project membership
209 # Find project membership
210 membership = memberships.detect {|m| m.project_id == project.id}
210 membership = memberships.detect {|m| m.project_id == project.id}
211 if membership
211 if membership
212 membership.role
212 membership.role
213 else
213 else
214 @role_non_member ||= Role.non_member
214 @role_non_member ||= Role.non_member
215 end
215 end
216 else
216 else
217 @role_anonymous ||= Role.anonymous
217 @role_anonymous ||= Role.anonymous
218 end
218 end
219 end
219 end
220
220
221 # Return true if the user is a member of project
221 # Return true if the user is a member of project
222 def member_of?(project)
222 def member_of?(project)
223 role_for_project(project).member?
223 role_for_project(project).member?
224 end
224 end
225
225
226 # Return true if the user is allowed to do the specified action on project
226 # Return true if the user is allowed to do the specified action on project
227 # action can be:
227 # action can be:
228 # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
228 # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
229 # * a permission Symbol (eg. :edit_project)
229 # * a permission Symbol (eg. :edit_project)
230 def allowed_to?(action, project, options={})
230 def allowed_to?(action, project, options={})
231 if project
231 if project
232 # No action allowed on archived projects
232 # No action allowed on archived projects
233 return false unless project.active?
233 return false unless project.active?
234 # No action allowed on disabled modules
234 # No action allowed on disabled modules
235 return false unless project.allows_to?(action)
235 return false unless project.allows_to?(action)
236 # Admin users are authorized for anything else
236 # Admin users are authorized for anything else
237 return true if admin?
237 return true if admin?
238
238
239 role = role_for_project(project)
239 role = role_for_project(project)
240 return false unless role
240 return false unless role
241 role.allowed_to?(action) && (project.is_public? || role.member?)
241 role.allowed_to?(action) && (project.is_public? || role.member?)
242
242
243 elsif options[:global]
243 elsif options[:global]
244 # authorize if user has at least one role that has this permission
244 # authorize if user has at least one role that has this permission
245 roles = memberships.collect {|m| m.role}.uniq
245 roles = memberships.collect {|m| m.role}.uniq
246 roles.detect {|r| r.allowed_to?(action)}
246 roles.detect {|r| r.allowed_to?(action)}
247 else
247 else
248 false
248 false
249 end
249 end
250 end
250 end
251
251
252 def self.current=(user)
252 def self.current=(user)
253 @current_user = user
253 @current_user = user
254 end
254 end
255
255
256 def self.current
256 def self.current
257 @current_user ||= User.anonymous
257 @current_user ||= User.anonymous
258 end
258 end
259
259
260 def self.anonymous
260 def self.anonymous
261 anonymous_user = AnonymousUser.find(:first)
261 anonymous_user = AnonymousUser.find(:first)
262 if anonymous_user.nil?
262 if anonymous_user.nil?
263 anonymous_user = AnonymousUser.create(:lastname => 'Anonymous', :firstname => '', :mail => '', :login => '', :status => 0)
263 anonymous_user = AnonymousUser.create(:lastname => 'Anonymous', :firstname => '', :mail => '', :login => '', :status => 0)
264 raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
264 raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
265 end
265 end
266 anonymous_user
266 anonymous_user
267 end
267 end
268
268
269 private
269 private
270 # Return password digest
270 # Return password digest
271 def self.hash_password(clear_password)
271 def self.hash_password(clear_password)
272 Digest::SHA1.hexdigest(clear_password || "")
272 Digest::SHA1.hexdigest(clear_password || "")
273 end
273 end
274 end
274 end
275
275
276 class AnonymousUser < User
276 class AnonymousUser < User
277
277
278 def validate_on_create
278 def validate_on_create
279 # There should be only one AnonymousUser in the database
279 # There should be only one AnonymousUser in the database
280 errors.add_to_base 'An anonymous user already exists.' if AnonymousUser.find(:first)
280 errors.add_to_base 'An anonymous user already exists.' if AnonymousUser.find(:first)
281 end
281 end
282
282
283 # Overrides a few properties
283 # Overrides a few properties
284 def logged?; false end
284 def logged?; false end
285 def admin; false end
285 def admin; false end
286 def name; 'Anonymous' end
286 def name; 'Anonymous' end
287 def mail; nil end
287 def mail; nil end
288 def time_zone; nil end
288 def time_zone; nil end
289 def rss_key; nil end
289 def rss_key; nil end
290 end
290 end
General Comments 0
You need to be logged in to leave comments. Login now