To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / app / models / user.rb @ 1591:63650ae64bf2

History | View | Annotate | Download (24.2 KB)

1
# Redmine - project management software
2
# Copyright (C) 2006-2014  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
  # Different ways of displaying/sorting users
24
  USER_FORMATS = {
25
    :firstname_lastname => {
26
        :string => '#{firstname} #{lastname}',
27
        :order => %w(firstname lastname id),
28
        :setting_order => 1
29
      },
30
    :firstname_lastinitial => {
31
        :string => '#{firstname} #{lastname.to_s.chars.first}.',
32
        :order => %w(firstname lastname id),
33
        :setting_order => 2
34
      },
35
    :firstinitial_lastname => {
36
        :string => '#{firstname.to_s.gsub(/(([[:alpha:]])[[:alpha:]]*\.?)/, \'\2.\')} #{lastname}',
37
        :order => %w(firstname lastname id),
38
        :setting_order => 2
39
      },
40
    :firstname => {
41
        :string => '#{firstname}',
42
        :order => %w(firstname id),
43
        :setting_order => 3
44
      },
45
    :lastname_firstname => {
46
        :string => '#{lastname} #{firstname}',
47
        :order => %w(lastname firstname id),
48
        :setting_order => 4
49
      },
50
    :lastname_coma_firstname => {
51
        :string => '#{lastname}, #{firstname}',
52
        :order => %w(lastname firstname id),
53
        :setting_order => 5
54
      },
55
    :lastname => {
56
        :string => '#{lastname}',
57
        :order => %w(lastname id),
58
        :setting_order => 6
59
      },
60
    :username => {
61
        :string => '#{login}',
62
        :order => %w(login id),
63
        :setting_order => 7
64
      },
65
  }
66

    
67
  MAIL_NOTIFICATION_OPTIONS = [
68
    ['all', :label_user_mail_option_all],
69
    ['selected', :label_user_mail_option_selected],
70
    ['only_my_events', :label_user_mail_option_only_my_events],
71
    ['only_assigned', :label_user_mail_option_only_assigned],
72
    ['only_owner', :label_user_mail_option_only_owner],
73
    ['none', :label_user_mail_option_none]
74
  ]
75

    
76
  has_and_belongs_to_many :groups,
77
                          :join_table   => "#{table_name_prefix}groups_users#{table_name_suffix}",
78
                          :after_add    => Proc.new {|user, group| group.user_added(user)},
79
                          :after_remove => Proc.new {|user, group| group.user_removed(user)}
80
  has_many :changesets, :dependent => :nullify
81
  has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
82
  has_one :rss_token, :class_name => 'Token', :conditions => "action='feeds'"
83
  has_one :api_token, :class_name => 'Token', :conditions => "action='api'"
84
  belongs_to :auth_source
85

    
86
  scope :logged, lambda { where("#{User.table_name}.status <> #{STATUS_ANONYMOUS}") }
87
  scope :status, lambda {|arg| where(arg.blank? ? nil : {:status => arg.to_i}) }
88

    
89
  has_one :ssamr_user_detail, :dependent => :destroy, :class_name => 'SsamrUserDetail'
90
  accepts_nested_attributes_for :ssamr_user_detail
91
  
92
  has_one :author
93

    
94
  acts_as_customizable
95

    
96
  attr_accessor :password, :password_confirmation, :generate_password
97
  attr_accessor :last_before_login_on
98
  # Prevents unauthorized assignments
99
  attr_protected :login, :admin, :password, :password_confirmation, :hashed_password
100

    
101
  LOGIN_LENGTH_LIMIT = 60
102
  MAIL_LENGTH_LIMIT = 60
103

    
104
  validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
105
  validates_uniqueness_of :login, :if => Proc.new { |user| user.login_changed? && user.login.present? }, :case_sensitive => false
106
  validates_uniqueness_of :mail, :if => Proc.new { |user| user.mail_changed? && user.mail.present? }, :case_sensitive => false
107

    
108
  # Login must contain letters, numbers, underscores only
109
  validates_format_of :login, :with => /\A[a-z0-9_\-@\.]*\z/i
110
  validates_length_of :login, :maximum => LOGIN_LENGTH_LIMIT
111
  validates_length_of :firstname, :lastname, :maximum => 30
112
  validates_format_of :mail, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, :allow_blank => true
