File: app/models/user.rb

Overview
Module Structure
Class Hierarchy
Code

Overview

Module Structure

  module: <Toplevel Module>
  class: User#20
includes
  SafeAttributes ( Redmine )
inherits from
  Principal   
has properties
constant: STATUS_ANONYMOUS #24
constant: STATUS_ACTIVE #25
constant: STATUS_REGISTERED #26
constant: STATUS_LOCKED #27
constant: USER_FORMATS #30
constant: MAIL_NOTIFICATION_OPTIONS #38
attribute: password [RW] #62
attribute: password_confirmation [RW] #62
attribute: last_before_login_on [RW] #63
constant: LOGIN_LENGTH_LIMIT #67
constant: MAIL_LENGTH_LIMIT #68
method: set_mail_notification #96
method: update_hashed_password #101
method: reload / 1 #108
method: mail= / 1 #114
method: identity_url= / 1 #118
class method: try_to_login / 2 #132
class method: try_to_autologin / 1 #166
class method: name_formatter / 1 #178
class method: fields_for_order_statement / 1 #188
method: name / 1 #194
method: active? #203
method: registered? #207
method: locked? #211
method: activate #215
method: register #219
method: lock #223
method: activate! #227
method: register! #231
method: lock! #235
method: check_password? / 1 #240
method: salt_password / 1 #250
method: change_password_allowed? #256
method: random_password #264
method: pref #273
method: time_zone #277
method: wants_comments_in_reverse_order? #281
method: rss_key #286
method: api_key #292
method: notified_projects_ids #298
method: notified_project_ids= / 1 #302
method: valid_notification_options (1/2) #309
class method: valid_notification_options (2/E) / 1 #314
class method: find_by_login / 1 #326
class method: find_by_rss_key / 1 #336
class method: find_by_api_key / 1 #341
class method: find_by_mail / 1 #347
class method: default_admin_account_changed? #352
method: to_s #356
method: today #361
method: logged? #369
method: anonymous? #373
method: roles_for_project / 1 #378
method: member_of? / 1 #399
method: projects_by_role #404
method: is_or_belongs_to? / 1 #421
method: allowed_to? / 4 #440
method: allowed_to_globally? / 3 #481
method: notify_about? / 1 #506
class method: current= / 1 #542
class method: current #546
class method: anonymous #552
class method: salt_unsalted_passwords! #564
method: validate_password_length #577
method: remove_references_before_destroy #588
class method: hash_password / 1 #612
class method: generate_salt #617
  class: AnonymousUser#623
inherits from
  User   
has properties
method: validate_anonymous_uniqueness #626
method: available_custom_fields #631
method: logged? #636
method: admin #637
method: name / 1 #638
method: mail #639
method: time_zone #640
method: rss_key #641
method: destroy #644

Class Hierarchy

Object ( Builtin-Module )
Base ( ActiveRecord )
Principal
User#20
  AnonymousUser    #623

