comparison app/models/user.rb @ 1298:4f746d8966dd redmine_2.3_integration

Merge from redmine-2.3 branch to create new branch redmine-2.3-integration
author Chris Cannam
date Fri, 14 Jun 2013 09:28:30 +0100
parents bb32da3bea34 622f24f53b42
children
comparison
equal deleted inserted replaced
1297:0a574315af3e 1298:4f746d8966dd
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 has_one :ssamr_user_detail, :dependent => :destroy, :class_name => 'SsamrUserDetail' 82 has_one :ssamr_user_detail, :dependent => :destroy, :class_name => 'SsamrUserDetail'
89 accepts_nested_attributes_for :ssamr_user_detail 83 accepts_nested_attributes_for :ssamr_user_detail
90 84
91 has_one :author 85 has_one :author
101 MAIL_LENGTH_LIMIT = 60 95 MAIL_LENGTH_LIMIT = 60
102 96
103 validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) } 97 validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
104 validates_uniqueness_of :login, :if => Proc.new { |user| user.login_changed? && user.login.present? }, :case_sensitive => false 98 validates_uniqueness_of :login, :if => Proc.new { |user| user.login_changed? && user.login.present? }, :case_sensitive => false
105 validates_uniqueness_of :mail, :if => Proc.new { |user| user.mail_changed? && user.mail.present? }, :case_sensitive => false 99 validates_uniqueness_of :mail, :if => Proc.new { |user| user.mail_changed? && user.mail.present? }, :case_sensitive => false
106 100 # Login must contain letters, numbers, underscores only
107 # Login must contain lettres, numbers, underscores only 101 validates_format_of :login, :with => /\A[a-z0-9_\-@\.]*\z/i
108 validates_format_of :login, :with => /^[a-z0-9_\-@\.]*$/i
109 validates_length_of :login, :maximum => LOGIN_LENGTH_LIMIT 102 validates_length_of :login, :maximum => LOGIN_LENGTH_LIMIT
110 validates_length_of :firstname, :lastname, :maximum => 30 103 validates_length_of :firstname, :lastname, :maximum => 30
111 validates_format_of :mail, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :allow_blank => true 104 validates_format_of :mail, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, :allow_blank => true
112 validates_length_of :mail, :maximum => MAIL_LENGTH_LIMIT, :allow_nil => true 105 validates_length_of :mail, :maximum => MAIL_LENGTH_LIMIT, :allow_nil => true
113 validates_confirmation_of :password, :allow_nil => true 106 validates_confirmation_of :password, :allow_nil => true
114 validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true 107 validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true
115 validate :validate_password_length 108 validate :validate_password_length
116 109
126 } 119 }
127 scope :not_in_group, lambda {|group| 120 scope :not_in_group, lambda {|group|
128 group_id = group.is_a?(Group) ? group.id : group.to_i 121 group_id = group.is_a?(Group) ? group.id : group.to_i
129 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 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)
130 } 123 }
124 scope :sorted, lambda { order(*User.fields_for_order_statement)}
131 125
132 def set_mail_notification 126 def set_mail_notification
133 self.mail_notification = Setting.default_notification_option if self.mail_notification.blank? 127 self.mail_notification = Setting.default_notification_option if self.mail_notification.blank?
134 true 128 true
135 end 129 end
139 if self.password && self.auth_source_id.blank? 133 if self.password && self.auth_source_id.blank?
140 salt_password(password) 134 salt_password(password)
141 end 135 end
142 end 136 end
143 137
138 alias :base_reload :reload
144 def reload(*args) 139 def reload(*args)
145 @name = nil 140 @name = nil
146 @projects_by_role = nil 141 @projects_by_role = nil
147 super 142 @membership_by_project_id = nil
143 base_reload(*args)
148 end 144 end
149 145
150 def mail=(arg) 146 def mail=(arg)
151 write_attribute(:mail, arg.to_s.strip) 147 write_attribute(:mail, arg.to_s.strip)
152 end 148 end
160 write_attribute(:identity_url, '') 156 write_attribute(:identity_url, '')
161 else 157 else
162 begin 158 begin
163 write_attribute(:identity_url, OpenIdAuthentication.normalize_identifier(url)) 159 write_attribute(:identity_url, OpenIdAuthentication.normalize_identifier(url))
164 rescue OpenIdAuthentication::InvalidOpenId 160 rescue OpenIdAuthentication::InvalidOpenId
165 # Invlaid url, don't save 161 # Invalid url, don't save
166 end 162 end
167 end 163 end
168 self.read_attribute(:identity_url) 164 self.read_attribute(:identity_url)
169 end 165 end
170 166
171 # Returns the user that matches provided login and password, or nil 167 # Returns the user that matches provided login and password, or nil
172 def self.try_to_login(login, password) 168 def self.try_to_login(login, password)
173 login = login.to_s 169 login = login.to_s
174 password = password.to_s 170 password = password.to_s
175 171
176 # Make sure no one can sign in with an empty password 172 # Make sure no one can sign in with an empty login or password
177 return nil if password.empty? 173 return nil if login.empty? || password.empty?
178 user = find_by_login(login) 174 user = find_by_login(login)
179 if user 175 if user
180 # user is already in local database 176 # user is already in local database
181 return nil if !user.active? 177 return nil unless user.active?
182 if user.auth_source 178 return nil unless user.check_password?(password)
183 # user has an external authentication method
184 return nil unless user.auth_source.authenticate(login, password)
185 else
186 # authentication with local password
187 return nil unless user.check_password?(password)
188 end
189 else 179 else
190 # user is not yet registered, try to authenticate with available sources 180 # user is not yet registered, try to authenticate with available sources
191 attrs = AuthSource.authenticate(login, password) 181 attrs = AuthSource.authenticate(login, password)
192 if attrs 182 if attrs
193 user = new(attrs) 183 user = new(attrs)
197 user.reload 187 user.reload
198 logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source 188 logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source
199 end 189 end
200 end 190 end
201 end 191 end
202 user.update_attribute(:last_login_on, Time.now) if user && !user.new_record? 192 user.update_column(:last_login_on, Time.now) if user && !user.new_record?
203 user 193 user
204 rescue => text 194 rescue => text
205 raise text 195 raise text
206 end 196 end
207 197
208 # Returns the user who matches the given autologin +key+ or nil 198 # Returns the user who matches the given autologin +key+ or nil
209 def self.try_to_autologin(key) 199 def self.try_to_autologin(key)
210 tokens = Token.find_all_by_action_and_value('autologin', key.to_s) 200 user = Token.find_active_user('autologin', key, Setting.autologin.to_i)
211 # Make sure there's only 1 token that matches the key 201 if user
212 if tokens.size == 1 202 user.update_column(:last_login_on, Time.now)
213 token = tokens.first 203 user
214 if (token.created_on > Setting.autologin.to_i.day.ago) && token.user && token.user.active?
215 token.user.update_attribute(:last_login_on, Time.now)
216 token.user
217 end
218 end 204 end
219 end 205 end
220 206
221 def self.name_formatter(formatter = nil) 207 def self.name_formatter(formatter = nil)
222 USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname] 208 USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname]
369 end 355 end
370 356
371 # Find a user account by matching the exact login and then a case-insensitive 357 # Find a user account by matching the exact login and then a case-insensitive
372 # version. Exact matches will be given priority. 358 # version. Exact matches will be given priority.
373 def self.find_by_login(login) 359 def self.find_by_login(login)
374 # First look for an exact match 360 if login.present?
375 user = where(:login => login).all.detect {|u| u.login == login} 361 login = login.to_s
376 unless user 362 # First look for an exact match
377 # Fail over to case-insensitive if none was found 363 user = where(:login => login).all.detect {|u| u.login == login}
378 user = where("LOWER(login) = ?", login.to_s.downcase).first 364 unless user
379 end 365 # Fail over to case-insensitive if none was found
380 user 366 user = where("LOWER(login) = ?", login.downcase).first
367 end
368 user
369 end
381 end 370 end
382 371
383 def self.find_by_rss_key(key) 372 def self.find_by_rss_key(key)
384 token = Token.find_by_action_and_value('feeds', key.to_s) 373 Token.find_active_user('feeds', key)
385 token && token.user.active? ? token.user : nil
386 end 374 end
387 375
388 def self.find_by_api_key(key) 376 def self.find_by_api_key(key)
389 token = Token.find_by_action_and_value('api', key.to_s) 377 Token.find_active_user('api', key)
390 token && token.user.active? ? token.user : nil
391 end 378 end
392 379
393 # Makes find_by_mail case-insensitive 380 # Makes find_by_mail case-insensitive
394 def self.find_by_mail(mail) 381 def self.find_by_mail(mail)
395 where("LOWER(mail) = ?", mail.to_s.downcase).first 382 where("LOWER(mail) = ?", mail.to_s.downcase).first
437 true 424 true
438 end 425 end
439 426
440 def anonymous? 427 def anonymous?
441 !logged? 428 !logged?
429 end
430
431 # Returns user's membership for the given project
432 # or nil if the user is not a member of project
433 def membership(project)
434 project_id = project.is_a?(Project) ? project.id : project
435
436 @membership_by_project_id ||= Hash.new {|h, project_id|
437 h[project_id] = memberships.where(:project_id => project_id).first
438 }
439 @membership_by_project_id[project_id]
442 end 440 end
443 441
444 # Return user's roles for project 442 # Return user's roles for project
445 def roles_for_project(project) 443 def roles_for_project(project)
446 roles = [] 444 roles = []
447 # No role on archived projects 445 # No role on archived projects
448 return roles if project.nil? || project.archived? 446 return roles if project.nil? || project.archived?
449 if logged? 447 if logged?
450 # Find project membership 448 # Find project membership
451 membership = memberships.detect {|m| m.project_id == project.id} 449 membership = membership(project)
452 if membership 450 if membership
453 roles = membership.roles 451 roles = membership.roles
454 else 452 else
455 @role_non_member ||= Role.non_member 453 @role_non_member ||= Role.non_member
456 roles << @role_non_member 454 roles << @role_non_member
462 roles 460 roles
463 end 461 end
464 462
465 # Return true if the user is a member of project 463 # Return true if the user is a member of project
466 def member_of?(project) 464 def member_of?(project)
467 !roles_for_project(project).detect {|role| role.member?}.nil? 465 projects.to_a.include?(project)
468 end 466 end
469 467
470 # Returns a hash of user's projects grouped by roles 468 # Returns a hash of user's projects grouped by roles
471 def projects_by_role 469 def projects_by_role
472 return @projects_by_role if @projects_by_role 470 return @projects_by_role if @projects_by_role
575 # Utility method to help check if a user should be notified about an 573 # Utility method to help check if a user should be notified about an
576 # event. 574 # event.
577 # 575 #
578 # TODO: only supports Issue events currently 576 # TODO: only supports Issue events currently
579 def notify_about?(object) 577 def notify_about?(object)
580 case mail_notification 578 if mail_notification == 'all'
581 when 'all'
582 true 579 true
583 when 'selected' 580 elsif mail_notification.blank? || mail_notification == 'none'
584 # user receives notifications for created/assigned issues on unselected projects 581 false
585 if object.is_a?(Issue) && (object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was)) 582 else
583 case object
584 when Issue
585 case mail_notification
586 when 'selected', 'only_my_events'
587 # user receives notifications for created/assigned issues on unselected projects
588 object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was)
589 when 'only_assigned'
590 is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was)
591 when 'only_owner'
592 object.author == self
593 end
594 when News
595 # always send to project members except when mail_notification is set to 'none'
586 true 596 true
587 else
588 false
589 end 597 end
590 when 'none'
591 false
592 when 'only_my_events'
593 if object.is_a?(Issue) && (object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was))
594 true
595 else
596 false
597 end
598 when 'only_assigned'
599 if object.is_a?(Issue) && (is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was))
600 true
601 else
602 false
603 end
604 when 'only_owner'
605 if object.is_a?(Issue) && object.author == self
606 true
607 else
608 false
609 end
610 else
611 false
612 end 598 end
613 end 599 end
614 600
615 def self.current=(user) 601 def self.current=(user)
616 @current_user = user 602 Thread.current[:current_user] = user
617 end 603 end
618 604
619 def self.current 605 def self.current
620 @current_user ||= User.anonymous 606 Thread.current[:current_user] ||= User.anonymous
621 end 607 end
622 608
623 # Returns the anonymous user. If the anonymous user does not exist, it is created. There can be only 609 # Returns the anonymous user. If the anonymous user does not exist, it is created. There can be only
624 # one anonymous user per database. 610 # one anonymous user per database.
625 def self.anonymous 611 def self.anonymous
696 class AnonymousUser < User 682 class AnonymousUser < User
697 validate :validate_anonymous_uniqueness, :on => :create 683 validate :validate_anonymous_uniqueness, :on => :create
698 684
699 def validate_anonymous_uniqueness 685 def validate_anonymous_uniqueness
700 # There should be only one AnonymousUser in the database 686 # There should be only one AnonymousUser in the database
701 errors.add :base, 'An anonymous user already exists.' if AnonymousUser.find(:first) 687 errors.add :base, 'An anonymous user already exists.' if AnonymousUser.exists?
702 end 688 end
703 689
704 def available_custom_fields 690 def available_custom_fields
705 [] 691 []
706 end 692 end
715 701
716 def pref 702 def pref
717 UserPreference.new(:user => self) 703 UserPreference.new(:user => self)
718 end 704 end
719 705
706 def member_of?(project)
707 false
708 end
709
720 # Anonymous user can not be destroyed 710 # Anonymous user can not be destroyed
721 def destroy 711 def destroy
722 false 712 false
723 end 713 end
724 end 714 end