comparison app/models/user.rb @ 1295:622f24f53b42 redmine-2.3

Update to Redmine SVN revision 11972 on 2.3-stable branch
author Chris Cannam
date Fri, 14 Jun 2013 09:02:21 +0100
parents 433d4f72a19b
children 4f746d8966dd
comparison
equal deleted inserted replaced
1294:3e4c3460b6ca 1295:622f24f53b42
1 # Redmine - project management software 1 # Redmine - project management software
2 # Copyright (C) 2006-2012 Jean-Philippe Lang 2 # Copyright (C) 2006-2013 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.
17 17
18 require "digest/sha1" 18 require "digest/sha1"
19 19
20 class User < Principal 20 class User < Principal
21 include Redmine::SafeAttributes 21 include Redmine::SafeAttributes
22
23 # Account statuses
24 STATUS_ANONYMOUS = 0
25 STATUS_ACTIVE = 1
26 STATUS_REGISTERED = 2
27 STATUS_LOCKED = 3
28 22
29 # Different ways of displaying/sorting users 23 # Different ways of displaying/sorting users
30 USER_FORMATS = { 24 USER_FORMATS = {
31 :firstname_lastname => { 25 :firstname_lastname => {
32 :string => '#{firstname} #{lastname}', 26 :string => '#{firstname} #{lastname}',
80 has_one :preference, :dependent => :destroy, :class_name => 'UserPreference' 74 has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
81 has_one :rss_token, :class_name => 'Token', :conditions => "action='feeds'" 75 has_one :rss_token, :class_name => 'Token', :conditions => "action='feeds'"
82 has_one :api_token, :class_name => 'Token', :conditions => "action='api'" 76 has_one :api_token, :class_name => 'Token', :conditions => "action='api'"
83 belongs_to :auth_source 77 belongs_to :auth_source
84 78
85 scope :logged, :conditions => "#{User.table_name}.status <> #{STATUS_ANONYMOUS}" 79 scope :logged, lambda { where("#{User.table_name}.status <> #{STATUS_ANONYMOUS}") }
86 scope :status, lambda {|arg| arg.blank? ? {} : {:conditions => {:status => arg.to_i}} } 80 scope :status, lambda {|arg| where(arg.blank? ? nil : {:status => arg.to_i}) }
87 81
88 acts_as_customizable 82 acts_as_customizable
89 83
90 attr_accessor :password, :password_confirmation 84 attr_accessor :password, :password_confirmation
91 attr_accessor :last_before_login_on 85 attr_accessor :last_before_login_on
96 MAIL_LENGTH_LIMIT = 60 90 MAIL_LENGTH_LIMIT = 60
97 91
98 validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) } 92 validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
99 validates_uniqueness_of :login, :if => Proc.new { |user| user.login_changed? && user.login.present? }, :case_sensitive => false 93 validates_uniqueness_of :login, :if => Proc.new { |user| user.login_changed? && user.login.present? }, :case_sensitive => false
100 validates_uniqueness_of :mail, :if => Proc.new { |user| user.mail_changed? && user.mail.present? }, :case_sensitive => false 94 validates_uniqueness_of :mail, :if => Proc.new { |user| user.mail_changed? && user.mail.present? }, :case_sensitive => false
101 # Login must contain lettres, numbers, underscores only 95 # Login must contain letters, numbers, underscores only
102 validates_format_of :login, :with => /^[a-z0-9_\-@\.]*$/i 96 validates_format_of :login, :with => /\A[a-z0-9_\-@\.]*\z/i
103 validates_length_of :login, :maximum => LOGIN_LENGTH_LIMIT 97 validates_length_of :login, :maximum => LOGIN_LENGTH_LIMIT
104 validates_length_of :firstname, :lastname, :maximum => 30 98 validates_length_of :firstname, :lastname, :maximum => 30
105 validates_format_of :mail, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :allow_blank => true 99 validates_format_of :mail, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, :allow_blank => true
106 validates_length_of :mail, :maximum => MAIL_LENGTH_LIMIT, :allow_nil => true 100 validates_length_of :mail, :maximum => MAIL_LENGTH_LIMIT, :allow_nil => true
107 validates_confirmation_of :password, :allow_nil => true 101 validates_confirmation_of :password, :allow_nil => true
108 validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true 102 validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true
109 validate :validate_password_length 103 validate :validate_password_length
110 104
118 } 112 }
119 scope :not_in_group, lambda {|group| 113 scope :not_in_group, lambda {|group|
120 group_id = group.is_a?(Group) ? group.id : group.to_i 114 group_id = group.is_a?(Group) ? group.id : group.to_i
121 where("#{User.table_name}.id NOT IN (SELECT gu.user_id FROM #{table_name_prefix}groups_users#{table_name_suffix} gu WHERE gu.group_id = ?)", group_id) 115 where("#{User.table_name}.id NOT IN (SELECT gu.user_id FROM #{table_name_prefix}groups_users#{table_name_suffix} gu WHERE gu.group_id = ?)", group_id)
122 } 116 }
117 scope :sorted, lambda { order(*User.fields_for_order_statement)}
123 118
124 def set_mail_notification 119 def set_mail_notification
125 self.mail_notification = Setting.default_notification_option if self.mail_notification.blank? 120 self.mail_notification = Setting.default_notification_option if self.mail_notification.blank?
126 true 121 true
127 end 122 end
131 if self.password && self.auth_source_id.blank? 126 if self.password && self.auth_source_id.blank?
132 salt_password(password) 127 salt_password(password)
133 end 128 end
134 end 129 end
135 130
131 alias :base_reload :reload
136 def reload(*args) 132 def reload(*args)
137 @name = nil 133 @name = nil
138 @projects_by_role = nil 134 @projects_by_role = nil
139 super 135 @membership_by_project_id = nil
136 base_reload(*args)
140 end 137 end
141 138
142 def mail=(arg) 139 def mail=(arg)
143 write_attribute(:mail, arg.to_s.strip) 140 write_attribute(:mail, arg.to_s.strip)
144 end 141 end
148 write_attribute(:identity_url, '') 145 write_attribute(:identity_url, '')
149 else 146 else
150 begin 147 begin
151 write_attribute(:identity_url, OpenIdAuthentication.normalize_identifier(url)) 148 write_attribute(:identity_url, OpenIdAuthentication.normalize_identifier(url))
152 rescue OpenIdAuthentication::InvalidOpenId 149 rescue OpenIdAuthentication::InvalidOpenId
153 # Invlaid url, don't save 150 # Invalid url, don't save
154 end 151 end
155 end 152 end
156 self.read_attribute(:identity_url) 153 self.read_attribute(:identity_url)
157 end 154 end
158 155
159 # Returns the user that matches provided login and password, or nil 156 # Returns the user that matches provided login and password, or nil
160 def self.try_to_login(login, password) 157 def self.try_to_login(login, password)
161 login = login.to_s 158 login = login.to_s
162 password = password.to_s 159 password = password.to_s
163 160
164 # Make sure no one can sign in with an empty password 161 # Make sure no one can sign in with an empty login or password
165 return nil if password.empty? 162 return nil if login.empty? || password.empty?
166 user = find_by_login(login) 163 user = find_by_login(login)
167 if user 164 if user
168 # user is already in local database 165 # user is already in local database
169 return nil if !user.active? 166 return nil unless user.active?
170 if user.auth_source 167 return nil unless user.check_password?(password)
171 # user has an external authentication method
172 return nil unless user.auth_source.authenticate(login, password)
173 else
174 # authentication with local password
175 return nil unless user.check_password?(password)
176 end
177 else 168 else
178 # user is not yet registered, try to authenticate with available sources 169 # user is not yet registered, try to authenticate with available sources
179 attrs = AuthSource.authenticate(login, password) 170 attrs = AuthSource.authenticate(login, password)
180 if attrs 171 if attrs
181 user = new(attrs) 172 user = new(attrs)
185 user.reload 176 user.reload
186 logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source 177 logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source
187 end 178 end
188 end 179 end
189 end 180 end
190 user.update_attribute(:last_login_on, Time.now) if user && !user.new_record? 181 user.update_column(:last_login_on, Time.now) if user && !user.new_record?
191 user 182 user
192 rescue => text 183 rescue => text
193 raise text 184 raise text
194 end 185 end
195 186
196 # Returns the user who matches the given autologin +key+ or nil 187 # Returns the user who matches the given autologin +key+ or nil
197 def self.try_to_autologin(key) 188 def self.try_to_autologin(key)
198 tokens = Token.find_all_by_action_and_value('autologin', key.to_s) 189 user = Token.find_active_user('autologin', key, Setting.autologin.to_i)
199 # Make sure there's only 1 token that matches the key 190 if user
200 if tokens.size == 1 191 user.update_column(:last_login_on, Time.now)
201 token = tokens.first 192 user
202 if (token.created_on > Setting.autologin.to_i.day.ago) && token.user && token.user.active?
203 token.user.update_attribute(:last_login_on, Time.now)
204 token.user
205 end
206 end 193 end
207 end 194 end
208 195
209 def self.name_formatter(formatter = nil) 196 def self.name_formatter(formatter = nil)
210 USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname] 197 USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname]
357 end 344 end
358 345
359 # Find a user account by matching the exact login and then a case-insensitive 346 # Find a user account by matching the exact login and then a case-insensitive
360 # version. Exact matches will be given priority. 347 # version. Exact matches will be given priority.
361 def self.find_by_login(login) 348 def self.find_by_login(login)
362 # First look for an exact match 349 if login.present?
363 user = where(:login => login).all.detect {|u| u.login == login} 350 login = login.to_s
364 unless user 351 # First look for an exact match
365 # Fail over to case-insensitive if none was found 352 user = where(:login => login).all.detect {|u| u.login == login}
366 user = where("LOWER(login) = ?", login.to_s.downcase).first 353 unless user
367 end 354 # Fail over to case-insensitive if none was found
368 user 355 user = where("LOWER(login) = ?", login.downcase).first
356 end
357 user
358 end
369 end 359 end
370 360
371 def self.find_by_rss_key(key) 361 def self.find_by_rss_key(key)
372 token = Token.find_by_action_and_value('feeds', key.to_s) 362 Token.find_active_user('feeds', key)
373 token && token.user.active? ? token.user : nil
374 end 363 end
375 364
376 def self.find_by_api_key(key) 365 def self.find_by_api_key(key)
377 token = Token.find_by_action_and_value('api', key.to_s) 366 Token.find_active_user('api', key)
378 token && token.user.active? ? token.user : nil
379 end 367 end
380 368
381 # Makes find_by_mail case-insensitive 369 # Makes find_by_mail case-insensitive
382 def self.find_by_mail(mail) 370 def self.find_by_mail(mail)
383 where("LOWER(mail) = ?", mail.to_s.downcase).first 371 where("LOWER(mail) = ?", mail.to_s.downcase).first
425 true 413 true
426 end 414 end
427 415
428 def anonymous? 416 def anonymous?
429 !logged? 417 !logged?
418 end
419
420 # Returns user's membership for the given project
421 # or nil if the user is not a member of project
422 def membership(project)
423 project_id = project.is_a?(Project) ? project.id : project
424
425 @membership_by_project_id ||= Hash.new {|h, project_id|
426 h[project_id] = memberships.where(:project_id => project_id).first
427 }
428 @membership_by_project_id[project_id]
430 end 429 end
431 430
432 # Return user's roles for project 431 # Return user's roles for project
433 def roles_for_project(project) 432 def roles_for_project(project)
434 roles = [] 433 roles = []
435 # No role on archived projects 434 # No role on archived projects
436 return roles if project.nil? || project.archived? 435 return roles if project.nil? || project.archived?
437 if logged? 436 if logged?
438 # Find project membership 437 # Find project membership
439 membership = memberships.detect {|m| m.project_id == project.id} 438 membership = membership(project)
440 if membership 439 if membership
441 roles = membership.roles 440 roles = membership.roles
442 else 441 else
443 @role_non_member ||= Role.non_member 442 @role_non_member ||= Role.non_member
444 roles << @role_non_member 443 roles << @role_non_member
450 roles 449 roles
451 end 450 end
452 451
453 # Return true if the user is a member of project 452 # Return true if the user is a member of project
454 def member_of?(project) 453 def member_of?(project)
455 !roles_for_project(project).detect {|role| role.member?}.nil? 454 projects.to_a.include?(project)
456 end 455 end
457 456
458 # Returns a hash of user's projects grouped by roles 457 # Returns a hash of user's projects grouped by roles
459 def projects_by_role 458 def projects_by_role
460 return @projects_by_role if @projects_by_role 459 return @projects_by_role if @projects_by_role
563 # Utility method to help check if a user should be notified about an 562 # Utility method to help check if a user should be notified about an
564 # event. 563 # event.
565 # 564 #
566 # TODO: only supports Issue events currently 565 # TODO: only supports Issue events currently
567 def notify_about?(object) 566 def notify_about?(object)
568 case mail_notification 567 if mail_notification == 'all'
569 when 'all'
570 true 568 true
571 when 'selected' 569 elsif mail_notification.blank? || mail_notification == 'none'
572 # user receives notifications for created/assigned issues on unselected projects 570 false
573 if object.is_a?(Issue) && (object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was)) 571 else
572 case object
573 when Issue
574 case mail_notification
575 when 'selected', 'only_my_events'
576 # user receives notifications for created/assigned issues on unselected projects
577 object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was)
578 when 'only_assigned'
579 is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was)
580 when 'only_owner'
581 object.author == self
582 end
583 when News
584 # always send to project members except when mail_notification is set to 'none'
574 true 585 true
575 else
576 false
577 end 586 end
578 when 'none'
579 false
580 when 'only_my_events'
581 if object.is_a?(Issue) && (object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was))
582 true
583 else
584 false
585 end
586 when 'only_assigned'
587 if object.is_a?(Issue) && (is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was))
588 true
589 else
590 false
591 end
592 when 'only_owner'
593 if object.is_a?(Issue) && object.author == self
594 true
595 else
596 false
597 end
598 else
599 false
600 end 587 end
601 end 588 end
602 589
603 def self.current=(user) 590 def self.current=(user)
604 @current_user = user 591 Thread.current[:current_user] = user
605 end 592 end
606 593
607 def self.current 594 def self.current
608 @current_user ||= User.anonymous 595 Thread.current[:current_user] ||= User.anonymous
609 end 596 end
610 597
611 # Returns the anonymous user. If the anonymous user does not exist, it is created. There can be only 598 # Returns the anonymous user. If the anonymous user does not exist, it is created. There can be only
612 # one anonymous user per database. 599 # one anonymous user per database.
613 def self.anonymous 600 def self.anonymous
684 class AnonymousUser < User 671 class AnonymousUser < User
685 validate :validate_anonymous_uniqueness, :on => :create 672 validate :validate_anonymous_uniqueness, :on => :create
686 673
687 def validate_anonymous_uniqueness 674 def validate_anonymous_uniqueness
688 # There should be only one AnonymousUser in the database 675 # There should be only one AnonymousUser in the database
689 errors.add :base, 'An anonymous user already exists.' if AnonymousUser.find(:first) 676 errors.add :base, 'An anonymous user already exists.' if AnonymousUser.exists?
690 end 677 end
691 678
692 def available_custom_fields 679 def available_custom_fields
693 [] 680 []
694 end 681 end
703 690
704 def pref 691 def pref
705 UserPreference.new(:user => self) 692 UserPreference.new(:user => self)
706 end 693 end
707 694
695 def member_of?(project)
696 false
697 end
698
708 # Anonymous user can not be destroyed 699 # Anonymous user can not be destroyed
709 def destroy 700 def destroy
710 false 701 false
711 end 702 end
712 end 703 end