Code

   1  # Redmine - project management software
   2  # Copyright (C) 2006-2011  Jean-Philippe Lang
   3  #
   4  # This program is free software; you can redistribute it and/or
   5  # modify it under the terms of the GNU General Public License
   6  # as published by the Free Software Foundation; either version 2
   7  # of the License, or (at your option) any later version.
   8  #
   9  # This program is distributed in the hope that it will be useful,
  10  # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  # GNU General Public License for more details.
  13  #
  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
  16  # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
  17 
  18  require "digest/sha1"
  19 
  20  class User < Principal
  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 
  29    # Different ways of displaying/sorting users
  30    USER_FORMATS = {
  31      :firstname_lastname => {:string => '#{firstname} #{lastname}', :order => %w(firstname lastname id)},
  32      :firstname => {:string => '#{firstname}', :order => %w(firstname id)},
  33      :lastname_firstname => {:string => '#{lastname} #{firstname}', :order => %w(lastname firstname id)},
  34      :lastname_coma_firstname => {:string => '#{lastname}, #{firstname}', :order => %w(lastname firstname id)},
  35      :username => {:string => '#{login}', :order => %w(login id)},
  36    }
  37 
  38    MAIL_NOTIFICATION_OPTIONS = [
  39      ['all', :label_user_mail_option_all],
  40      ['selected', :label_user_mail_option_selected],
  41      ['only_my_events', :label_user_mail_option_only_my_events],
  42      ['only_assigned', :label_user_mail_option_only_assigned],
  43      ['only_owner', :label_user_mail_option_only_owner],
  44      ['none', :label_user_mail_option_none]
  45    ]
  46 
  47    has_and_belongs_to_many :groups, :after_add => Proc.new {|user, group| group.user_added(user)},
  48                                     :after_remove => Proc.new {|user, group| group.user_removed(user)}
  49    has_many :changesets, :dependent => :nullify
  50    has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
  51    has_one :rss_token, :class_name => 'Token', :conditions => "action='feeds'"
  52    has_one :api_token, :class_name => 'Token', :conditions => "action='api'"
  53    belongs_to :auth_source
  54 
  55    # Active non-anonymous users scope
  56    named_scope :active, :conditions => "#{User.table_name}.status = #{STATUS_ACTIVE}"
  57    named_scope :logged, :conditions => "#{User.table_name}.status <> #{STATUS_ANONYMOUS}"
  58    named_scope :status, lambda {|arg| arg.blank? ? {} : {:conditions => {:status => arg.to_i}} }
  59 
  60    acts_as_customizable
  61 
  62    attr_accessor :password, :password_confirmation
  63    attr_accessor :last_before_login_on
  64    # Prevents unauthorized assignments
  65    attr_protected :login, :admin, :password, :password_confirmation, :hashed_password
  66 
  67    LOGIN_LENGTH_LIMIT = 60
  68    MAIL_LENGTH_LIMIT = 60
  69 
  70    validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
  71    validates_uniqueness_of :login, :if => Proc.new { |user| !user.login.blank? }, :case_sensitive => false
  72    validates_uniqueness_of :mail, :if => Proc.new { |user| !user.mail.blank? }, :case_sensitive => false
  73    # Login must contain lettres, numbers, underscores only
  74    validates_format_of :login, :with => /^[a-z0-9_\-@\.]*$/i
  75    validates_length_of :login, :maximum => LOGIN_LENGTH_LIMIT
  76    validates_length_of :firstname, :lastname, :maximum => 30
  77    validates_format_of :mail, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :allow_blank => true
  78    validates_length_of :mail, :maximum => MAIL_LENGTH_LIMIT, :allow_nil => true
  79    validates_confirmation_of :password, :allow_nil => true
  80    validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true
  81    validate :validate_password_length
  82 
  83    before_create :set_mail_notification
  84    before_save   :update_hashed_password
  85    before_destroy :remove_references_before_destroy
  86 
  87    named_scope :in_group, lambda {|group|
  88      group_id = group.is_a?(Group) ? group.id : group.to_i
  89      { :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] }
  90    }
  91    named_scope :not_in_group, lambda {|group|
  92      group_id = group.is_a?(Group) ? group.id : group.to_i
  93      { :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] }
  94    }
  95 
  96    def set_mail_notification
  97      self.mail_notification = Setting.default_notification_option if self.mail_notification.blank?
  98      true
  99    end
 100 
 101    def update_hashed_password
 102      # update hashed_password if password was set
 103      if self.password && self.auth_source_id.blank?
 104        salt_password(password)
 105      end
 106    end
 107 
 108    def reload(*args)
 109      @name = nil
 110      @projects_by_role = nil
 111      super
 112    end
 113 
 114    def mail=(arg)
 115      write_attribute(:mail, arg.to_s.strip)
 116    end
 117 
 118    def identity_url=(url)
 119      if url.blank?
 120        write_attribute(:identity_url, '')
 121      else
 122        begin
 123          write_attribute(:identity_url, OpenIdAuthentication.normalize_identifier(url))
 124        rescue OpenIdAuthentication::InvalidOpenId
 125          # Invlaid url, don't save
 126        end
 127      end
 128      self.read_attribute(:identity_url)
 129    end
 130 
 131    # Returns the user that matches provided login and password, or nil
 132    def self.try_to_login(login, password)
 133      # Make sure no one can sign in with an empty password
 134      return nil if password.to_s.empty?
 135      user = find_by_login(login)
 136      if user
 137        # user is already in local database
 138        return nil if !user.active?
 139        if user.auth_source
 140          # user has an external authentication method
 141          return nil unless user.auth_source.authenticate(login, password)
 142        else
 143          # authentication with local password
 144          return nil unless user.check_password?(password)
 145        end
 146      else
 147        # user is not yet registered, try to authenticate with available sources
 148        attrs = AuthSource.authenticate(login, password)
 149        if attrs
 150          user = new(attrs)
 151          user.login = login
 152          user.language = Setting.default_language
 153          if user.save
 154            user.reload
 155            logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source
 156          end
 157        end
 158      end
 159      user.update_attribute(:last_login_on, Time.now) if user && !user.new_record?
 160      user
 161    rescue => text
 162      raise text
 163    end
 164 
 165    # Returns the user who matches the given autologin +key+ or nil
 166    def self.try_to_autologin(key)
 167      tokens = Token.find_all_by_action_and_value('autologin', key)
 168      # Make sure there's only 1 token that matches the key
 169      if tokens.size == 1
 170        token = tokens.first
 171        if (token.created_on > Setting.autologin.to_i.day.ago) && token.user && token.user.active?
 172          token.user.update_attribute(:last_login_on, Time.now)
 173          token.user
 174        end
 175      end
 176    end
 177 
 178    def self.name_formatter(formatter = nil)
 179      USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname]
 180    end
 181 
 182    # Returns an array of fields names than can be used to make an order statement for users
 183    # according to how user names are displayed
 184    # Examples:
 185    #
 186    #   User.fields_for_order_statement              => ['users.login', 'users.id']
 187    #   User.fields_for_order_statement('authors')   => ['authors.login', 'authors.id']
 188    def self.fields_for_order_statement(table=nil)
 189      table ||= table_name
 190      name_formatter[:order].map {|field| "#{table}.#{field}"}
 191    end
 192 
 193    # Return user's full name for display
 194    def name(formatter = nil)
 195      f = self.class.name_formatter(formatter)
 196      if formatter
 197        eval('"' + f[:string] + '"')
 198      else
 199        @name ||= eval('"' + f[:string] + '"')
 200      end
 201    end
 202 
 203    def active?
 204      self.status == STATUS_ACTIVE
 205    end
 206 
 207    def registered?
 208      self.status == STATUS_REGISTERED
 209    end
 210 
 211    def locked?
 212      self.status == STATUS_LOCKED
 213    end
 214 
 215    def activate
 216      self.status = STATUS_ACTIVE
 217    end
 218 
 219    def register
 220      self.status = STATUS_REGISTERED
 221    end
 222 
 223    def lock
 224      self.status = STATUS_LOCKED
 225    end
 226 
 227    def activate!
 228      update_attribute(:status, STATUS_ACTIVE)
 229    end
 230 
 231    def register!
 232      update_attribute(:status, STATUS_REGISTERED)
 233    end
 234 
 235    def lock!
 236      update_attribute(:status, STATUS_LOCKED)
 237    end
 238 
 239    # Returns true if +clear_password+ is the correct user's password, otherwise false
 240    def check_password?(clear_password)
 241      if auth_source_id.present?
 242        auth_source.authenticate(self.login, clear_password)
 243      else
 244        User.hash_password("#{salt}#{User.hash_password clear_password}") == hashed_password
 245      end
 246    end
 247 
 248    # Generates a random salt and computes hashed_password for +clear_password+
 249    # The hashed password is stored in the following form: SHA1(salt + SHA1(password))
 250    def salt_password(clear_password)
 251      self.salt = User.generate_salt
 252      self.hashed_password = User.hash_password("#{salt}#{User.hash_password clear_password}")
 253    end
 254 
 255    # Does the backend storage allow this user to change their password?
 256    def change_password_allowed?
 257      return true if auth_source.nil?
 258      return auth_source.allow_password_changes?
 259    end
 260 
 261    # Generate and set a random password.  Useful for automated user creation
 262    # Based on Token#generate_token_value
 263    #
 264    def random_password
 265      chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
 266      password = ''
 267      40.times { |i| password << chars[rand(chars.size-1)] }
 268      self.password = password
 269      self.password_confirmation = password
 270      self
 271    end
 272 
 273    def pref
 274      self.preference ||= UserPreference.new(:user => self)
 275    end
 276 
 277    def time_zone
 278      @time_zone ||= (self.pref.time_zone.blank? ? nil : ActiveSupport::TimeZone[self.pref.time_zone])
 279    end
 280 
 281    def wants_comments_in_reverse_order?
 282      self.pref[:comments_sorting] == 'desc'
 283    end
 284 
 285    # Return user's RSS key (a 40 chars long string), used to access feeds
 286    def rss_key
 287      token = self.rss_token || Token.create(:user => self, :action => 'feeds')
 288      token.value
 289    end
 290 
 291    # Return user's API key (a 40 chars long string), used to access the API
 292    def api_key
 293      token = self.api_token || self.create_api_token(:action => 'api')
 294      token.value
 295    end
 296 
 297    # Return an array of project ids for which the user has explicitly turned mail notifications on
 298    def notified_projects_ids
 299      @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
 300    end
 301 
 302    def notified_project_ids=(ids)
 303      Member.update_all("mail_notification = #{connection.quoted_false}", ['user_id = ?', id])
 304      Member.update_all("mail_notification = #{connection.quoted_true}", ['user_id = ? AND project_id IN (?)', id, ids]) if ids && !ids.empty?
 305      @notified_projects_ids = nil
 306      notified_projects_ids
 307    end
 308 
 309    def valid_notification_options
 310      self.class.valid_notification_options(self)
 311    end
 312 
 313    # Only users that belong to more than 1 project can select projects for which they are notified
 314    def self.valid_notification_options(user=nil)
 315      # Note that @user.membership.size would fail since AR ignores
 316      # :include association option when doing a count
 317      if user.nil? || user.memberships.length < 1
 318        MAIL_NOTIFICATION_OPTIONS.reject {|option| option.first == 'selected'}
 319      else
 320        MAIL_NOTIFICATION_OPTIONS
 321      end
 322    end
 323 
 324    # Find a user account by matching the exact login and then a case-insensitive
 325    # version.  Exact matches will be given priority.
 326    def self.find_by_login(login)
 327      # First look for an exact match
 328      user = all(:conditions => {:login => login}).detect {|u| u.login == login}
 329      unless user
 330        # Fail over to case-insensitive if none was found
 331        user = first(:conditions => ["LOWER(login) = ?", login.to_s.downcase])
 332      end
 333      user
 334    end
 335 
 336    def self.find_by_rss_key(key)
 337      token = Token.find_by_value(key)
 338      token && token.user.active? ? token.user : nil
 339    end
 340 
 341    def self.find_by_api_key(key)
 342      token = Token.find_by_action_and_value('api', key)
 343      token && token.user.active? ? token.user : nil
 344    end
 345 
 346    # Makes find_by_mail case-insensitive
 347    def self.find_by_mail(mail)
 348      find(:first, :conditions => ["LOWER(mail) = ?", mail.to_s.downcase])
 349    end
 350 
 351    # Returns true if the default admin account can no longer be used
 352    def self.default_admin_account_changed?
 353      !User.active.find_by_login("admin").try(:check_password?, "admin")
 354    end
 355 
 356    def to_s
 357      name
 358    end
 359 
 360    # Returns the current day according to user's time zone
 361    def today
 362      if time_zone.nil?
 363        Date.today
 364      else
 365        Time.now.in_time_zone(time_zone).to_date
 366      end
 367    end
 368 
 369    def logged?
 370      true
 371    end
 372 
 373    def anonymous?
 374      !logged?
 375    end
 376 
 377    # Return user's roles for project
 378    def roles_for_project(project)
 379      roles = []
 380      # No role on archived projects
 381      return roles unless project && project.active?
 382      if logged?
 383        # Find project membership
 384        membership = memberships.detect {|m| m.project_id == project.id}
 385        if membership
 386          roles = membership.roles
 387        else
 388          @role_non_member ||= Role.non_member
 389          roles << @role_non_member
 390        end
 391      else
 392        @role_anonymous ||= Role.anonymous
 393        roles << @role_anonymous
 394      end
 395      roles
 396    end
 397 
 398    # Return true if the user is a member of project
 399    def member_of?(project)
 400      !roles_for_project(project).detect {|role| role.member?}.nil?
 401    end
 402 
 403    # Returns a hash of user's projects grouped by roles
 404    def projects_by_role
 405      return @projects_by_role if @projects_by_role
 406 
 407      @projects_by_role = Hash.new {|h,k| h[k]=[]}
 408      memberships.each do |membership|
 409        membership.roles.each do |role|
 410          @projects_by_role[role] << membership.project if membership.project
 411        end
 412      end
 413      @projects_by_role.each do |role, projects|
 414        projects.uniq!
 415      end
 416 
 417      @projects_by_role
 418    end
 419 
 420    # Returns true if user is arg or belongs to arg
 421    def is_or_belongs_to?(arg)
 422      if arg.is_a?(User)
 423        self == arg
 424      elsif arg.is_a?(Group)
 425        arg.users.include?(self)
 426      else
 427        false
 428      end
 429    end
 430 
 431    # Return true if the user is allowed to do the specified action on a specific context
 432    # Action can be:
 433    # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
 434    # * a permission Symbol (eg. :edit_project)
 435    # Context can be:
 436    # * a project : returns true if user is allowed to do the specified action on this project
 437    # * an array of projects : returns true if user is allowed on every project
 438    # * nil with options[:global] set : check if user has at least one role allowed for this action,
 439    #   or falls back to Non Member / Anonymous permissions depending if the user is logged
 440    def allowed_to?(action, context, options={}, &block)
 441      if context && context.is_a?(Project)
 442        # No action allowed on archived projects
 443        return false unless context.active?
 444        # No action allowed on disabled modules
 445        return false unless context.allows_to?(action)
 446        # Admin users are authorized for anything else
 447        return true if admin?
 448 
 449        roles = roles_for_project(context)
 450        return false unless roles
 451        roles.detect {|role|
 452          (context.is_public? || role.member?) &&
 453          role.allowed_to?(action) &&
 454          (block_given? ? yield(role, self) : true)
 455        }
 456      elsif context && context.is_a?(Array)
 457        # Authorize if user is authorized on every element of the array
 458        context.map do |project|
 459          allowed_to?(action, project, options, &block)
 460        end.inject do |memo,allowed|
 461          memo && allowed
 462        end
 463      elsif options[:global]
 464        # Admin users are always authorized
 465        return true if admin?
 466 
 467        # authorize if user has at least one role that has this permission
 468        roles = memberships.collect {|m| m.roles}.flatten.uniq
 469        roles << (self.logged? ? Role.non_member : Role.anonymous)
 470        roles.detect {|role|
 471          role.allowed_to?(action) &&
 472          (block_given? ? yield(role, self) : true)
 473        }
 474      else
 475        false
 476      end
 477    end
 478 
 479    # Is the user allowed to do the specified action on any project?
 480    # See allowed_to? for the actions and valid options.
 481    def allowed_to_globally?(action, options, &block)
 482      allowed_to?(action, nil, options.reverse_merge(:global => true), &block)
 483    end
 484 
 485    safe_attributes 'login',
 486      'firstname',
 487      'lastname',
 488      'mail',
 489      'mail_notification',
 490      'language',
 491      'custom_field_values',
 492      'custom_fields',
 493      'identity_url'
 494 
 495    safe_attributes 'status',
 496      'auth_source_id',
 497      :if => lambda {|user, current_user| current_user.admin?}
 498 
 499    safe_attributes 'group_ids',
 500      :if => lambda {|user, current_user| current_user.admin? && !user.new_record?}
 501 
 502    # Utility method to help check if a user should be notified about an
 503    # event.
 504    #
 505    # TODO: only supports Issue events currently
 506    def notify_about?(object)
 507      case mail_notification
 508      when 'all'
 509        true
 510      when 'selected'
 511        # user receives notifications for created/assigned issues on unselected projects
 512        if object.is_a?(Issue) && (object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was))
 513          true
 514        else
 515          false
 516        end
 517      when 'none'
 518        false
 519      when 'only_my_events'
 520        if object.is_a?(Issue) && (object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was))
 521          true
 522        else
 523          false
 524        end
 525      when 'only_assigned'
 526        if object.is_a?(Issue) && (is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was))
 527          true
 528        else
 529          false
 530        end
 531      when 'only_owner'
 532        if object.is_a?(Issue) && object.author == self
 533          true
 534        else
 535          false
 536        end
 537      else
 538        false
 539      end
 540    end
 541 
 542    def self.current=(user)
 543      @current_user = user
 544    end
 545 
 546    def self.current
 547      @current_user ||= User.anonymous
 548    end
 549 
 550    # Returns the anonymous user.  If the anonymous user does not exist, it is created.  There can be only
 551    # one anonymous user per database.
 552    def self.anonymous
 553      anonymous_user = AnonymousUser.find(:first)
 554      if anonymous_user.nil?
 555        anonymous_user = AnonymousUser.create(:lastname => 'Anonymous', :firstname => '', :mail => '', :login => '', :status => 0)
 556        raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
 557      end
 558      anonymous_user
 559    end
 560 
 561    # Salts all existing unsalted passwords
 562    # It changes password storage scheme from SHA1(password) to SHA1(salt + SHA1(password))
 563    # This method is used in the SaltPasswords migration and is to be kept as is
 564    def self.salt_unsalted_passwords!
 565      transaction do
 566        User.find_each(:conditions => "salt IS NULL OR salt = ''") do |user|
 567          next if user.hashed_password.blank?
 568          salt = User.generate_salt
 569          hashed_password = User.hash_password("#{salt}#{user.hashed_password}")
 570          User.update_all("salt = '#{salt}', hashed_password = '#{hashed_password}'", ["id = ?", user.id] )
 571        end
 572      end
 573    end
 574 
 575    protected
 576 
 577    def validate_password_length
 578      # Password length validation based on setting
 579      if !password.nil? && password.size < Setting.password_min_length.to_i
 580        errors.add(:password, :too_short, :count => Setting.password_min_length.to_i)
 581      end
 582    end
 583 
 584    private
 585 
 586    # Removes references that are not handled by associations
 587    # Things that are not deleted are reassociated with the anonymous user
 588    def remove_references_before_destroy
 589      return if self.id.nil?
 590 
 591      substitute = User.anonymous
 592      Attachment.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
 593      Comment.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
 594      Issue.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
 595      Issue.update_all 'assigned_to_id = NULL', ['assigned_to_id = ?', id]
 596      Journal.update_all ['user_id = ?', substitute.id], ['user_id = ?', id]
 597      JournalDetail.update_all ['old_value = ?', substitute.id.to_s], ["property = 'attr' AND prop_key = 'assigned_to_id' AND old_value = ?", id.to_s]
 598      JournalDetail.update_all ['value = ?', substitute.id.to_s], ["property = 'attr' AND prop_key = 'assigned_to_id' AND value = ?", id.to_s]
 599      Message.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
 600      News.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
 601      # Remove private queries and keep public ones
 602      ::Query.delete_all ['user_id = ? AND is_public = ?', id, false]
 603      ::Query.update_all ['user_id = ?', substitute.id], ['user_id = ?', id]
 604      TimeEntry.update_all ['user_id = ?', substitute.id], ['user_id = ?', id]
 605      Token.delete_all ['user_id = ?', id]
 606      Watcher.delete_all ['user_id = ?', id]
 607      WikiContent.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
 608      WikiContent::Version.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
 609    end
 610 
 611    # Return password digest
 612    def self.hash_password(clear_password)
 613      Digest::SHA1.hexdigest(clear_password || "")
 614    end
 615 
 616    # Returns a 128bits random salt as a hex string (32 chars long)
 617    def self.generate_salt
 618      Redmine::Utils.random_hex(16)
 619    end
 620 
 621  end
 622 
 623  class AnonymousUser < User
 624    validate :validate_anonymous_uniqueness, :on => :create
 625 
 626    def validate_anonymous_uniqueness
 627      # There should be only one AnonymousUser in the database
 628      errors.add :base, 'An anonymous user already exists.' if AnonymousUser.find(:first)
 629    end
 630 
 631    def available_custom_fields
 632      []
 633    end
 634 
 635    # Overrides a few properties
 636    def logged?; false end
 637    def admin; false end
 638    def name(*args); I18n.t(:label_user_anonymous) end
 639    def mail; nil end
 640    def time_zone; nil end
 641    def rss_key; nil end
 642 
 643    # Anonymous user can not be destroyed
 644    def destroy
 645      false
 646    end
 647  end