113
  validates_length_of :mail, :maximum => MAIL_LENGTH_LIMIT, :allow_nil => true
114
  validates_confirmation_of :password, :allow_nil => true
115
  validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true
116
  validate :validate_password_length
117

    
118
  before_create :set_mail_notification
119
  before_save   :generate_password_if_needed, :update_hashed_password
120
  before_destroy :remove_references_before_destroy
121
  after_save :update_notified_project_ids
122

    
123
  validates_acceptance_of :terms_and_conditions, :on => :create, :message => :must_accept_terms_and_conditions
124

    
125
  scope :in_group, lambda {|group|
126
    group_id = group.is_a?(Group) ? group.id : group.to_i
127
    where("#{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)
128
  }
129
  scope :not_in_group, lambda {|group|
130
    group_id = group.is_a?(Group) ? group.id : group.to_i
131
    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)
132
  }
133
  scope :sorted, lambda { order(*User.fields_for_order_statement)}
134

    
135
  def set_mail_notification
136
    self.mail_notification = Setting.default_notification_option if self.mail_notification.blank?
137
    true
138
  end
139

    
140
  def update_hashed_password
141
    # update hashed_password if password was set
142
    if self.password && self.auth_source_id.blank?
143
      salt_password(password)
144
    end
145
  end
146

    
147
  alias :base_reload :reload
148
  def reload(*args)
149
    @name = nil
150
    @projects_by_role = nil
151
    @membership_by_project_id = nil
152
    @notified_projects_ids = nil
153
    @notified_projects_ids_changed = false
154
    @builtin_role = nil
155
    base_reload(*args)
156
  end
157

    
158
  def mail=(arg)
159
    write_attribute(:mail, arg.to_s.strip)
160
  end
161

    
162
  def description=(arg)
163
    write_attribute(:description, arg.to_s.strip)
164
  end
165
    
166
  def identity_url=(url)
167
    if url.blank?
168
      write_attribute(:identity_url, '')
169
    else
170
      begin
171
        write_attribute(:identity_url, OpenIdAuthentication.normalize_identifier(url))
172
      rescue OpenIdAuthentication::InvalidOpenId
173
        # Invalid url, don't save
174
      end
175
    end
176
    self.read_attribute(:identity_url)
177
  end
178

    
179
  # Returns the user that matches provided login and password, or nil
180
  def self.try_to_login(login, password, active_only=true)
181
    login = login.to_s
182
    password = password.to_s
183

    
184
    # Make sure no one can sign in with an empty login or password
185
    return nil if login.empty? || password.empty?
186
    user = find_by_login(login)
187
    if user
188
      # user is already in local database
189
      return nil unless user.check_password?(password)
190
      return nil if !user.active? && active_only
191
    else
192
      # user is not yet registered, try to authenticate with available sources
193
      attrs = AuthSource.authenticate(login, password)
194
      if attrs
195
        user = new(attrs)
196
        user.login = login
197
        user.language = Setting.default_language
198
        if user.save
199
          user.reload
200
          logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source
201
        end
202
      end
203
    end
204
    user.update_column(:last_login_on, Time.now) if user && !user.new_record? && user.active?
205
    user
206
  rescue => text
207
    raise text
208
  end
209

    
210
  # Returns the user who matches the given autologin +key+ or nil
211
  def self.try_to_autologin(key)
212
    user = Token.find_active_user('autologin', key, Setting.autologin.to_i)
213
    if user
214
      user.update_column(:last_login_on, Time.now)
215
      user
216
    end
217
  end
218

    
219
  def self.name_formatter(formatter = nil)
220
    USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname]
221
  end
222

    
223
  # Returns an array of fields names than can be used to make an order statement for users
224
  # according to how user names are displayed
225
  # Examples:
226
  #
227
  #   User.fields_for_order_statement              => ['users.login', 'users.id']
228
  #   User.fields_for_order_statement('authors')   => ['authors.login', 'authors.id']
229
  def self.fields_for_order_statement(table=nil)
230
    table ||= table_name
231
    name_formatter[:order].map {|field| "#{table}.#{field}"}
232
  end
233

    
234
  # Return user's full name for display
235
  def name(formatter = nil)
236
    f = self.class.name_formatter(formatter)
237
    if formatter
