diff app/models/user.rb @ 909:cbb26bc654de redmine-1.3

Update to Redmine 1.3-stable branch (Redmine SVN rev 8964)
author Chris Cannam
date Fri, 24 Feb 2012 19:09:32 +0000
parents cbce1fd3b1b7
children 5e80956cc792 5f33065ddc4b
line wrap: on
line diff
--- a/app/models/user.rb	Fri Feb 24 18:36:29 2012 +0000
+++ b/app/models/user.rb	Fri Feb 24 19:09:32 2012 +0000
@@ -5,12 +5,12 @@
 # modify it under the terms of the GNU General Public License
 # as published by the Free Software Foundation; either version 2
 # of the License, or (at your option) any later version.
-# 
+#
 # This program is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
-# 
+#
 # You should have received a copy of the GNU General Public License
 # along with this program; if not, write to the Free Software
 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
@@ -19,19 +19,20 @@
 
 class User < Principal
   include Redmine::SafeAttributes
-  
+
   # Account statuses
   STATUS_ANONYMOUS  = 0
   STATUS_ACTIVE     = 1
   STATUS_REGISTERED = 2
   STATUS_LOCKED     = 3
-  
+
+  # Different ways of displaying/sorting users
   USER_FORMATS = {
-    :firstname_lastname => '#{firstname} #{lastname}',
-    :firstname => '#{firstname}',
-    :lastname_firstname => '#{lastname} #{firstname}',
-    :lastname_coma_firstname => '#{lastname}, #{firstname}',
-    :username => '#{login}'
+    :firstname_lastname => {:string => '#{firstname} #{lastname}', :order => %w(firstname lastname id)},
+    :firstname => {:string => '#{firstname}', :order => %w(firstname id)},
+    :lastname_firstname => {:string => '#{lastname} #{firstname}', :order => %w(lastname firstname id)},
+    :lastname_coma_firstname => {:string => '#{lastname}, #{firstname}', :order => %w(lastname firstname id)},
+    :username => {:string => '#{login}', :order => %w(login id)},
   }
 
   MAIL_NOTIFICATION_OPTIONS = [
@@ -45,18 +46,17 @@
 
   has_and_belongs_to_many :groups, :after_add => Proc.new {|user, group| group.user_added(user)},
                                    :after_remove => Proc.new {|user, group| group.user_removed(user)}
-  has_many :issue_categories, :foreign_key => 'assigned_to_id', :dependent => :nullify
   has_many :changesets, :dependent => :nullify
   has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
   has_one :rss_token, :class_name => 'Token', :conditions => "action='feeds'"
   has_one :api_token, :class_name => 'Token', :conditions => "action='api'"
   belongs_to :auth_source
-  
+
   # Active non-anonymous users scope
   named_scope :active, :conditions => "#{User.table_name}.status = #{STATUS_ACTIVE}"
-  
+
   acts_as_customizable
-  
+
   attr_accessor :password, :password_confirmation
   attr_accessor :last_before_login_on
   # Prevents unauthorized assignments
@@ -69,13 +69,16 @@
   validates_format_of :login, :with => /^[a-z0-9_\-@\.]*$/i
   validates_length_of :login, :maximum => 30
   validates_length_of :firstname, :lastname, :maximum => 30
-  validates_format_of :mail, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :allow_nil => true
+  validates_format_of :mail, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :allow_blank => true
   validates_length_of :mail, :maximum => 60, :allow_nil => true
   validates_confirmation_of :password, :allow_nil => true
   validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true
+  validate :validate_password_length
 
+  before_create :set_mail_notification
+  before_save   :update_hashed_password
   before_destroy :remove_references_before_destroy
-  
+
   named_scope :in_group, lambda {|group|
     group_id = group.is_a?(Group) ? group.id : group.to_i
     { :conditions => ["#{User.table_name}.id IN (SELECT gu.user_id FROM #{table_name_prefix}groups_users#{table_name_suffix} gu WHERE gu.group_id = ?)", group_id] }
@@ -84,29 +87,29 @@
     group_id = group.is_a?(Group) ? group.id : group.to_i
     { :conditions => ["#{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] }
   }
-  
-  def before_create
+
+  def set_mail_notification
     self.mail_notification = Setting.default_notification_option if self.mail_notification.blank?
     true
   end
-  
-  def before_save
+
+  def update_hashed_password
     # update hashed_password if password was set
     if self.password && self.auth_source_id.blank?
       salt_password(password)
     end
   end
-  
+
   def reload(*args)
     @name = nil
     @projects_by_role = nil
     super
   end
-  
+
   def mail=(arg)
     write_attribute(:mail, arg.to_s.strip)
   end
-  
+
   def identity_url=(url)
     if url.blank?
       write_attribute(:identity_url, '')
@@ -119,7 +122,7 @@
     end
     self.read_attribute(:identity_url)
   end
-  
+
   # Returns the user that matches provided login and password, or nil
   def self.try_to_login(login, password)
     # Make sure no one can sign in with an empty password
@@ -147,13 +150,13 @@
           logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source
         end
       end
-    end    
+    end
     user.update_attribute(:last_login_on, Time.now) if user && !user.new_record?
     user
   rescue => text
     raise text
   end
-  
+
   # Returns the user who matches the given autologin +key+ or nil
   def self.try_to_autologin(key)
     tokens = Token.find_all_by_action_and_value('autologin', key)
@@ -166,16 +169,32 @@
       end
     end
   end
-	
+
+  def self.name_formatter(formatter = nil)
+    USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname]
+  end
+
+  # Returns an array of fields names than can be used to make an order statement for users
+  # according to how user names are displayed
+  # Examples:
+  #
+  #   User.fields_for_order_statement              => ['users.login', 'users.id']
+  #   User.fields_for_order_statement('authors')   => ['authors.login', 'authors.id']
+  def self.fields_for_order_statement(table=nil)
+    table ||= table_name
+    name_formatter[:order].map {|field| "#{table}.#{field}"}
+  end
+
   # Return user's full name for display
   def name(formatter = nil)
+    f = self.class.name_formatter(formatter)
     if formatter
-      eval('"' + (USER_FORMATS[formatter] || USER_FORMATS[:firstname_lastname]) + '"')
+      eval('"' + f[:string] + '"')
     else
-      @name ||= eval('"' + (USER_FORMATS[Setting.user_format] || USER_FORMATS[:firstname_lastname]) + '"')
+      @name ||= eval('"' + f[:string] + '"')
     end
   end
-  
+
   def active?
     self.status == STATUS_ACTIVE
   end
@@ -183,7 +202,7 @@
   def registered?
     self.status == STATUS_REGISTERED
   end
-    
+
   def locked?
     self.status == STATUS_LOCKED
   end
@@ -220,7 +239,7 @@
       User.hash_password("#{salt}#{User.hash_password clear_password}") == hashed_password
     end
   end
-  
+
   # Generates a random salt and computes hashed_password for +clear_password+
   # The hashed password is stored in the following form: SHA1(salt + SHA1(password))
   def salt_password(clear_password)
@@ -245,19 +264,19 @@
     self.password_confirmation = password
     self
   end
-  
+
   def pref
     self.preference ||= UserPreference.new(:user => self)
   end
-  
+
   def time_zone
     @time_zone ||= (self.pref.time_zone.blank? ? nil : ActiveSupport::TimeZone[self.pref.time_zone])
   end
-  
+
   def wants_comments_in_reverse_order?
     self.pref[:comments_sorting] == 'desc'
   end
-  
+
   # Return user's RSS key (a 40 chars long string), used to access feeds
   def rss_key
     token = self.rss_token || Token.create(:user => self, :action => 'feeds')
@@ -269,12 +288,12 @@
     token = self.api_token || self.create_api_token(:action => 'api')
     token.value
   end
-  
+
   # Return an array of project ids for which the user has explicitly turned mail notifications on
   def notified_projects_ids
     @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
   end
-  
+
   def notified_project_ids=(ids)
     Member.update_all("mail_notification = #{connection.quoted_false}", ['user_id = ?', id])
     Member.update_all("mail_notification = #{connection.quoted_true}", ['user_id = ? AND project_id IN (?)', id, ids]) if ids && !ids.empty?
@@ -302,7 +321,7 @@
   def self.find_by_login(login)
     # force string comparison to be case sensitive on MySQL
     type_cast = (ActiveRecord::Base.connection.adapter_name == 'MySQL') ? 'BINARY' : ''
-    
+
     # First look for an exact match
     user = first(:conditions => ["#{type_cast} login = ?", login])
     # Fail over to case-insensitive if none was found
@@ -313,21 +332,21 @@
     token = Token.find_by_value(key)
     token && token.user.active? ? token.user : nil
   end
-  
+
   def self.find_by_api_key(key)
     token = Token.find_by_action_and_value('api', key)
     token && token.user.active? ? token.user : nil
   end
-  
+
   # Makes find_by_mail case-insensitive
   def self.find_by_mail(mail)
     find(:first, :conditions => ["LOWER(mail) = ?", mail.to_s.downcase])
   end
-  
+
   def to_s
     name
   end
-  
+
   # Returns the current day according to user's time zone
   def today
     if time_zone.nil?
@@ -336,15 +355,15 @@
       Time.now.in_time_zone(time_zone).to_date
     end
   end
-  
+
   def logged?
     true
   end
-  
+
   def anonymous?
     !logged?
   end
-  
+
   # Return user's roles for project
   def roles_for_project(project)
     roles = []
@@ -365,16 +384,16 @@
     end
     roles
   end
-  
+
   # Return true if the user is a member of project
   def member_of?(project)
     !roles_for_project(project).detect {|role| role.member?}.nil?
   end
-  
+
   # Returns a hash of user's projects grouped by roles
   def projects_by_role
     return @projects_by_role if @projects_by_role
-    
+
     @projects_by_role = Hash.new {|h,k| h[k]=[]}
     memberships.each do |membership|
       membership.roles.each do |role|
@@ -384,10 +403,21 @@
     @projects_by_role.each do |role, projects|
       projects.uniq!
     end
-  
+
     @projects_by_role
   end
-  
+
+  # Returns true if user is arg or belongs to arg
+  def is_or_belongs_to?(arg)
+    if arg.is_a?(User)
+      self == arg
+    elsif arg.is_a?(Group)
+      arg.users.include?(self)
+    else
+      false
+    end
+  end
+
   # Return true if the user is allowed to do the specified action on a specific context
   # Action can be:
   # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
@@ -395,7 +425,7 @@
   # Context can be:
   # * a project : returns true if user is allowed to do the specified action on this project
   # * an array of projects : returns true if user is allowed on every project
-  # * nil with options[:global] set : check if user has at least one role allowed for this action, 
+  # * nil with options[:global] set : check if user has at least one role allowed for this action,
   #   or falls back to Non Member / Anonymous permissions depending if the user is logged
   def allowed_to?(action, context, options={}, &block)
     if context && context.is_a?(Project)
@@ -405,7 +435,7 @@
       return false unless context.allows_to?(action)
       # Admin users are authorized for anything else
       return true if admin?
-      
+
       roles = roles_for_project(context)
       return false unless roles
       roles.detect {|role|
@@ -423,7 +453,7 @@
     elsif options[:global]
       # Admin users are always authorized
       return true if admin?
-      
+
       # authorize if user has at least one role that has this permission
       roles = memberships.collect {|m| m.roles}.flatten.uniq
       roles << (self.logged? ? Role.non_member : Role.anonymous)
@@ -451,14 +481,14 @@
     'custom_field_values',
     'custom_fields',
     'identity_url'
-  
+
   safe_attributes 'status',
     'auth_source_id',
     :if => lambda {|user, current_user| current_user.admin?}
-  
+
   safe_attributes 'group_ids',
     :if => lambda {|user, current_user| current_user.admin? && !user.new_record?}
-  
+
   # Utility method to help check if a user should be notified about an
   # event.
   #
@@ -469,7 +499,7 @@
       true
     when 'selected'
       # user receives notifications for created/assigned issues on unselected projects
-      if object.is_a?(Issue) && (object.author == self || object.assigned_to == self)
+      if object.is_a?(Issue) && (object.author == self || is_or_belongs_to?(object.assigned_to))
         true
       else
         false
@@ -477,13 +507,13 @@
     when 'none'
       false
     when 'only_my_events'
-      if object.is_a?(Issue) && (object.author == self || object.assigned_to == self)
+      if object.is_a?(Issue) && (object.author == self || is_or_belongs_to?(object.assigned_to))
         true
       else
         false
       end
     when 'only_assigned'
-      if object.is_a?(Issue) && object.assigned_to == self
+      if object.is_a?(Issue) && is_or_belongs_to?(object.assigned_to)
         true
       else
         false
@@ -498,15 +528,15 @@
       false
     end
   end
-  
+
   def self.current=(user)
     @current_user = user
   end
-  
+
   def self.current
     @current_user ||= User.anonymous
   end
-  
+
   # Returns the anonymous user.  If the anonymous user does not exist, it is created.  There can be only
   # one anonymous user per database.
   def self.anonymous
@@ -531,23 +561,23 @@
       end
     end
   end
-  
+
   protected
-  
-  def validate
+
+  def validate_password_length
     # Password length validation based on setting
     if !password.nil? && password.size < Setting.password_min_length.to_i
       errors.add(:password, :too_short, :count => Setting.password_min_length.to_i)
     end
   end
-  
+
   private
-  
+
   # Removes references that are not handled by associations
   # Things that are not deleted are reassociated with the anonymous user
   def remove_references_before_destroy
     return if self.id.nil?
-    
+
     substitute = User.anonymous
     Attachment.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
     Comment.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
@@ -567,30 +597,30 @@
     WikiContent.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
     WikiContent::Version.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
   end
-    
+
   # Return password digest
   def self.hash_password(clear_password)
     Digest::SHA1.hexdigest(clear_password || "")
   end
-  
+
   # Returns a 128bits random salt as a hex string (32 chars long)
   def self.generate_salt
     ActiveSupport::SecureRandom.hex(16)
   end
-  
+
 end
 
 class AnonymousUser < User
-  
+
   def validate_on_create
     # There should be only one AnonymousUser in the database
-    errors.add_to_base 'An anonymous user already exists.' if AnonymousUser.find(:first)
+    errors.add :base, 'An anonymous user already exists.' if AnonymousUser.find(:first)
   end
-  
+
   def available_custom_fields
     []
   end
-  
+
   # Overrides a few properties
   def logged?; false end
   def admin; false end
@@ -598,7 +628,7 @@
   def mail; nil end
   def time_zone; nil end
   def rss_key; nil end
-  
+
   # Anonymous user can not be destroyed
   def destroy
     false