238
      eval('"' + f[:string] + '"')
239
    else
240
      @name ||= eval('"' + f[:string] + '"')
241
    end
242
  end
243

    
244
  def active?
245
    self.status == STATUS_ACTIVE
246
  end
247

    
248
  def registered?
249
    self.status == STATUS_REGISTERED
250
  end
251

    
252
  def locked?
253
    self.status == STATUS_LOCKED
254
  end
255

    
256
  def activate
257
    self.status = STATUS_ACTIVE
258
  end
259

    
260
  def register
261
    self.status = STATUS_REGISTERED
262
  end
263

    
264
  def lock
265
    self.status = STATUS_LOCKED
266
  end
267

    
268
  def activate!
269
    update_attribute(:status, STATUS_ACTIVE)
270
  end
271

    
272
  def register!
273
    update_attribute(:status, STATUS_REGISTERED)
274
  end
275

    
276
  def lock!
277
    update_attribute(:status, STATUS_LOCKED)
278
  end
279

    
280
  # Returns true if +clear_password+ is the correct user's password, otherwise false
281
  def check_password?(clear_password)
282
    if auth_source_id.present?
283
      auth_source.authenticate(self.login, clear_password)
284
    else
285
      User.hash_password("#{salt}#{User.hash_password clear_password}") == hashed_password
286
    end
287
  end
288

    
289
  # Generates a random salt and computes hashed_password for +clear_password+
290
  # The hashed password is stored in the following form: SHA1(salt + SHA1(password))
291
  def salt_password(clear_password)
292
    self.salt = User.generate_salt
293
    self.hashed_password = User.hash_password("#{salt}#{User.hash_password clear_password}")
294
  end
295

    
296
  # Does the backend storage allow this user to change their password?
297
  def change_password_allowed?
298
    return true if auth_source.nil?
299
    return auth_source.allow_password_changes?
300
  end
301

    
302
  def must_change_password?
303
    must_change_passwd? && change_password_allowed?
304
  end
305

    
306
  def generate_password?
307
    generate_password == '1' || generate_password == true
308
  end
309

    
310
  # Generate and set a random password on given length
311
  def random_password(length=40)
312
    chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
313
    chars -= %w(0 O 1 l)
314
    password = ''
315
    length.times {|i| password << chars[SecureRandom.random_number(chars.size)] }
316
    self.password = password
317
    self.password_confirmation = password
318
    self
319
  end
320

    
321
  def pref
322
    self.preference ||= UserPreference.new(:user => self)
323
  end
324

    
325
  def time_zone
326
    @time_zone ||= (self.pref.time_zone.blank? ? nil : ActiveSupport::TimeZone[self.pref.time_zone])
327
  end
328

    
329
  def force_default_language?
330
    Setting.force_default_language_for_loggedin?
331
  end
332

    
333
  def language
334
    if force_default_language?
335
      Setting.default_language
336
    else
337
      super
338
    end
339
  end
340

    
341
  def wants_comments_in_reverse_order?
342
    self.pref[:comments_sorting] == 'desc'
343
  end
344

    
345
  # Return user's RSS key (a 40 chars long string), used to access feeds
346
  def rss_key
347
    if rss_token.nil?
348
      create_rss_token(:action => 'feeds')
349
    end
350
    rss_token.value
351
  end
352

    
353
  # Return user's API key (a 40 chars long string), used to access the API
354
  def api_key
355
    if api_token.nil?
356
      create_api_token(:action => 'api')
357
    end
358
    api_token.value
359
  end
360

    
361
  # Return an array of project ids for which the user has explicitly turned mail notifications on
362
  def notified_projects_ids
363
    @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
364
  end
365

    
366
  def notified_project_ids=(ids)
367
    @notified_projects_ids_changed = true
368
    @notified_projects_ids = ids
369
  end
370

    
371
  # Updates per project notifications (after_save callback)
372
  def update_notified_project_ids
373
    if @notified_projects_ids_changed
374
      ids = (mail_notification == 'selected' ? Array.wrap(notified_projects_ids).reject(&:blank?) : [])
375
      members.update_all(:mail_notification => false)
376
      members.where(:project_id => ids).update_all(:mail_notification => true) if ids.any?
377
    end
378
  end
379
  private :update_notified_project_ids
380

    
381
  def valid_notification_options
382
    self.class.valid_notification_options(self)
383
  end
384

    
385
  # Only users that belong to more than 1 project can select projects for which they are notified
386
  def self.valid_notification_options(user=nil)
387
    # Note that @user.membership.size would fail since AR ignores
388
    # :include association option when doing a count
389
    if user.nil? || user.memberships.length < 1
390
      MAIL_NOTIFICATION_OPTIONS.reject {|option| option.first == 'selected'}
391
    else
392
      MAIL_NOTIFICATION_OPTIONS
393
    end
394
  end
395

    
396
  # Find a user account by matching the exact login and then a case-insensitive
397
  # version.  Exact matches will be given priority.
398
  def self.find_by_login(login)
399
    login = Redmine::CodesetUtil.replace_invalid_utf8(login.to_s)
400
    if login.present?
401
      # First look for an exact match
402
      user = where(:login => login).detect {|u| u.login == login}
403
      unless user
404
        # Fail over to case-insensitive if none was found
405
        user = where("LOWER(login) = ?", login.downcase).first
406
      end
407
      user
408
    end
409
  end
410

    
411
  def self.find_by_rss_key(key)
412
    Token.find_active_user('feeds', key)
413
  end
414

    
415
  def self.find_by_api_key(key)
416
    Token.find_active_user('api', key)
417
  end
418

    
419
  # Makes find_by_mail case-insensitive
420
  def self.find_by_mail(mail)
421
    where("LOWER(mail) = ?", mail.to_s.downcase).first
422
  end
423

    
424
  # Returns true if the default admin account can no longer be used
425
  def self.default_admin_account_changed?
426
    !User.active.find_by_login("admin").try(:check_password?, "admin")
427
  end
428

    
429
  def to_s
430
    name
431
  end
432

    
433
  CSS_CLASS_BY_STATUS = {
434
    STATUS_ANONYMOUS  => 'anon',
435
    STATUS_ACTIVE     => 'active',
436
    STATUS_REGISTERED => 'registered',
437
    STATUS_LOCKED     => 'locked'
438
  }
439

    
440
  def css_classes
441
    "user #{CSS_CLASS_BY_STATUS[status]}"
442
  end
443

    
444
  # Returns the current day according to user's time zone
445
  def today
446
    if time_zone.nil?
447
      Date.today
448
    else
449
      Time.now.in_time_zone(time_zone).to_date
450
    end
451
  end
452

    
453
  # Returns the day of +time+ according to user's time zone
454
  def time_to_date(time)
455
    if time_zone.nil?
456
      time.to_date
457
    else
458
      time.in_time_zone(time_zone).to_date
459
    end
460
  end
461

    
462
  def logged?
463
    true
464
  end
465

    
466
  def anonymous?
467
    !logged?
468
  end
469

    
470
  # Returns user's membership for the given project
471
  # or nil if the user is not a member of project
472
  def membership(project)
473
    project_id = project.is_a?(Project) ? project.id : project
474

    
475
    @membership_by_project_id ||= Hash.new {|h, project_id|
476
      h[project_id] = memberships.where(:project_id => project_id).first
477
    }
478
    @membership_by_project_id[project_id]
479
  end
480

    
481
  # Returns the user's bult-in role
482
  def builtin_role
483
    @builtin_role ||= Role.non_member
484
  end
485

    
486
  # Return user's roles for project
487
  def roles_for_project(project)
488
    roles = []
489
    # No role on archived projects
490
    return roles if project.nil? || project.archived?
491
    if membership = membership(project)
492
      roles = membership.roles
493
    else
494
      roles << builtin_role
495
    end
496
    roles
497
  end
498

    
499
  # Return true if the user is a member of project
500
  def member_of?(project)
501
    projects.to_a.include?(project)
502
  end
503

    
504
  # Returns a hash of user's projects grouped by roles
505
  def projects_by_role
506
    return @projects_by_role if @projects_by_role
507

    
508
    @projects_by_role = Hash.new([])
509
    memberships.each do |membership|
510
      if membership.project
511
        membership.roles.each do |role|
512
          @projects_by_role[role] = [] unless @projects_by_role.key?(role)
513
          @projects_by_role[role] << membership.project
514
        end
515
      end
516
    end
517
    @projects_by_role.each do |role, projects|
518
      projects.uniq!
519
    end
520

    
521
    @projects_by_role
522
  end
523

    
524
  # Returns true if user is arg or belongs to arg
525
  def is_or_belongs_to?(arg)
526
    if arg.is_a?(User)
527
      self == arg
528
    elsif arg.is_a?(Group)
529
      arg.users.include?(self)
530
    else
531
      false
532
    end
533
  end
534

    
535
  # Return true if the user is allowed to do the specified action on a specific context
536
  # Action can be:
537
  # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
538
  # * a permission Symbol (eg. :edit_project)
539
  # Context can be:
540
  # * a project : returns true if user is allowed to do the specified action on this project
541
  # * an array of projects : returns true if user is allowed on every project
542
  # * nil with options[:global] set : check if user has at least one role allowed for this action,
543
  #   or falls back to Non Member / Anonymous permissions depending if the user is logged
544
  def allowed_to?(action, context, options={}, &block)
545
    if context && context.is_a?(Project)
546
      return false unless context.allows_to?(action)
547
      # Admin users are authorized for anything else
548
      return true if admin?
549

    
550
      roles = roles_for_project(context)
551
      return false unless roles
552
      roles.any? {|role|
553
        (context.is_public? || role.member?) &&
554
        role.allowed_to?(action) &&
555
        (block_given? ? yield(role, self) : true)
556
      }
557
    elsif context && context.is_a?(Array)
558
      if context.empty?
559
        false
560
      else
561
        # Authorize if user is authorized on every element of the array
562
        context.map {|project| allowed_to?(action, project, options, &block)}.reduce(:&)
563
      end
564
    elsif options[:global]
565
      # Admin users are always authorized
566
      return true if admin?
567

    
568
      # authorize if user has at least one role that has this permission
569
      roles = memberships.collect {|m| m.roles}.flatten.uniq
570
      roles << (self.logged? ? Role.non_member : Role.anonymous)
571
      roles.any? {|role|
572
        role.allowed_to?(action) &&
573
        (block_given? ? yield(role, self) : true)
574
      }
575
    else
576
      false
577
    end
578
  end
579

    
580
  # Is the user allowed to do the specified action on any project?
581
  # See allowed_to? for the actions and valid options.
582
  def allowed_to_globally?(action, options, &block)
583
    allowed_to?(action, nil, options.reverse_merge(:global => true), &block)
584
  end
585

    
586
  # Returns true if the user is allowed to delete the user's own account
587
  def own_account_deletable?
588
    Setting.unsubscribe? &&
589
      (!admin? || User.active.where("admin = ? AND id <> ?", true, id).exists?)
590
  end
591

    
592
  safe_attributes 'login',
593
    'firstname',
594
    'lastname',
595
    'mail',
596
    'mail_notification',
597
    'notified_project_ids',
598
    'language',
599
    'custom_field_values',
600
    'custom_fields',
601
    'identity_url'
602

    
603
  safe_attributes 'status',
604
    'auth_source_id',
605
    'generate_password',
606
    'must_change_passwd',
607
    :if => lambda {|user, current_user| current_user.admin?}
608

    
609
  safe_attributes 'group_ids',
610
    :if => lambda {|user, current_user| current_user.admin? && !user.new_record?}
611

    
612
  # Utility method to help check if a user should be notified about an
613
  # event.
614
  #
615
  # TODO: only supports Issue events currently
616
  def notify_about?(object)
617
    if mail_notification == 'all'
618
      true
619
    elsif mail_notification.blank? || mail_notification == 'none'
620
      false
621
    else
622
      case object
623
      when Issue
624
        case mail_notification
625
        when 'selected', 'only_my_events'
626
          # user receives notifications for created/assigned issues on unselected projects
627
          object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was)
628
        when 'only_assigned'
629
          is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was)
630
        when 'only_owner'
631
          object.author == self
632
        end
633
      when News
634
        # always send to project members except when mail_notification is set to 'none'
635
        true
636
      end
637
    end
638
  end
639

    
640
  def self.current=(user)
641
    Thread.current[:current_user] = user
642
  end
643

    
644
  def self.current
645
    Thread.current[:current_user] ||= User.anonymous
646
  end
647

    
648
  # Returns the anonymous user.  If the anonymous user does not exist, it is created.  There can be only
649
  # one anonymous user per database.
650
  def self.anonymous
651
    anonymous_user = AnonymousUser.first
652
    if anonymous_user.nil?
653
      anonymous_user = AnonymousUser.create(:lastname => 'Anonymous', :firstname => '', :mail => '', :login => '', :status => 0)
654
      raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
655
    end
656
    anonymous_user
657
  end
658

    
659
  # Salts all existing unsalted passwords
660
  # It changes password storage scheme from SHA1(password) to SHA1(salt + SHA1(password))
661
  # This method is used in the SaltPasswords migration and is to be kept as is
662
  def self.salt_unsalted_passwords!
663
    transaction do
664
      User.where("salt IS NULL OR salt = ''").find_each do |user|
665
        next if user.hashed_password.blank?
666
        salt = User.generate_salt
667
        hashed_password = User.hash_password("#{salt}#{user.hashed_password}")
668
        User.where(:id => user.id).update_all(:salt => salt, :hashed_password => hashed_password)
669
      end
670
    end
671
  end
672

    
673
  protected
674

    
675
  def validate_password_length
676
    return if password.blank? && generate_password?
677
    # Password length validation based on setting
678
    if !password.nil? && password.size < Setting.password_min_length.to_i
679
      errors.add(:password, :too_short, :count => Setting.password_min_length.to_i)
680
    end
681
  end
682

    
683
  private
684

    
685
  def generate_password_if_needed
686
    if generate_password? && auth_source.nil?
687
      length = [Setting.password_min_length.to_i + 2, 10].max
688
      random_password(length)
689
    end
690
  end
691

    
692
  # Removes references that are not handled by associations
693
  # Things that are not deleted are reassociated with the anonymous user
694
  def remove_references_before_destroy
695
    return if self.id.nil?
696

    
697
    substitute = User.anonymous
698
    Attachment.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id]) 
699
    Comment.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
700
    Issue.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
701
    Issue.where(['assigned_to_id = ?', id]).update_all('assigned_to_id = NULL')
702
    Journal.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id]) 
703
    JournalDetail.
704
      where(["property = 'attr' AND prop_key = 'assigned_to_id' AND old_value = ?", id.to_s]).
705
      update_all(['old_value = ?', substitute.id.to_s])
706
    JournalDetail.
707
      where(["property = 'attr' AND prop_key = 'assigned_to_id' AND value = ?", id.to_s]).
708
      update_all(['value = ?', substitute.id.to_s]) 
709
    Message.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
710
    News.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
711
    # Remove private queries and keep public ones
712
    ::Query.delete_all ['user_id = ? AND visibility = ?', id, ::Query::VISIBILITY_PRIVATE]
713
    ::Query.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
714
    TimeEntry.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
715
    Token.delete_all ['user_id = ?', id]
716
    Watcher.delete_all ['user_id = ?', id]
717
    WikiContent.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
718
    WikiContent::Version.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
719
  end
720

    
721
  # Return password digest
722
  def self.hash_password(clear_password)
723
    Digest::SHA1.hexdigest(clear_password || "")
724
  end
725

    
726
  # Returns a 128bits random salt as a hex string (32 chars long)
727
  def self.generate_salt
728
    Redmine::Utils.random_hex(16)
729
  end
730

    
731
end
732

    
733
class AnonymousUser < User
734
  validate :validate_anonymous_uniqueness, :on => :create
735

    
736
  def validate_anonymous_uniqueness
737
    # There should be only one AnonymousUser in the database
738
    errors.add :base, 'An anonymous user already exists.' if AnonymousUser.exists?
739
  end
740

    
741
  def available_custom_fields
742
    []
743
  end
744

    
745
  # Overrides a few properties
746
  def logged?; false end
747
  def admin; false end
748
  def name(*args); I18n.t(:label_user_anonymous) end
749
  def mail; nil end
750
  def time_zone; nil end
751
  def rss_key; nil end
752

    
753
  def pref
754
    UserPreference.new(:user => self)
755
  end
756

    
757
  # Returns the user's bult-in role
758
  def builtin_role
759
    @builtin_role ||= Role.anonymous
760
  end
761

    
762
  def membership(*args)
763
    nil
764
  end
765

    
766
  def member_of?(*args)
767
    false
768
  end
769

    
770
  # Anonymous user can not be destroyed
771
  def destroy
772
    false
773
  end
774
end